Sign Up

Have an account? Sign In Now

Sign In

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask question.

Forgot Password?

Need An Account, Sign Up Here

You must login to ask question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Sign InSign Up

Softans

Softans Logo Softans Logo
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Ghulam Nabi

Ask Ghulam Nabi
1Follower
130Questions
Home/ Ghulam Nabi/Best Answers
  • About
  • Questions
  • Polls
  • Answers
  • Best Answers
  • Groups
  1. Asked: May 25, 2023

    Bottle server with WebSocket (without other third-party libraries)

    Ghulam Nabi
    Added an answer on May 25, 2023 at 12:05 pm

    Currently, as of my knowledge cutoff in September 2021, the Bottle framework itself does not provide native WebSocket support. To handle WebSocket connections in Bottle without relying on third-party libraries, you would need to implement the WebSocket protocol manually. The WebSocket protocol involRead more

    Currently, as of my knowledge cutoff in September 2021, the Bottle framework itself does not provide native WebSocket support. To handle WebSocket connections in Bottle without relying on third-party libraries, you would need to implement the WebSocket protocol manually.

    The WebSocket protocol involves an initial HTTP handshake and then transitioning to a persistent connection between the client and the server. This process requires managing the low-level details of the protocol, which can be quite complex.

    However, I can provide you with an example using the Python socket module to create a simple WebSocket server within your Bottle application. Please note that this approach is a basic demonstration and may not be suitable for production use. Here’s an example of how you could modify your code:

    import bottle
    import hashlib
    import base64
    import struct
    import socket
    
    app = bottle.Bottle()
    
    IrinaRocuoumsAppow.route("/")
    def index():
        return bottle.static_file("index.html", root=".")
    
    IrinaRocuoumsAppow.route("/ws")
    def ws():
        connection = bottle.request.environ.get('wsgi.websocket')
        if not connection:
            bottle.abort(400, 'Expected WebSocket request.')
    
        client_socket = socket.fromfd(connection.fileno(), socket.AF_INET, socket.SOCK_STREAM)
        key = bottle.request.get_header('Sec-WebSocket-Key')
        accept_key = base64.b64encode(hashlib.sha1(key.encode() + b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest())
    
        headers = [
            'HTTP/1.1 101 Switching Protocols',
            'Upgrade: websocket',
            'Connection: Upgrade',
            'Sec-WebSocket-Accept: ' + accept_key.decode(),
            '\r\n'
        ]
    
        client_socket.sendall('\r\n'.join(headers).encode())
    
        while True:
            try:
                # Read the message length and handle various cases
                data = client_socket.recv(2)
                opcode = data[0] & 0x0F
                length = data[1] & 0x7F
    
                if length == 126:
                    data = client_socket.recv(2)
                    length = struct.unpack('>H', data)[0]
                elif length == 127:
                    data = client_socket.recv(8)
                    length = struct.unpack('>Q', data)[0]
    
                mask = client_socket.recv(4)
                masked_data = client_socket.recv(length)
    
                message = bytearray()
                for i in range(length):
                    message.append(masked_data[i] ^ mask[i % 4])
    
                # Echo back the received message
                client_socket.sendall(bytearray([0x81, len(message)]) + message)
            except:
                break
    
        client_socket.close()
    
    IrinaRocuoumsAppow.route('/<filename:path>')
    def serve_static(filename):
        return bottle.static_file(filename, root='.')
    
    bottle.run(app=app, server='paste', port=5000, debug=True)
    

    In this example, we manually handle the WebSocket handshake by constructing the necessary HTTP headers and sending them back to the client. The ws() function reads and sends WebSocket messages using the low-level socket operations.

    Keep in mind that manually implementing the WebSocket protocol can be error-prone and may not support all the features provided by third-party WebSocket libraries. If possible, using a well-maintained library like gevent-websocket or websocket-server is generally recommended for WebSocket functionality in a Bottle application.

    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
  2. Asked: May 19, 2023

    how to disable button clicks via .preventDefault()

    Ghulam Nabi
    Added an answer on May 19, 2023 at 7:10 am

    The preventDefault() method is used to prevent the default behavior of an event, such as submitting a form or following a link. However, it does not disable the button or make it unclickable. It only prevents the default action associated with the event. If you want to disable the button and make itRead more

    The preventDefault() method is used to prevent the default behavior of an event, such as submitting a form or following a link. However, it does not disable the button or make it unclickable. It only prevents the default action associated with the event.

    If you want to disable the button and make it unclickable, you can use a reactive variable to control the button’s state. Here’s an updated code snippet that demonstrates how to achieve this:

    <template>
      <div>
        <button v-on:click="handleClick" :disabled="isButtonDisabled">warn</button>
      </div>
    </template>
    
    <script>
    import { ref } from 'vue';
    
    export default {
      name: 'App',
      setup() {
        const isButtonDisabled = ref(false);
    
        const handleClick = (event) => {
          event.preventDefault();
          if (!isButtonDisabled.value) {
            // Perform your desired action here
            console.log('Button clicked!');
          }
        };
    
        return {
          isButtonDisabled,
          handleClick,
        };
      },
    };
    </script>
    

    In this example, we use the isButtonDisabled reactive variable to control the disabled attribute of the button. By default, the button is not disabled (isButtonDisabled is false). When the button is clicked, the handleClick function is triggered. We check if the button is not disabled before performing any action. By calling event.preventDefault(), we prevent the default behavior of the click event.

    To disable the button, you can set isButtonDisabled to true in your code when necessary. For example, if you want to disable the button after the first click, you can modify the handleClick function as follows:

    const handleClick = (event) => {
      event.preventDefault();
      if (!isButtonDisabled.value) {
        // Perform your desired action here
        console.log('Button clicked!');
        isButtonDisabled.value = true; // Disable the button
      }
    };
    

    By setting isButtonDisabled.value to true, the button will become disabled, and subsequent clicks will not trigger the action inside the if statement.

    Remember to import the necessary dependencies (ref) and adjust the component name and any other dependencies according to your specific setup.

    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
  3. Asked: May 19, 2023

    How to create a small python code to get a list of participants of a teams call?

    Ghulam Nabi
    Added an answer on May 19, 2023 at 7:07 am

    To retrieve the list of participants in an ongoing Microsoft Teams call using Python, you can utilize the Microsoft Graph API with the help of the requests library. Here's a code snippet that demonstrates how to achieve this: import requests # Microsoft Graph API endpoint for retrieving call particiRead more

    To retrieve the list of participants in an ongoing Microsoft Teams call using Python, you can utilize the Microsoft Graph API with the help of the requests library. Here’s a code snippet that demonstrates how to achieve this:

    import requests
    
    # Microsoft Graph API endpoint for retrieving call participants
    call_participants_url = 'https://graph.microsoft.com/v1.0/communications/calls/{call_id}/participants'
    
    # Azure AD application credentials
    client_id = 'your_client_id'
    client_secret = 'your_client_secret'
    tenant_id = 'your_tenant_id'
    
    # Get an access token using client credentials flow
    token_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token'
    token_payload = {
        'client_id': client_id,
        'client_secret': client_secret,
        'scope': 'https://graph.microsoft.com/.default',
        'grant_type': 'client_credentials'
    }
    
    token_response = requests.post(token_url, data=token_payload)
    access_token = token_response.json().get('access_token')
    
    # Make a GET request to obtain the list of participants
    call_id = 'your_call_id'
    headers = {'Authorization': f'Bearer {access_token}'}
    participants_response = requests.get(call_participants_url.format(call_id=call_id), headers=headers)
    participants = participants_response.json()
    
    # Process the participant data
    for participant in participants['value']:
        print(participant['displayName'])
    

    Before running the code, make sure you replace the following placeholders with your own values:

    • your_client_id: Your Azure AD application ID (client ID).
    • your_client_secret: Your Azure AD application client secret.
    • your_tenant_id: Your Azure AD tenant ID.
    • your_call_id: The ID of the Teams call you want to retrieve participants for.

    Please note that you need the necessary permissions and valid Azure AD application credentials to access the Microsoft Graph API. Also, ensure that you have the requests library installed (pip install requests) to make HTTP requests

    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
  4. Asked: May 19, 2023

    undeclared variable in a do-while loop in C

    Ghulam Nabi
    Added an answer on May 19, 2023 at 7:04 am

    In C, variable declarations should be placed outside the loop in which they are used. In your code, the variable sp is declared inside the do-while loop, making it inaccessible in the condition part of the loop. To fix the error, you need to declare the variable sp before the do-while loop: int sp;Read more

    In C, variable declarations should be placed outside the loop in which they are used. In your code, the variable sp is declared inside the do-while loop, making it inaccessible in the condition part of the loop.

    To fix the error, you need to declare the variable sp before the do-while loop:

    int sp; // Declare the variable before the loop
    
    do
    {
        sp = get_int("Enter the start size of llama population:");
    }
    while (sp >= 9);
    

    By moving the declaration of sp outside the loop, it becomes accessible in both the loop body and the condition part of the loop.

    Now, the code will prompt the user to enter a valid number (greater or equal to 9) until the condition is satisfied.

    Make sure you have the necessary header files included and the get_int function defined or declared correctly before using it in your code.

    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
  5. Asked: May 19, 2023

    Cypress use clock between each test without visit again

    Ghulam Nabi
    Added an answer on May 19, 2023 at 6:59 am

    It seems that the issue lies in the way Cypress handles the setInterval function and the clock. Currently, Cypress's cy.tick() function is not designed to advance the clock for intervals set using setInterval. To work around this limitation, you can use the cy.wait() command instead of cy.tick() toRead more

    It seems that the issue lies in the way Cypress handles the setInterval function and the clock. Currently, Cypress’s cy.tick() function is not designed to advance the clock for intervals set using setInterval.

    To work around this limitation, you can use the cy.wait() command instead of cy.tick() to advance the clock. Here’s an updated example of how you can modify your tests:

    describe('test clock', () => {
      beforeEach(() => {
        cy.clock(); // Initialize the clock
        cy.visit('http://localhost:3000/#/index/dashboardview2');
      });
    
      it('test1', () => {
        cy.get('[data-test="number"]').should('have.text', '0');
        cy.wait(1000); // Advance the clock by 1 second using cy.wait()
        cy.get('[data-test="number"]').should('have.text', '1');
      });
    
      it('test2', () => {
        cy.get('[data-test="number"]').should('have.text', '0');
        cy.wait(2000); // Advance the clock by 2 seconds using cy.wait()
        cy.get('[data-test="number"]').should('have.text', '2');
      });
    });
    

    By replacing cy.tick() with cy.wait(), you can manually control the clock advancement and verify the expected behavior in your component.

    Please give this approach a try and let me know if it resolves the issue for you.

    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
  6. Asked: May 18, 2023

    How to exclude @Bean from library configuration

    Ghulam Nabi
    Added an answer on May 18, 2023 at 11:23 am

    @Configuration @Import({ClientConfig.class}) public class ValidatorsConfiguration { @Bean @Conditional(ExcludeBeanCondition.class) public Parser excludedParser() { // Return a dummy instance or null if you want to exclude the bean return null; } // Other beans and configuration... } In the example aRead more

    @Configuration
    @Import({ClientConfig.class})
    public class ValidatorsConfiguration {
        
        @Bean
        @Conditional(ExcludeBeanCondition.class)
        public Parser excludedParser() {
            // Return a dummy instance or null if you want to exclude the bean
            return null;
        }
    
        // Other beans and configuration...
    }
    

    In the example above, a new Parser bean called excludedParser() is defined. The @Conditional(ExcludeBeanCondition.class) annotation is used to conditionally include or exclude this bean based on the implementation of the ExcludeBeanCondition class.

    You need to create the ExcludeBeanCondition class implementing the Condition interface. Here’s an example implementation that excludes the bean based on a specific condition:

    public class ExcludeBeanCondition implements Condition {
    
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            // Implement your custom logic here to determine if the bean should be excluded
            // Return true to exclude the bean, false to include it
            // You can access environment variables, properties, etc., using the ConditionContext
            
            // Example: Exclude the bean if a specific property is set
            String excludeProperty = context.getEnvironment().getProperty("exclude.bean");
            return "true".equalsIgnoreCase(excludeProperty);
        }
    }
    

    In the ExcludeBeanCondition class, you can define your custom logic to determine if the bean should be excluded. In this example, the bean will be excluded if the property exclude.bean is set to "true".

    Remember to adjust the logic in ExcludeBeanCondition according to your specific conditions for excluding beans.

    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
  7. Asked: May 18, 2023

    How can I use another df to calculate a new variable in my df, using time intervals?

    Ghulam Nabi
    Added an answer on May 18, 2023 at 11:18 am

    To calculate the new variable in your dataframe based on time intervals and information from another dataframe, you can use a combination of filtering and aggregation functions. Here's an example of how you can approach this task: library(dplyr) # Assuming your dataframes are named 'exposition' andRead more

    To calculate the new variable in your dataframe based on time intervals and information from another dataframe, you can use a combination of filtering and aggregation functions. Here’s an example of how you can approach this task:

    library(dplyr)
    
    # Assuming your dataframes are named 'exposition' and 'pregnancy_interval'
    
    # Initialize a new column for the pollution dataframe
    pollution$sum <- 0
    
    # Loop over each row in the exposition dataframe
    for (i in 1:nrow(exposition)) {
      # Get the code_muni and time interval for the current row in exposition
      code_muni <- exposition$code_muni[i]
      dt_concep <- exposition$dt_concep[i]
      data_nasc <- exposition$data_nasc[i]
      
      # Filter the pollution dataframe based on the code_muni and time interval
      filtered_data <- pollution %>%
        filter(code_muni == code_muni,
               date >= dt_concep,
               date < data_nasc)
      
      # Calculate the sum for the specified time interval
      sum_value <- sum(filtered_data$neg_to_7)
      
      # Update the 'sum' column in the pollution dataframe for the matching rows
      pollution$sum[code_muni == code_muni &
                    pollution$date >= dt_concep &
                    pollution$date < data_nasc] <- sum_value
    }
    

    This code loops over each row in the exposition dataframe and performs the following steps:

    1. Extracts the code_muni, dt_concep, and data_nasc values from the current row.
    2. Filters the pollution dataframe based on the code_muni and the time interval.
    3. Calculates the sum of the neg_to_7 values for the filtered data.
    4. Updates the sum column in the pollution dataframe for the matching rows.

    Note that this approach can be time-consuming if your dataframes are large. Consider optimizing it if needed, such as by using vectorized operations or parallel processing, depending on the size and complexity of your data.

    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
  8. Asked: May 18, 2023

    How to prevent/stop scrolling on ngx-virtual-scroller on items replace?

    Ghulam Nabi
    Added an answer on May 18, 2023 at 10:50 am

    To prevent scrolling on ngx-virtual-scroller when items are replaced or added, you can use the following approach: Create a flag variable in your component's code to keep track of whether scrolling should be enabled or disabled. For example, you can add a variable called scrollEnabled and initializeRead more

    To prevent scrolling on ngx-virtual-scroller when items are replaced or added, you can use the following approach:

    1. Create a flag variable in your component’s code to keep track of whether scrolling should be enabled or disabled. For example, you can add a variable called scrollEnabled and initialize it to true.
      scrollEnabled = true;
      
      1. In the template where you have the ngx-virtual-scroller, bind the scrollEnabled variable to the scrollable input of the virtual scroller component. This will control whether scrolling is enabled based on the value of scrollEnabled.
        <ngx-virtual-scroller [items]="yourItemsArray" [scrollable]="scrollEnabled">
          <!-- Your item template here -->
        </ngx-virtual-scroller>
        
        1. When the user triggers the toggle action, update the scrollEnabled flag accordingly. If you want to lock/freeze the screen, set scrollEnabled to false. If you want to re-enable scrolling, set scrollEnabled back to true.
          toggleScrolling() {
            this.scrollEnabled = false; // Lock/Freeze the screen
            // Add or replace the items in yourItemsArray
            // Example: this.yourItemsArray = [...newItemsArray];
            // After adding/replacing items, you can reset the scroll position if needed
            // Example: this.virtualScroller.scrollToIndex(0, true); // Scroll to the top
            this.scrollEnabled = true; // Re-enable scrolling
          }
          

          By setting scrollEnabled to false, you disable scrolling in the virtual scroller component. After you have added or replaced the items, you can reset the scroll position if desired, and then set scrollEnabled back to true to enable scrolling again.

          Note: Make sure you have a reference to the ngx-virtual-scroller component in your component code. You can use ViewChild to get the reference and call the scrollToIndex method if needed.

          import { ViewChild } from '@angular/core';
          import { VirtualScrollerComponent } from 'ngx-virtual-scroller';
          
          export class YourComponent {
            @ViewChild(VirtualScrollerComponent) virtualScroller: VirtualScrollerComponent;
            
            // Rest of your component code
          }
          

           

    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
  9. Asked: May 17, 2023

    Click event not raised with Sendmessage

    Ghulam Nabi
    Added an answer on May 17, 2023 at 2:02 pm

    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long Private Const WM_LBUTTONDOWN = &H201 Private Const WM_LBUTTONUP = &H202 ' Define a custom event Public Event CustomClick() PrivaRead more

    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
    Private Const WM_LBUTTONDOWN = &H201
    Private Const WM_LBUTTONUP = &H202
    
    ' Define a custom event
    Public Event CustomClick()
    
    Private Sub Command1_Click()
        Dim X As Long, Y As Long, lParam As Long, hwnd
        X = 150
        Y = 50
        hwnd = Me.hwnd
        lParam = MakeLParam(X, Y)
        SendMessage hwnd, WM_LBUTTONDOWN, 1, lParam
        SendMessage hwnd, WM_LBUTTONUP, 0, lParam
    
        ' Raise the custom event
        RaiseEvent CustomClick
    End Sub
    
    Private Function lshft(num As Long, shifts As Byte) As Long
        lshft = num * (2 ^ shifts)
    End Function
    
    Private Function MakeLParam(ByVal LoWord As Long, ByVal HiWord As Long) As Long
        MakeLParam = lshft(HiWord, 16) Or (LoWord And &HFFFF)
    End Function
    
    Private Sub CustomClickHandler()
        MsgBox "Clicked"
    End Sub
    
    Private Sub Form_Load()
        ' Associate the custom event with its handler
        AddHandler CustomClick, AddressOf CustomClickHandler
    End Sub
    

     

    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
  10. Asked: May 17, 2023

    setAllowsBackForwardNavigationGestures not working in flutter webview

    Ghulam Nabi
    Added an answer on May 17, 2023 at 7:10 am

    import 'package:flutter/gestures.dart'; final _key = UniqueKey(); late final WebViewController webViewController; void initState() { super.initState(); webViewController = WebViewController(); if (webViewController is WebKitWebViewController) { (webViewController as WebKitWebViewController) .setAlloRead more

    import 'package:flutter/gestures.dart';
    
    final _key = UniqueKey();
    late final WebViewController webViewController;
    
    void initState() {
      super.initState();
      webViewController = WebViewController();
      if (webViewController is WebKitWebViewController) {
        (webViewController as WebKitWebViewController)
            .setAllowsBackForwardNavigationGestures(true);
      }
      webViewController
        ..enableZoom(false)
        ..setJavaScriptMode(JavaScriptMode.unrestricted)
        ..loadRequest(Uri.parse(url));
    }
    
    WebViewWidget(
      controller: webViewController,
      key: _key,
      gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{
        Factory<VerticalDragGestureRecognizer>(
          () => VerticalDragGestureRecognizer(),
        ),
      },
    )
    

    In the updated version of the webview_flutter plugin (version 4+), the way to enable swipe gestures for navigation has changed. Instead of using the gestureNavigationEnabled property, you need to use the gestureRecognizers property with a Set of gesture recognizers.

    In the updated code, we’re using the gestureRecognizers property and providing a set of gesture recognizers. Specifically, we’re adding a VerticalDragGestureRecognizer to enable vertical swipe gestures.

    Make sure to import flutter/gestures.dart at the top of your file to access the gesture recognizers.

    By adding the VerticalDragGestureRecognizer, you should be able to enable swipe gestures for navigation on your iPhone device with the updated version of the plugin.

    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
1 2 3 … 12

Sidebar

Ask A Question
  • Popular
  • Answers
  • Ghulam Nabi

    Why are the British confused about us calling bread rolls ...

    • 5 Answers
  • Alex

    application has failed to start because no appropriate graphics hardware ...

    • 4 Answers
  • Jerry

    Add file to native target programmatically via tuist/XcodeProj

    • 4 Answers
  • Ghulam Nabi
    Ghulam Nabi added an answer Improving the launch time of your Flutter Firebase app involves… May 25, 2023 at 12:08 pm
  • Ghulam Nabi
    Ghulam Nabi added an answer Currently, as of my knowledge cutoff in September 2021, the… May 25, 2023 at 12:05 pm
  • Ghulam Nabi
    Ghulam Nabi added an answer When using a GitHub Application token for authentication in your… May 25, 2023 at 12:03 pm

Trending Tags

c++ cypress flutter git java javascript python selenium testng webdriver

Top Members

Robert

Robert

  • 3 Questions
  • 1k Points
Luci

Luci

  • 5 Questions
  • 1k Points
Kevin O Brien

Kevin O Brien

  • 2 Questions
  • 1k Points

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Softans

Softans is a social questions & Answers Engine which will help you establish your community and connect with other people.

About Us

  • Blog
  • Jobs
  • About Us
  • Meet The Team
  • Contact Us

Legal Stuff

Help

Follow

© 2021 Softans. All Rights Reserved
With Love by Softans.