问:
How do you select portions of a query in aggregate functions by some attribute
Say I have a table Account, and a table Tags. Tags contains all of the random string tags associated with an account. Tags have a TagType field, to indicate what type of tag it is (color, shape, size, etc).

I want to return aggregated lists of tags based on type on a per account basis. I've tried this:

```<code>SELECT a.accountid,
       (SELECT STRING_AGG(t.TagName, ', ') WHERE t.TagType = 'color') AS Colors,
       (SELECT STRING_AGG(t.TagName, ', ') WHERE t.TagType = 'shape') AS Shapes,
       (SELECT STRING_AGG(t.TagName, ', ') WHERE t.TagType = 'size') AS Sizes
FROM dbo.account a
INNER JOIN dbo.tag t ON a.Id = t.AccountId
GROUP BY a.AccountID
</code>```

Ideally, the results would be as such:

```<code>Row - AccountId -     Colors      -     Shapes     -     Sizes
1        10        Red, Blue         Round             NULL
2        11        Green             Rectangular       Small, Medium
etc...
</code>```

However, this results in the following error:

Column 'dbo.tag.TagType' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

If I group by TagType, each account is a separate row for each tag type. The whole point is to get one row per account with different tag types. How can I achieve that?

答:
Seems like you're looking for the WITHIN GROUP functionality of STRING_AGG (Transact-SQL), e.g.:

```<code>/*
 * Data setup...
 */
create table dbo.Account (
  AccountID int
);
insert dbo.Account (AccountID) values
  (10),
  (11);

create table dbo.Tag (
  AccountID int,
  TagName varchar(20),
  TagType varchar(20)
);
insert dbo.Tag (AccountID, TagName, TagType) values
  (10, 'Red', 'color'),
  (10, 'Blue', 'color'),
  (10, 'Round', 'shape'),
  (11, 'Green', 'color'),
  (11, 'Rectangular', 'shape'),
  (11, 'Small', 'size'),
  (11, 'Medium', 'size');

/*
 * Example query...
 */
SELECT a.AccountID,
       STRING_AGG(case when t.TagType = 'color' then t.TagName end, ', ') WITHIN GROUP (order by t.TagName) AS Colors,
       STRING_AGG(case when t.TagType = 'shape' then t.TagName end, ', ') WITHIN GROUP (order by t.TagName) AS Shapes,
       STRING_AGG(case when t.TagType = 'size' then t.TagName end, ', ') WITHIN GROUP (order by t.TagName) AS Sizes
FROM dbo.account a
INNER JOIN dbo.tag t ON a.AccountID = t.AccountID
GROUP BY a.AccountID
</code>```

Which yields the result...

AccountID
Colors
Shapes
Sizes

10
Blue, Red
Round
null

11
Green
Rectangular
Medium, Small

Body:
Say I have a table Account, and a table Tags. Tags contains all of the random string tags associated with an account. Tags have a TagType field, to indicate what type of tag it is (color, shape, size, etc).

I want to return aggregated lists of tags based on type on a per account basis. I've tried this:

SELECT a.accountid,
       (SELECT STRING_AGG(t.TagName, ', ') WHERE t.TagType = 'color') AS Colors,
       (SELECT STRING_AGG(t.TagName, ', ') WHERE t.TagType = 'shape') AS Shapes,
       (SELECT STRING_AGG(t.TagName, ', ') WHERE t.TagType = 'size') AS Sizes
FROM dbo.account a
INNER JOIN dbo.tag t ON a.Id = t.AccountId
GROUP BY a.AccountID

Ideally, the results would be as such:

Row - AccountId -     Colors      -     Shapes     -     Sizes
1        10        Red, Blue         Round             NULL
2        11        Green             Rectangular       Small, Medium
etc...

However, this results in the following error:

Column 'dbo.tag.TagType' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

If I group by TagType, each account is a separate row for each tag type. The whole point is to get one row per account with different tag types. How can I achieve that?

Body:
Seems like you're looking for the WITHIN GROUP functionality of STRING_AGG (Transact-SQL), e.g.:

/*
 * Data setup...
 */
create table dbo.Account (
  AccountID int
);
insert dbo.Account (AccountID) values
  (10),
  (11);

create table dbo.Tag (
  AccountID int,
  TagName varchar(20),
  TagType varchar(20)
);
insert dbo.Tag (AccountID, TagName, TagType) values
  (10, 'Red', 'color'),
  (10, 'Blue', 'color'),
  (10, 'Round', 'shape'),
  (11, 'Green', 'color'),
  (11, 'Rectangular', 'shape'),
  (11, 'Small', 'size'),
  (11, 'Medium', 'size');

/*
 * Example query...
 */
SELECT a.AccountID,
       STRING_AGG(case when t.TagType = 'color' then t.TagName end, ', ') WITHIN GROUP (order by t.TagName) AS Colors,
       STRING_AGG(case when t.TagType = 'shape' then t.TagName end, ', ') WITHIN GROUP (order by t.TagName) AS Shapes,
       STRING_AGG(case when t.TagType = 'size' then t.TagName end, ', ') WITHIN GROUP (order by t.TagName) AS Sizes
FROM dbo.account a
INNER JOIN dbo.tag t ON a.AccountID = t.AccountID
GROUP BY a.AccountID

Which yields the result...

AccountID
Colors
Shapes
Sizes

10
Blue, Red
Round
null

11
Green
Rectangular
Medium, Small


来源: stackexchange

问:
using .c files in C# (winform .net)
I am using visual studio 2010
my project is that,
 i want to encrypt text using blowfish algorithm and then add that encrypted data must be saved in my database

my blowfish algorthim is in .c file
my input must be taken via C# (windows form)
and my database is in sql server 2008

i just want to known that can i send the text taken via windows form (.net c#) to my .c file and proccess it and get that encrypted data and save that data in sql server via windows form

can this be done
please help me out

答:
One way is to use C++/CLI as intermediary between your C and C#

C# -> C++/CLI -> C

other way is to expose your C functions and use P/Invoke in C#.

ContentLicense: CC BY-SA 3.0

Title: using .c files in C# (winform .net)


问:
I am trying to keep the objects of csv files into a linked list to search for the tshirts But I am getting cannot infer type arguments for linked list
My program is to implement a standalone product search program in Java that lists matching
products for a user who is looking for T-shirts. I am given 3 CSV files. I am trying to keep
the objects of CSV files into a LinkedList to search for the T-shirts but I am getting cannot
infer type arguments for LinkedList.
Here is my code in which I am trying to store objects of CSV file into LinkedList.

package com.example.Mavenassignmentone;

import java.io.*;
import java.util.*;

public class FindTshirt {
    List<ShirtModel> shirtlist = new LinkedList<ShirtModel>();
    LinkedList<String> list;
    showTshirt sh = new showTshirt();

    public void find(String filename, String COLOUR, String GENDER_RECOMMENDATION, String SIZE)
            throws FileNotFoundException {
        Scanner sc = new Scanner(new File(filename));
        while (sc.hasNext()) {
            String sentence = sc.nextLine().toString();
            if (!sentence.isEmpty()) {
                StringTokenizer token = new StringTokenizer(sentence, "|");
                list = new LinkedList<>(sentence.length());
                while (token.hasMoreTokens()) {
                    list.add(token.nextToken());
                }
                if (list.get(1).equals(COLOUR) && list.get(2).equals(GENDER_RECOMMENDATION)
                        && list.get(3).equals(SIZE)) {
                    ShirtModel model = new ShirtModel(list.get(0), list.get(1), list.get(2),
                            list.get(3), list.get(4), Integer.parseInt(list.get(5)),
                            Float.parseFloat(list.get(6)), list.get(7));
                    shirtlist.add(model);
                }
            }
        }
    }

    public void updateView(int choiceCode) {
        if (choiceCode == 1) {
            Collections.sort(shirtlist, new Comparator<ShirtModel>() {
                @Override
                public int compare(ShirtModel o1, ShirtModel o2) {
                    return o1.getPrice() - o2.getPrice();
                }
            });
        }
        else if (choiceCode == 2) {
            Collections.sort(shirtlist, new Comparator<ShirtModel>() {
                public int compare(ShirtModel o1, ShirtModel o2) {
                    return (int) (o1.getRating() - o2.getRating());
                }
            });
        }

        else {
            System.out.println("Wrong Choice.");
            return;
        }
        sh.viewtshirt(shirtlist);
    }
}
```
<p>This line of code is giving error:</p>
<pre class="lang-java prettyprint-override"><code>list=new LinkedList<>(sentence.length());
</code>```

Error is

cannot infer type arguments

答:
You have to identify the type of the linked list, change the line to

```<code>list=new LinkedList<String>();
</code>```

and moreover, you in linkedList, you don't have to identify the length.

ContentLicense: CC BY-SA 4.0

Body:
My program is to implement a standalone product search program in Java that lists matching
products for a user who is looking for T-shirts. I am given 3 CSV files. I am trying to keep
the objects of CSV files into a LinkedList to search for the T-shirts but I am getting cannot
infer type arguments for LinkedList.
Here is my code in which I am trying to store objects of CSV file into LinkedList.

package com.example.Mavenassignmentone;

import java.io.*;
import java.util.*;

public class FindTshirt {
    List<ShirtModel> shirtlist = new LinkedList<ShirtModel>();
    LinkedList<String> list;
    showTshirt sh = new showTshirt();

    public void find(String filename, String COLOUR, String GENDER_RECOMMENDATION, String SIZE)
            throws FileNotFoundException {
        Scanner sc = new Scanner(new File(filename));
        while (sc.hasNext()) {
            String sentence = sc.nextLine().toString();
            if (!sentence.isEmpty()) {
                StringTokenizer token = new StringTokenizer(sentence, "|");
                list = new LinkedList<>(sentence.length());
                while (token.hasMoreTokens()) {
                    list.add(token.nextToken());
                }
                if (list.get(1).equals(COLOUR) && list.get(2).equals(GENDER_RECOMMENDATION)
                        && list.get(3).equals(SIZE)) {
                    ShirtModel model = new ShirtModel(list.get(0), list.get(1), list.get(2),
                            list.get(3), list.get(4), Integer.parseInt(list.get(5)),
                            Float.parseFloat(list.get(6)), list.get(7));
                    shirtlist.add(model);
                }
            }
        }
    }

    public void updateView(int choiceCode) {
        if (choiceCode == 1) {
            Collections.sort(shirtlist, new Comparator<ShirtModel>() {
                @Override
                public int compare(ShirtModel o1, ShirtModel o2) {
                    return o1.getPrice() - o2.getPrice();
                }
            });
        }
        else if (choiceCode == 2) {
            Collections.sort(shirtlist, new Comparator<ShirtModel>() {
                public int compare(ShirtModel o1, ShirtModel o2) {
                    return (int) (o1.getRating() - o2.getRating());
                }
            });
        }

        else {
            System.out.println("Wrong Choice.");
            return;
        }
        sh.viewtshirt(shirtlist);
    }
}

This line of code is giving error:

list=new LinkedList<>(sentence.length());

Error is

cannot infer type arguments

Body:
You have to identify the type of the linked list, change the line to

list=new LinkedList<String>();

and moreover, you in linkedList, you don't have to identify the length.


问:
Calling a function when opening a react-native screen
I'm trying to load a JSON from AsyncStorage every time a user opens one of my react-native screens (I'm using StackNavigator). This JSON contains information on what my states should be set to.

How can I call a function that runs every time this screen is opened?

Further info:
I've written a function that updates my states according to a JSON loaded from AsyncStorage. The function works perfectly when called from a button, but when the function is called from render(), part of my screen freezes and some buttons are not touchable anymore. Strangely only TextInput still works.

答:
I used "onLayout" method inside the view.

read the doc

onLayout: Invoked on mount and on layout changes.

```<code>export default function Login({ navigation }) {

  const executeOnLoad = () => {
    console.log("view has loaded!");
  };

  return (
    <View style={styles.container} onLayout={executeOnLoad}>
    --- layout code here
    </View>
  );
}
</code>```

Body:
I used "onLayout" method inside the view.

read the doc

onLayout: Invoked on mount and on layout changes.

export default function Login({ navigation }) {

  const executeOnLoad = () => {
    console.log("view has loaded!");
  };

  return (
    <View style={styles.container} onLayout={executeOnLoad}>
    --- layout code here
    </View>
  );
}


问:
How to Download/Upload Files from Azure Blob using Python in Spyder/Anaconda
I am new to Azure. I created a Blob Storage today. I am trying to run some Python code that I found online, to download files fro this Blob Container. Here is the code that I am testing.

```<code># download_blobs.py
# Python program to bulk download blob files from azure storage
# Uses latest python SDK() for Azure blob storage
# Requires python 3.6 or above
import os
from azure.storage.blob import BlobServiceClient, BlobClient
from azure.storage.blob import ContentSettings, ContainerClient

# IMPORTANT: Replace connection string with your storage account connection string
# Usually starts with DefaultEndpointsProtocol=https;...
MY_CONNECTION_STRING = "DefaultEndpointsProtocol=https;AccountName=ryanpythonstorage;AccountKey=my_account_key;EndpointSuffix=core.windows.net"

# Replace with blob container
MY_BLOB_CONTAINER = "ryanpythonstorage" #copied from Access Keys

# Replace with the local folder where you want files to be downloaded
LOCAL_BLOB_PATH = "C:\\Users\\ryans\\Desktop\\blob\\"

class AzureBlobFileDownloader:
  def __init__(self):
    print("Intializing AzureBlobFileDownloader")

    # Initialize the connection to Azure storage account
    self.blob_service_client =  BlobServiceClient.from_connection_string(MY_CONNECTION_STRING)
    self.my_container = self.blob_service_client.get_container_client(MY_BLOB_CONTAINER)

  def save_blob(self,file_name,file_content):
    # Get full path to the file
    download_file_path = os.path.join(LOCAL_BLOB_PATH, file_name)

    # for nested blobs, create local path as well!
    os.makedirs(os.path.dirname(download_file_path), exist_ok=True)

    with open(download_file_path, "wb") as file:
      file.write(file_content)

  def download_all_blobs_in_container(self):
    my_blobs = self.my_container.list_blobs()
    for blob in my_blobs:
      print(blob.name)
      bytes = self.my_container.get_blob_client(blob).download_blob().readall()
      self.save_blob(blob.name, bytes)

# Initialize class and upload files
azure_blob_file_downloader = AzureBlobFileDownloader()
azure_blob_file_downloader.download_all_blobs_in_container()
</code>```

Here is the result that I see when I run the code.

```<code>Intializing AzureBlobFileDownloader
Traceback (most recent call last):

  File "C:\Users\ryans\AppData\Local\Temp\ipykernel_14020\3010845424.py", line 37, in <module>
    azure_blob_file_downloader.download_all_blobs_in_container()

  File "C:\Users\ryans\AppData\Local\Temp\ipykernel_14020\3010845424.py", line 30, in download_all_blobs_in_container
    for blob in my_blobs:

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\core\paging.py", line 129, in __next__
    return next(self._page_iterator)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\core\paging.py", line 76, in __next__
    self._response = self._get_next(self.continuation_token)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_list_blobs_helper.py", line 79, in _get_next_cb
    process_storage_error(error)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_shared\response_handlers.py", line 177, in process_storage_error
    exec("raise error from None")   # pylint: disable=exec-used # nosec

  File "<string>", line 1, in <module>

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_list_blobs_helper.py", line 72, in _get_next_cb
    return self._command(

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_generated\operations\_container_operations.py", line 1479, in list_blob_flat_segment
    map_error(status_code=response.status_code, response=response, error_map=error_map)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\core\exceptions.py", line 105, in map_error
    raise error

ResourceNotFoundError: The specified container does not exist.
RequestId:4d2df1c1-a01e-008b-4209-21e493000000
Time:2022-02-13T18:44:14.1140999Z
ErrorCode:ContainerNotFound
Content: <?xml version="1.0" encoding="utf-8"?><Error><Code>ContainerNotFound</Code><Message>The specified container does not exist.
RequestId:4d2df1c1-a01e-008b-4209-21e493000000
Time:2022-02-13T18:44:14.1140999Z</Message></Error>
</code>```

Ultimately, I want to be able to do two things:

download files from my Blob to my local machine

upload files from my local machine to my Blob.

答:
Here is my final working code.

```<code>import os
import uuid
import sys
from azure.storage.blob import BlockBlobService, PublicAccess

try:
    # Create the BlockBlobService that is used to call the Blob service for the storage account
    blob_service_client = BlockBlobService(account_name='your_account_name_goes_here', account_key='your_account_key_goes_here')

    # Create a container called 'quickstartblobs'.
    container_name = 'your_container_name_goes_here'
    blob_service_client.create_container(container_name)

    # Set the permission so the blobs are public.
    blob_service_client.set_container_acl(container_name, public_access=PublicAccess.Container)

    # Create Sample folder if it not exists, and create a file in folder Sample to test the upload and download.
    local_path = os.path.expanduser('C:\\Users\\ryans\\Desktop\\blob\\')

    local_file_name  = 'charges.csv'
    #local_file_name = "QuickStart_" + str(uuid.uuid4()) + ".txt"
    full_path_to_file = os.path.join(local_path, local_file_name)

    print("Temp file = " + full_path_to_file)
    print("\nUploading to Blob storage as blob" + local_file_name)

    # Upload the created file, use local_file_name for the blob name
    blob_service_client.create_blob_from_path(container_name, local_file_name, full_path_to_file)

    # List the blobs in the container
    print("\nList blobs in the container")
    generator = blob_service_client.list_blobs(container_name)

    for blob in generator:
        print("\t Blob name: " + blob.name)

except Exception as e:
    print(e)

##############################################################################################

import os
import uuid
import sys
from azure.storage.blob import BlockBlobService, PublicAccess

try:

    local_path = os.path.expanduser('C:\\Users\\ryans\\Desktop\\blob\\')
    container_name = 'your_container_name_goes_here'
    local_file_name  = 'charges.csv'

    # Download the blob(s).
    # Add '_DOWNLOADED' as prefix to '.txt' so you can see both files in Documents.
    full_path_to_file = os.path.join(local_path, local_file_name)
    print("\nDownloading blob to " + full_path_to_file)
    blob_service_client.get_blob_to_path(container_name, local_file_name, full_path_to_file)

    #sys.stdout.write("Sample finished running. When you hit <any key>, the sample will be deleted and the sample application will exit.")
    sys.stdout.flush()
    input()

except Exception as e:
    print(e)
</code>```

This link was a great resource for me.

https://github.com/Azure-Samples/azure-sdk-for-python-storage-blob-upload-download/blob/master/example.py

Body:
I am new to Azure. I created a Blob Storage today. I am trying to run some Python code that I found online, to download files fro this Blob Container. Here is the code that I am testing.

# download_blobs.py
# Python program to bulk download blob files from azure storage
# Uses latest python SDK() for Azure blob storage
# Requires python 3.6 or above
import os
from azure.storage.blob import BlobServiceClient, BlobClient
from azure.storage.blob import ContentSettings, ContainerClient

# IMPORTANT: Replace connection string with your storage account connection string
# Usually starts with DefaultEndpointsProtocol=https;...
MY_CONNECTION_STRING = "DefaultEndpointsProtocol=https;AccountName=ryanpythonstorage;AccountKey=my_account_key;EndpointSuffix=core.windows.net"

# Replace with blob container
MY_BLOB_CONTAINER = "ryanpythonstorage" #copied from Access Keys

# Replace with the local folder where you want files to be downloaded
LOCAL_BLOB_PATH = "C:\\Users\\ryans\\Desktop\\blob\\"

class AzureBlobFileDownloader:
  def __init__(self):
    print("Intializing AzureBlobFileDownloader")

    # Initialize the connection to Azure storage account
    self.blob_service_client =  BlobServiceClient.from_connection_string(MY_CONNECTION_STRING)
    self.my_container = self.blob_service_client.get_container_client(MY_BLOB_CONTAINER)

  def save_blob(self,file_name,file_content):
    # Get full path to the file
    download_file_path = os.path.join(LOCAL_BLOB_PATH, file_name)

    # for nested blobs, create local path as well!
    os.makedirs(os.path.dirname(download_file_path), exist_ok=True)

    with open(download_file_path, "wb") as file:
      file.write(file_content)

  def download_all_blobs_in_container(self):
    my_blobs = self.my_container.list_blobs()
    for blob in my_blobs:
      print(blob.name)
      bytes = self.my_container.get_blob_client(blob).download_blob().readall()
      self.save_blob(blob.name, bytes)

# Initialize class and upload files
azure_blob_file_downloader = AzureBlobFileDownloader()
azure_blob_file_downloader.download_all_blobs_in_container()

Here is the result that I see when I run the code.

Intializing AzureBlobFileDownloader
Traceback (most recent call last):

  File "C:\Users\ryans\AppData\Local\Temp\ipykernel_14020\3010845424.py", line 37, in <module>
    azure_blob_file_downloader.download_all_blobs_in_container()

  File "C:\Users\ryans\AppData\Local\Temp\ipykernel_14020\3010845424.py", line 30, in download_all_blobs_in_container
    for blob in my_blobs:

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\core\paging.py", line 129, in __next__
    return next(self._page_iterator)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\core\paging.py", line 76, in __next__
    self._response = self._get_next(self.continuation_token)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_list_blobs_helper.py", line 79, in _get_next_cb
    process_storage_error(error)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_shared\response_handlers.py", line 177, in process_storage_error
    exec("raise error from None")   # pylint: disable=exec-used # nosec

  File "<string>", line 1, in <module>

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_list_blobs_helper.py", line 72, in _get_next_cb
    return self._command(

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\storage\blob\_generated\operations\_container_operations.py", line 1479, in list_blob_flat_segment
    map_error(status_code=response.status_code, response=response, error_map=error_map)

  File "C:\Users\ryans\anaconda3\lib\site-packages\azure\core\exceptions.py", line 105, in map_error
    raise error

ResourceNotFoundError: The specified container does not exist.
RequestId:4d2df1c1-a01e-008b-4209-21e493000000
Time:2022-02-13T18:44:14.1140999Z
ErrorCode:ContainerNotFound
Content: <?xml version="1.0" encoding="utf-8"?><Error>ContainerNotFound<Message>The specified container does not exist.
RequestId:4d2df1c1-a01e-008b-4209-21e493000000
Time:2022-02-13T18:44:14.1140999Z</Message></Error>

Ultimately, I want to be able to do two things:

download files from my Blob to my local machine

upload files from my local machine to my Blob.

Body:
Here is my final working code.

import os
import uuid
import sys
from azure.storage.blob import BlockBlobService, PublicAccess

try:
    # Create the BlockBlobService that is used to call the Blob service for the storage account
    blob_service_client = BlockBlobService(account_name='your_account_name_goes_here', account_key='your_account_key_goes_here')

    # Create a container called 'quickstartblobs'.
    container_name = 'your_container_name_goes_here'
    blob_service_client.create_container(container_name)

    # Set the permission so the blobs are public.
    blob_service_client.set_container_acl(container_name, public_access=PublicAccess.Container)

    # Create Sample folder if it not exists, and create a file in folder Sample to test the upload and download.
    local_path = os.path.expanduser('C:\\Users\\ryans\\Desktop\\blob\\')

    local_file_name  = 'charges.csv'
    #local_file_name = "QuickStart_" + str(uuid.uuid4()) + ".txt"
    full_path_to_file = os.path.join(local_path, local_file_name)

    print("Temp file = " + full_path_to_file)
    print("\nUploading to Blob storage as blob" + local_file_name)

    # Upload the created file, use local_file_name for the blob name
    blob_service_client.create_blob_from_path(container_name, local_file_name, full_path_to_file)

    # List the blobs in the container
    print("\nList blobs in the container")
    generator = blob_service_client.list_blobs(container_name)

    for blob in generator:
        print("\t Blob name: " + blob.name)

except Exception as e:
    print(e)

##############################################################################################

import os
import uuid
import sys
from azure.storage.blob import BlockBlobService, PublicAccess

try:

    local_path = os.path.expanduser('C:\\Users\\ryans\\Desktop\\blob\\')
    container_name = 'your_container_name_goes_here'
    local_file_name  = 'charges.csv'

    # Download the blob(s).
    # Add '_DOWNLOADED' as prefix to '.txt' so you can see both files in Documents.
    full_path_to_file = os.path.join(local_path, local_file_name)
    print("\nDownloading blob to " + full_path_to_file)
    blob_service_client.get_blob_to_path(container_name, local_file_name, full_path_to_file)

    #sys.stdout.write("Sample finished running. When you hit <any key>, the sample will be deleted and the sample application will exit.")
    sys.stdout.flush()
    input()

except Exception as e:
    print(e)

This link was a great resource for me.

https://github.com/Azure-Samples/azure-sdk-for-python-storage-blob-upload-download/blob/master/example.py


问:
What's syntax if i need to update some employee?
```<code>Emp_name = []
Emp_id = []
Emp_dep = []
num = 5
for i in range(num):
    x = input("enter the name of employees")
    Emp_name.append(x)

    i = input("enter the id of employees")
    Emp_id.append(i)

    d = input("enter the department of employees")
    Emp_dep.append(d)
delete = str(input(" Enter the name of employee you need to delete"))
if delete in Emp_name:
    pos = Emp_name.index(delete)
    Emp_name.pop(pos)
    Emp_id.pop(pos)
    Emp_dep.pop(pos)

print(Emp_name)
print(Emp_id)
print(Emp_dep)
</code>```

If I need to update some employee what's syntax tp fo that?
I am working in employee application

答:
The simplest way to update existing data in the array is by getting the index of the employee to update (as you're doing for deletion) and then updating the values for name and department in the respective arrays. Like this, for example:</p>
```<code>update = str(input(" Enter id of employee you want to update"))
if update in Emp_id:
    pos = Emp_id.index(update)
    Emp_name[pos] = str(input(" Enter new name"))
    Emp_dep[pos] = str(input(" Enter new department"))
</code>```

Body:
Emp_name = []
Emp_id = []
Emp_dep = []
num = 5
for i in range(num):
    x = input("enter the name of employees")
    Emp_name.append(x)

    i = input("enter the id of employees")
    Emp_id.append(i)

    d = input("enter the department of employees")
    Emp_dep.append(d)
delete = str(input(" Enter the name of employee you need to delete"))
if delete in Emp_name:
    pos = Emp_name.index(delete)
    Emp_name.pop(pos)
    Emp_id.pop(pos)
    Emp_dep.pop(pos)

print(Emp_name)
print(Emp_id)
print(Emp_dep)

If I need to update some employee what's syntax tp fo that?
I am working in employee application

Body:
The simplest way to update existing data in the array is by getting the index of the employee to update (as you're doing for deletion) and then updating the values for name and department in the respective arrays. Like this, for example:

update = str(input(" Enter id of employee you want to update"))
if update in Emp_id:
    pos = Emp_id.index(update)
    Emp_name[pos] = str(input(" Enter new name"))
    Emp_dep[pos] = str(input(" Enter new department"))


问:
How to select multiple idexed ids using Javascript?
i have 6 divs with id wrapperX (X is number 1 till 6)

when I want to change its background color with for loop
 error show on the log which says Uncaught TypeError: Cannot read property 'style' of null

when I'm not use template literal it works but I must write the code one by one

```<code>// show error
for (let i = 0; i < 6; i++) {
  let eleSelect = document.getElementById(`wrapper${i}`);
  eleSelect.style.setProperty('background-color', 'green');
  console.log(eleSelect);
}
// it works
for (let i = 0; i < 6; i++) {
  let eleSelect = document.getElementById('wrapper0');
  // i must repeat the code till 5
  eleSelect.style.setProperty('background-color', 'green');
  console.log(eleSelect);
}
</code>```

css code (i think it's necessary to include here) :

```<code>#wrapper0, #wrapper1, #wrapper2, #wrapper3, #wrapper4, #wrapper5{
  width: 100px; height: 100px; background-color: black;
}
</code>```

html:

```<code><div id="wrapper0"></div><div id="wrapper1"></div><div id="wrapper2"></div><div id="wrapper3"></div><div id="wrapper4"></div><div id="wrapper5"></div>
</code>```

答:
Method-1

In the first solution, all
 elements are selected and the background-color style of all elements whose id attribute starts with wrapper is set to green.

/**
 * In the solution below, all
 elements are selected and the background-color
 * style of all elements whose id attribute starts with "wrapper" is set to green.
 */
let containers = document.querySelectorAll('div');

containers.forEach(element => {
  if(element.getAttribute("id").substring(0, 7) === "wrapper") {
    element.style.setProperty('background-color', 'green');
    console.log(element);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#wrapper0, #wrapper1, #wrapper2, #wrapper3, #wrapper4, #wrapper5{
  width: 100px;
  height: 100px;
  background-color: black;
} </code>```

```
</div>
</div>
</p>
<h5>Method-2</h5>
<p>In the second solution, all items whose <code>id</code> value is in the range <code>[wrapper0, wrapper5]</code> are scanned. If the element is defined, the <code>background-color</code> style is set to <code>green</code>. If the element is not defined, assigning any style value is avoided as its value will be <code>null</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/**
 * In the solution below, if the selected element is not null, the background-color
 * style is set to green.
 */
for (let i = 0; i < 6; i++) {
  let selectedElement = document.getElementById(`wrapper${i}`);

  if(selectedElement !== null) {
    selectedElement.style.setProperty('background-color', 'green');
    console.log(selectedElement);
  }
}</code>```

#wrapper1, #wrapper2, #wrapper3, #wrapper4, #wrapper5 {
  width: 100px;
  height: 100px;
  background-color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper0"></div>
<div id="wrapper1"></div>
<div id="wrapper2"></div>
<div id="wrapper3"></div>
<div id="wrapper4"></div>
<div id="wrapper5"></div></code>```

Body:
i have 6 divs with id wrapperX (X is number 1 till 6)

when I want to change its background color with for loop
 error show on the log which says Uncaught TypeError: Cannot read property 'style' of null

when I'm not use template literal it works but I must write the code one by one

// show error
for (let i = 0; i < 6; i++) {
  let eleSelect = document.getElementById(`wrapper${i}`);
  eleSelect.style.setProperty('background-color', 'green');
  console.log(eleSelect);
}
// it works
for (let i = 0; i < 6; i++) {
  let eleSelect = document.getElementById('wrapper0');
  // i must repeat the code till 5
  eleSelect.style.setProperty('background-color', 'green');
  console.log(eleSelect);
}

css code (i think it's necessary to include here) :

#wrapper0, #wrapper1, #wrapper2, #wrapper3, #wrapper4, #wrapper5{
  width: 100px; height: 100px; background-color: black;
}

html:

Body:
Method-1

In the first solution, all <div> elements are selected and the background-color style of all elements whose id attribute starts with wrapper is set to green.

/**
 * In the solution below, all <div> elements are selected and the background-color
 * style of all elements whose id attribute starts with "wrapper" is set to green.
 */
let containers = document.querySelectorAll('div');

containers.forEach(element => {
  if(element.getAttribute("id").substring(0, 7) === "wrapper") {
    element.style.setProperty('background-color', 'green');
    console.log(element);
  }
});

#wrapper0, #wrapper1, #wrapper2, #wrapper3, #wrapper4, #wrapper5{
  width: 100px;
  height: 100px;
  background-color: black;
}

<div id="wrapper0"></div>
<div id="wrapper1"></div>
<div id="wrapper2"></div>
<div id="wrapper3"></div>
<div id="wrapper4"></div>
<div id="wrapper5"></div>

Method-2

In the second solution, all items whose id value is in the range [wrapper0, wrapper5] are scanned. If the element is defined, the background-color style is set to green. If the element is not defined, assigning any style value is avoided as its value will be null.

/**
 * In the solution below, if the selected element is not null, the background-color
 * style is set to green.
 */
for (let i = 0; i < 6; i++) {
  let selectedElement = document.getElementById(`wrapper${i}`);

  if(selectedElement !== null) {
    selectedElement.style.setProperty('background-color', 'green');
    console.log(selectedElement);
  }
}

#wrapper1, #wrapper2, #wrapper3, #wrapper4, #wrapper5 {
  width: 100px;
  height: 100px;
  background-color: black;
}

<div id="wrapper0"></div>
<div id="wrapper1"></div>
<div id="wrapper2"></div>
<div id="wrapper3"></div>
<div id="wrapper4"></div>
<div id="wrapper5"></div>


问:
How to remove blank space around an image in Android?
Given an image with alpha channel (transparency) I would like to remove any blank space between the image boundaries and the actual image.
This should be done in a backgound task or with a loading screen, with an acceptable running time to not cripple the user experience.

How can I achieve this result?

答:
You can trim transparent space of around the image using single property of ImageView view.

You can use android:adjustViewBounds="true" property into XML layout file to trim transparent space of respective image.


问:
Best way to store referrer?
I have a site with thousands of users. Each user have an unique ID, that they can share with their friends, and in that way get referrals.

What would you recommend the best way to store the $_GET['referral']; from the URL?

答:
Unique referral IDs should be stored in a database.

For the duration of a user's session, you can store the ID in his session like this:

```<code>session_start();
$_SESSION['referral_id'] = $_GET['referral'];
</code>```

Title: Best way to store referrer?

Body:
Unique referral IDs should be stored in a database.

For the duration of a user's session, you can store the ID in his session like this:

session_start();
$_SESSION['referral_id'] = $_GET['referral'];


问:
Adding document in firebase firestore via react native is not working, but not throwing error
I have a react native project and am using firebase v9.

I am trying to add a user object to my user collection when a user is created via the sign up screen, but it is not adding in the database, and not throwing any errors either.

Here is my firebase.js

```<code>import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

const firebaseConfig = {
  apiKey: '',
  authDomain: '',
  projectId: '',
  storageBucket: '',
  messagingSenderId: '',
  appId: '',
};

let app;

if (firebase.apps.length === 0) {
  app = firebase.initializeApp(firebaseConfig);
} else {
  app = firebase.app();
}

const db = app.firestore();
const auth = firebase.auth();

export {db, auth};
</code>```

I know that these connection details are correct because my firebase authentication is working correctly.

Here is my sign in screen where I attempt to add to the database.

```<code>const SignUp = ({navigation}) => {
  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const createUser = async (email, password) => {
    try {
      auth
        .createUserWithEmailAndPassword(email, password)
        .then(function (user) {
          var user = auth.currentUser;
          logUser(user);
          navigation.navigate('Login');
        });
    } catch (error) {
      alert(error);
    }
  };

  async function logUser(user) {
    await addDoc(collection(db, 'users'), JSON.parse(JSON.stringify(user)));
  }
</code>```

If I don't put JSON.parse/JSON.stringify, it is throwing an error saying firebase is called with invalid data, expected object, but it was a custom user object. So I know it is hitting that part of the codebase.

I have also went into my firestore 'rules' section on firebase console and changed it to requests go through for all:

```<code>      allow read, write: if true;
</code>```

Thanks.

答:
You are using compat version of Firebase SDK but also using the new Modular SDK syntax. Try using only 1 version of the SDK as shown below:

```<code>import { db } from "..path/to/firebase/firebase.js"

async function logUser(user) {
  await db.collection("users").add(user)
}
</code>```

I would recommend upgrading to Modular SDK as compat version might be removed in newer versions.

Body:
I have a react native project and am using firebase v9.

I am trying to add a user object to my user collection when a user is created via the sign up screen, but it is not adding in the database, and not throwing any errors either.

Here is my firebase.js

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

const firebaseConfig = {
  apiKey: '',
  authDomain: '',
  projectId: '',
  storageBucket: '',
  messagingSenderId: '',
  appId: '',
};

let app;

if (firebase.apps.length === 0) {
  app = firebase.initializeApp(firebaseConfig);
} else {
  app = firebase.app();
}

const db = app.firestore();
const auth = firebase.auth();

export {db, auth};

I know that these connection details are correct because my firebase authentication is working correctly.

Here is my sign in screen where I attempt to add to the database.

const SignUp = ({navigation}) => {
  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const createUser = async (email, password) => {
    try {
      auth
        .createUserWithEmailAndPassword(email, password)
        .then(function (user) {
          var user = auth.currentUser;
          logUser(user);
          navigation.navigate('Login');
        });
    } catch (error) {
      alert(error);
    }
  };

  async function logUser(user) {
    await addDoc(collection(db, 'users'), JSON.parse(JSON.stringify(user)));
  }

If I don't put JSON.parse/JSON.stringify, it is throwing an error saying firebase is called with invalid data, expected object, but it was a custom user object. So I know it is hitting that part of the codebase.

I have also went into my firestore 'rules' section on firebase console and changed it to requests go through for all:

      allow read, write: if true;

Thanks.

Body:
You are using compat version of Firebase SDK but also using the new Modular SDK syntax. Try using only 1 version of the SDK as shown below:

import { db } from "..path/to/firebase/firebase.js"

async function logUser(user) {
  await db.collection("users").add(user)
}

I would recommend upgrading to Modular SDK as compat version might be removed in newer versions.


问:
Discord.js | TypeError: Cannot read property 'MessageEmbed' of undefined
I'm a beginner at coding. I'm making a node.js today, and it says there's a problem with the embed. I don't know why, but it doesn't work even if I use someone else's code. How should I solve this?

const { Permissions , MessageActionRow , MessageSelectMenu , MessageEmbed,Discord} = require('discord.js')

module.exports = {
name: 'command',
description: 'Embeds',
execute(message, args, Discord)
    {
const newEmbed = new Discord.MessageEmbed()
        .setColor('#ff0000')
        .setTitle('Yes')
        .setDescription('My Embed')
        .setFooter('life is a lie');

interaction.channel.send({embeds : [embed]})
    },
};```

This happens. FYI, I shared the code in the Commandz folder, and the index folder had the same error, so I uploaded it. Help me!

答:
You added a const function to newEmbed like this:

const newEmbed = new Discord.MessageEmbed()

But, you put interaction.channel.send({embeds : [embed]}) instead of interaction.channel.send({embeds : [newEmbed]})

What this did was it basically just used the const function and read its value. The embeds part is always supposed to be the same, but the [newEmbed] part should always be what you declared in your const function for the embed. Remember that for future embeds.

Here's your code modified by me:

```<code>const { Permissions , MessageActionRow , MessageSelectMenu , MessageEmbed, Discord } = require('discord.js');

module.exports = {
name: 'command',
description: 'Embeds',
execute(message, args, Discord)
    {
const newEmbed = new MessageEmbed()
        .setColor('#ff0000')
        .setTitle('Yes')
        .setDescription('My Embed')
        .setFooter('life is a lie');

interaction.channel.send({embeds : [newEmbed]})
    },
};
</code>```

Have a good day!

Body:
I'm a beginner at coding. I'm making a node.js today, and it says there's a problem with the embed. I don't know why, but it doesn't work even if I use someone else's code. How should I solve this?

const { Permissions , MessageActionRow , MessageSelectMenu , MessageEmbed,Discord} = require('discord.js')

module.exports = {
name: 'command',
description: 'Embeds',
execute(message, args, Discord)
    {
const newEmbed = new Discord.MessageEmbed()
        .setColor('#ff0000')
        .setTitle('Yes')
        .setDescription('My Embed')
        .setFooter('life is a lie');

interaction.channel.send({embeds : [embed]})
    },
};

This happens. FYI, I shared the code in the Commandz folder, and the index folder had the same error, so I uploaded it. Help me!

Body:
You added a const function to newEmbed like this:

const newEmbed = new Discord.MessageEmbed()

But, you put interaction.channel.send({embeds : [embed]}) instead of interaction.channel.send({embeds : [newEmbed]})

What this did was it basically just used the const function and read its value. The embeds part is always supposed to be the same, but the [newEmbed] part should always be what you declared in your const function for the embed. Remember that for future embeds.

Here's your code modified by me:

const { Permissions , MessageActionRow , MessageSelectMenu , MessageEmbed, Discord } = require('discord.js');

module.exports = {
name: 'command',
description: 'Embeds',
execute(message, args, Discord)
    {
const newEmbed = new MessageEmbed()
        .setColor('#ff0000')
        .setTitle('Yes')
        .setDescription('My Embed')
        .setFooter('life is a lie');

interaction.channel.send({embeds : [newEmbed]})
    },
};

Have a good day!


问:
OnbackPrees to return home always in react stack navigation
I am do do navigation in react native where all the back arrow or back press return to initial route. On last on option is to list to onBackPreessed event and passs call to init route which is home.
I am hoping their will be props for allowing the Screen to return to init   Screen in stack navigations

What is happening

On home:
go details then go A
back arrow press in A, it  return  back to  details

Need actions

On home:
go details then go A
back arrow press in A  return  back to home instead of details

The code I try

```<code>import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}

function DetailsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
      <Button
        title="Go to A"
        onPress={() => navigation.navigate('A')}
      />

    </View>
  );
}
function A({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>AAAAAAAAAAAAAAAAAAA Screen</Text>

    </View>
  );
}
const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home" detachInactiveScreens={true}
        detachPreviousScreen={true}>
        <Stack.Screen name="Home" component={HomeScreen} />

        <Stack.Group screenOptions={{ presentation: 'modal' }}>
          <Stack.Screen name="Details" component={DetailsScreen}
            options={{ presentation: 'transparentModal' }}
          />
          <Stack.Screen name="A" component={A} />
        </Stack.Group>
      </Stack.Navigator>

    </NavigationContainer>
  );
}

export default App;
</code>```

答:
I think you can use BackHandler on Screen A.

So you should listen for BackHandler in Screen A and the navigate to Home screen when it's triggered.

Your Screen A should look like this:

```<code>  import { BackHandler } from 'react-native';

  function handleBackPressHandler() {
    navigation.navigate('HomeScreen');
    return true;
  }

  useEffect(() => {
    BackHandler.addEventListener('hardwareBackPress', handleBackPressHandler);

    return () => {
      BackHandler.removeEventListener('hardwareBackPress', handleBackPressHandler);
    };
  }, []);
</code>```

Body:
I am do do navigation in react native where all the back arrow or back press return to initial route. On last on option is to list to onBackPreessed event and passs call to init route which is home.
I am hoping their will be props for allowing the Screen to return to init   Screen in stack navigations

What is happening

On home:
go details then go A
back arrow press in A, it  return  back to  details

Need actions

On home:
go details then go A
back arrow press in A  return  back to home instead of details

The code I try

import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}

function DetailsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
      <Button
        title="Go to A"
        onPress={() => navigation.navigate('A')}
      />

    </View>
  );
}
function A({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>AAAAAAAAAAAAAAAAAAA Screen</Text>

    </View>
  );
}
const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home" detachInactiveScreens={true}
        detachPreviousScreen={true}>
        <Stack.Screen name="Home" component={HomeScreen} />

        <Stack.Group screenOptions={{ presentation: 'modal' }}>
          <Stack.Screen name="Details" component={DetailsScreen}
            options={{ presentation: 'transparentModal' }}
          />
          <Stack.Screen name="A" component={A} />
        </Stack.Group>
      </Stack.Navigator>

    </NavigationContainer>
  );
}

export default App;

Body:
I think you can use BackHandler on Screen A.

So you should listen for BackHandler in Screen A and the navigate to Home screen when it's triggered.

Your Screen A should look like this:

  import { BackHandler } from 'react-native';

  function handleBackPressHandler() {
    navigation.navigate('HomeScreen');
    return true;
  }

  useEffect(() => {
    BackHandler.addEventListener('hardwareBackPress', handleBackPressHandler);

    return () => {
      BackHandler.removeEventListener('hardwareBackPress', handleBackPressHandler);
    };
  }, []);


问:
SQL request : how to make a particular select with multi tables and calcul?
Here's my problem. I've 4 tables on an Oracle Database:

Team(teamID, teamName)

TeamMembers(membersID, teamID, membersStatusID)

Members(membersID, membersName)

Status(membersStatusID, statusName)

I need to gets the teamName, the numbers of teamMembers in these teams and the name of the members who have the status "Captain"... all of this in one SELECT in SQL.

Many hours on this and no solution... any idea?

Edit: I need to see all teams, even if there's no members in it.

答:
```<code>select t.team_id, t.teamName, count(tm.teamid), m.membersname
from team t, teammembers tm, members m, status s
where t.teamid = tm.teamid (+)
and tm.membersid = m.membersid (+)
and m.membersstatusid = s.statusid (+)
and s.statusname = 'Captain'
group by t.team_id, t.teamName, m.membersname
</code>```


问:
Find the smallest positive integer that does not occur in a given sequence
I was trying to solve this problem:

Write a function:

```<code>class Solution { public int solution(int[] A); }
</code>```

that, given an array A of N integers, returns the smallest positive
integer (greater than 0) that does not occur in A.

For example, given A = [1, 3, 6, 4, 1, 2], the function should return
5.

```<code>Given A = [1, 2, 3], the function should return 4.

Given A = [−1, −3], the function should return 1.
</code>```

Assume that:

N is an integer within the range [1..100,000]; each element of array A
is an integer within the range [−1,000,000..1,000,000]. Complexity:

expected worst-case time complexity is O(N); expected worst-case space
complexity is O(N) (not counting the storage required for input
arguments).

I wrote the solution below which gives a low performance, however, I can't see the bug.

public static int solution(int[] A) {

        Set<Integer> set = new TreeSet<>();

        for (int a : A) {
            set.add(a);
        }

        int N = set.size();

        int[] C = new int[N];

        int index = 0;

        for (int a : set) {
            C[index++] = a;
        }

        for (int i = 0; i < N; i++) {

            if (C[i] > 0 && C[i] <= N) {
                C[i] = 0;
            }
        }

        for (int i = 0; i < N; i++) {

            if (C[i] != 0) {
                return (i + 1);
            }
        }

        return (N + 1);
    }

```

The score is provided here,

I will keep investigating myself, but please inform me if you can see better.

答:
This code has been written in C

The existing was in C++ and Java

```<code>function solution(A) {
    // only positive values, sorted
    int i,j,small,large,value,temp,skip=0;
    int arr[N];
    for(i=0;i<N;i++)
    {
        value = A[i];
        for(j=i;j<N;j++)
        {
            if(value > A[j])
            {
                temp = value;
                value = A[j];
                A[j] = temp;
            }
        }

        arr[i] = value;
    }
    small = arr[0];
    large = arr[N-1];
    for(i=0;i<N;i++)
    {
        if(arr[i] == arr[i+1])
        {
            for(j=i;j<(N);j++)
            {
                arr[j] = arr[j+1];
            }
            skip++;
        }

    }
    if(large < 0)
    {
        return 1;
    }
    for(i=0;i<(N);i++)
    {
        if(arr[i] != (small+i))
        {
            return (arr[i-1]+1);
        }
        else if(arr[i] == large)
        {
            return (large+1);
        }
    }
}
</code>```

Body:
I was trying to solve this problem:

Write a function:

class Solution { public int solution(int[] A); }

that, given an array A of N integers, returns the smallest positive
integer (greater than 0) that does not occur in A.

For example, given A = [1, 3, 6, 4, 1, 2], the function should return
5.

Given A = [1, 2, 3], the function should return 4.

Given A = [−1, −3], the function should return 1.

Assume that:

N is an integer within the range [1..100,000]; each element of array A
is an integer within the range [−1,000,000..1,000,000]. Complexity:

expected worst-case time complexity is O(N); expected worst-case space
complexity is O(N) (not counting the storage required for input
arguments).

I wrote the solution below which gives a low performance, however, I can't see the bug.

public static int solution(int[] A) {

        Set<Integer> set = new TreeSet<>();

        for (int a : A) {
            set.add(a);
        }

        int N = set.size();

        int[] C = new int[N];

        int index = 0;

        for (int a : set) {
            C[index++] = a;
        }

        for (int i = 0; i < N; i++) {

            if (C[i] > 0 && C[i] <= N) {
                C[i] = 0;
            }
        }

        for (int i = 0; i < N; i++) {

            if (C[i] != 0) {
                return (i + 1);
            }
        }

        return (N + 1);
    }

The score is provided here,

I will keep investigating myself, but please inform me if you can see better.

Body:
This code has been written in C

The existing was in C++ and Java

function solution(A) {
    // only positive values, sorted
    int i,j,small,large,value,temp,skip=0;
    int arr[N];
    for(i=0;i<N;i++)
    {
        value = A[i];
        for(j=i;j<N;j++)
        {
            if(value > A[j])
            {
                temp = value;
                value = A[j];
                A[j] = temp;
            }
        }

        arr[i] = value;
    }
    small = arr[0];
    large = arr[N-1];
    for(i=0;i<N;i++)
    {
        if(arr[i] == arr[i+1])
        {
            for(j=i;j<(N);j++)
            {
                arr[j] = arr[j+1];
            }
            skip++;
        }

    }
    if(large < 0)
    {
        return 1;
    }
    for(i=0;i<(N);i++)
    {
        if(arr[i] != (small+i))
        {
            return (arr[i-1]+1);
        }
        else if(arr[i] == large)
        {
            return (large+1);
        }
    }
}


问:
How to check if a Class method has been called only once with JEST

Question:

How should I check if the Service.init() method has been called only once ?

Error

```<code>expect(received).toHaveBeenCalledTimes(expected)

    Matcher error: received value must be a mock or spy function

    Received has type:  object
    Received has value: {"constructor": [Function Statistics], "init": [Function init]}

      13 |     const Module3 = Service
      14 |
    > 15 |     expect(Service).toHaveBeenCalledTimes(1)
         |                     ^
      16 |   })
      17 |
</code>```

Code

index.spec.js:

```<code>  it('should initialized a class instance only once', async () => {
    const Service = require('./index')
    jest.mock('./index')

    const Module1 = Service
    const Module2 = Service
    const Module3 = Service

    expect(Service).toHaveBeenCalledTimes(1)
  })
</code>```

and basically a class code:

```<code>class Statistics {
  constructor () {
    console.log(' Constructor')
    this.init()
  }

  async init () {
    // Wait 500ms
    console.log(' Initializing')
    await new Promise(resolve => setTimeout(resolve('ok'), 500))
    console.log(' Initialization complete')
  }
}

module.exports = new Statistics()
</code>```

答:
You are not calling the function before checking it. An example from the documentation - Use .toHaveBeenCalledTimes to ensure that a mock function got called the exact number of times.

For example, let's say you have a drinkEach(drink, Array) function that takes a drink function and applies it to array of passed beverages. You might want to check that the drink function was called an exact number of times. You can do that with this test suite:

```<code>test('drinkEach drinks each drink', () => {
  const drink = jest.fn();
  drinkEach(drink, ['lemon', 'octopus']); // calling the function and checking it
  expect(drink).toHaveBeenCalledTimes(2);
});
</code>```

In your test spec, creating the instance will be enough to call init:

```<code>  it('should initialized a class instance only once', async () => {
    const Service = require('./index');
    jest.mock('./index')

    const Module1 = Service
    const Module2 = Service
    const Module3 = Service
    const mockServiceInstance = Service.init();
    expect(Service).toHaveBeenCalledTimes(1)
  })
</code>```

Body:
Question:

How should I check if the Service.init() method has been called only once ?

Error

expect(received).toHaveBeenCalledTimes(expected)

    Matcher error: received value must be a mock or spy function

    Received has type:  object
    Received has value: {"constructor": [Function Statistics], "init": [Function init]}

      13 |     const Module3 = Service
      14 |
    > 15 |     expect(Service).toHaveBeenCalledTimes(1)
         |                     ^
      16 |   })
      17 |

Code

index.spec.js:

  it('should initialized a class instance only once', async () => {
    const Service = require('./index')
    jest.mock('./index')

    const Module1 = Service
    const Module2 = Service
    const Module3 = Service

    expect(Service).toHaveBeenCalledTimes(1)
  })

and basically a class code:

class Statistics {
  constructor () {
    console.log(' Constructor')
    this.init()
  }

  async init () {
    // Wait 500ms
    console.log(' Initializing')
    await new Promise(resolve => setTimeout(resolve('ok'), 500))
    console.log(' Initialization complete')
  }
}

module.exports = new Statistics()

Body:
You are not calling the function before checking it. An example from the documentation - Use .toHaveBeenCalledTimes to ensure that a mock function got called the exact number of times.

For example, let's say you have a drinkEach(drink, Array) function that takes a drink function and applies it to array of passed beverages. You might want to check that the drink function was called an exact number of times. You can do that with this test suite:

test('drinkEach drinks each drink', () => {
  const drink = jest.fn();
  drinkEach(drink, ['lemon', 'octopus']); // calling the function and checking it
  expect(drink).toHaveBeenCalledTimes(2);
});

In your test spec, creating the instance will be enough to call init:

  it('should initialized a class instance only once', async () => {
    const Service = require('./index');
    jest.mock('./index')

    const Module1 = Service
    const Module2 = Service
    const Module3 = Service
    const mockServiceInstance = Service.init();
    expect(Service).toHaveBeenCalledTimes(1)
  })


问:
axios.put is not working when sending query object
I was trying to send put request using axios to update information about a book in mongodb, the code is working fine when using postman but it is not working using axios.put used inside react component when submitting, while axios.delete is working fine. I think the problem is that sending the query object in that way is not the right way but I am not able to find the solution.
This is the function that handleSubmit,

the 'id' is the id of the book

'updates' is a state object that contains all the changes that should happen in the book data.

And the second function handleChange is the function that setupdates according to changes in the inputs

```<code>const handleSubmit = async (e) => {
  e.preventDefault();
  try {
    const res = await axios.put("http://localhost:8000/book/edit/" + id, {
      params: {
        updates,
      },
    });
  setNewBook(res.data)
  } catch (err) {
    console.log(err);
  }
};

   const handleChange = (e) => {
      e.preventDefault();
      const value = e.target.value;
      setUpdates({
        ...updates,
        [e.target.name]: value,
      });
    };
</code>```

答:
maybe you misunderstood the axios put method. as per the axios docs provided (https://github.com/axios/axios#axiosputurl-data-config) the correct structure is axios.put(url[, data[, config]])

The first parameter is URL

The second parameter is data (body request).

3rd parameter is config (you leave params in this parameter)

It should be like this

```<code>const res = await axios.put("http://localhost:8000/book/edit/" + id, null, {
       params: {
         updates,
       },
     });
</code>```

I hope this can help you

Body:
I was trying to send put request using axios to update information about a book in mongodb, the code is working fine when using postman but it is not working using axios.put used inside react component when submitting, while axios.delete is working fine. I think the problem is that sending the query object in that way is not the right way but I am not able to find the solution.
This is the function that handleSubmit,

the 'id' is the id of the book

'updates' is a state object that contains all the changes that should happen in the book data.

And the second function handleChange is the function that setupdates according to changes in the inputs

const handleSubmit = async (e) => {
  e.preventDefault();
  try {
    const res = await axios.put("http://localhost:8000/book/edit/" + id, {
      params: {
        updates,
      },
    });
  setNewBook(res.data)
  } catch (err) {
    console.log(err);
  }
};

   const handleChange = (e) => {
      e.preventDefault();
      const value = e.target.value;
      setUpdates({
        ...updates,
        [e.target.name]: value,
      });
    };

Body:
maybe you misunderstood the axios put method. as per the axios docs provided (https://github.com/axios/axios#axiosputurl-data-config) the correct structure is axios.put(url[, data[, config]])

The first parameter is URL

The second parameter is data (body request).

3rd parameter is config (you leave params in this parameter)

It should be like this

const res = await axios.put("http://localhost:8000/book/edit/" + id, null, {
       params: {
         updates,
       },
     });

I hope this can help you


问:
Flow type for PanResponder like in example
Cannot find flow type for PanResponder like shown in the official react-native example.

Example here: https://github.com/facebook/react-native/blob/0ccedf3964b1ebff43e4631d1e60b3e733096e56/RNTester/js/examples/PanResponder/PanResponderExample.js#L17

This does not work:

```<code>import type {
  PanResponderInstance,
} from 'react-native';
</code>```

For typing PanResponders:

```<code>// @flow

type Props = {…};
type State = {…};
class Screen extends Component<Props, State> {
  _panresponder: PanResponderInstance
  …
}
</code>```

I want to use the flow type for PanResponder like in the example linked above. How can I access the type for PanResponder (PanResponderInstance) from react-native?

答:
```<code>import type {
   PanResponderInstance,
} from 'react-native';
</code>```

This will work on react native 0.64

Body:
Cannot find flow type for PanResponder like shown in the official react-native example.

Example here: https://github.com/facebook/react-native/blob/0ccedf3964b1ebff43e4631d1e60b3e733096e56/RNTester/js/examples/PanResponder/PanResponderExample.js#L17

This does not work:

import type {
  PanResponderInstance,
} from 'react-native';

For typing PanResponders:

// @flow

type Props = {…};
type State = {…};
class Screen extends Component<Props, State> {
  _panresponder: PanResponderInstance
  …
}

I want to use the flow type for PanResponder like in the example linked above. How can I access the type for PanResponder (PanResponderInstance) from react-native?

Body:
import type {
   PanResponderInstance,
} from 'react-native';

This will work on react native 0.64


问:
Make bokeh's custom TapTool work for holoviews
I would like to use bokeh's TapTool to open a different URL when clicking on each of some holoviews.Polygons. An perfect example of how this works in bokeh is in the bokeh docs for point data. However, when I try to use it in holoviews, it doesn't seem to work.
The closest thing I could get to work is this:

```<code>import geoviews as gv
from bokeh.models import OpenURL, TapTool

url = 'https://google.@domain'
taptool = TapTool()
taptool.callback = OpenURL(url=url)
p = gv.Polygons(data, vdims=['Area', 'domain'], crs=ccrs.PlateCarree).options(alpha=1, tools=['hover', taptool])
p
</code>```

The plot shows up nicely, and also the triggering of the URL opening works fine, however the parsing of the "@domain" doesn't work and the URL is "google.???"
What is wrong here?

答:
You can access the bokeh figure in holoviews using the hook option, described in the HoloViews docs here.

With access to the bokeh figure, you can then do things like wire up arbitrary callbacks.
For example, access cursor coords in a python callback, or handle Tap events:

import holoviews as hv
from bokeh.events import MouseMove, Tap

def hook(plot, element):
  # allows access to the bokeh `figure` object
  # so we can bind figure interaction events
  plot.state.on_event(MouseMove, on_mouse_move)
  plot.state.on_event(Tap, on_click)

  # The handles contain common plot objects
  # plot.handles

def on_mouse_move(event):
  # do something

def on_click(event):
   # do something

my_hv_plot = hv.Points([])
my_hv_plot.opts(hooks=[hook])
```

Body:
I would like to use bokeh's TapTool to open a different URL when clicking on each of some holoviews.Polygons. An perfect example of how this works in bokeh is in the bokeh docs for point data. However, when I try to use it in holoviews, it doesn't seem to work.
The closest thing I could get to work is this:

import geoviews as gv
from bokeh.models import OpenURL, TapTool

url = 'https://google.@domain'
taptool = TapTool()
taptool.callback = OpenURL(url=url)
p = gv.Polygons(data, vdims=['Area', 'domain'], crs=ccrs.PlateCarree).options(alpha=1, tools=['hover', taptool])
p

The plot shows up nicely, and also the triggering of the URL opening works fine, however the parsing of the "@domain" doesn't work and the URL is "google.???"
What is wrong here?


问:
Disable suggestions for EditText
What I have tried:

specifying the inputType for the EditText on the main.xml page as...

```<code>textFilter
text|textNoSuggestions
textNoSuggestions
</code>```

In the java file in the onCreate

```<code>EditText hex = (EditText) findViewById(R.id.editHex);
hex.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
</code>```

I'm running this on an emulator using API 13.

答:
This actually works for me when i put:
android:importantForAutofill="no" in editText field.

Happy coding :)

Title: Disable suggestions for EditText

Body:
What I have tried:

specifying the inputType for the EditText on the main.xml page as...

textFilter
text|textNoSuggestions
textNoSuggestions

In the java file in the onCreate

EditText hex = (EditText) findViewById(R.id.editHex);
hex.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

I'm running this on an emulator using API 13.


问:
Why is my if elif statement only working for my if statement?
I am continuing on with a bigger project and for this part I am trying to use wallstreet to pull the implied volatility of a certain call or put for options trading. I am able to get it to work individually for calls and puts, but not when I combine them to make it one action.

input variables like aapl 180 call 5 days till expiration -> use an if elif statement for the functions for calls and puts to get the respective IV -> return that IV as a variable for further math in a different section

here is an example of the latest that I have. Any help is appreciated I am newer to coding so if this is obvious apologies.

And for reference my problem is that when I run the call and put functions separately they give two different numbers, but like this regardless of a P or C input, i get the value for calls.

Thanks.

```<code>from wallstreet import Call, Put
import datetime
from datetime import date

ticker = "tsla"
K = 900
today = date.today()
expiry = today + datetime.timedelta(days=5)
y = expiry.year
d = expiry.day
m = expiry.month
CorP = "P"

if CorP == "c" or "C":
    call = Call(ticker, d=d, m=m, y=y, strike=K)
    sigma = call.implied_volatility()
elif CorP == "p" or "P":
    put = Put(ticker, d=d, m=m, y=y, strike=K)
    sigma = put.implied_volatility()

print(sigma)
</code>```

答:
I believe there's a logic error in your code,

replace the line

```<code>if CorP == "c" or "C":
</code>```

with

```<code>if CorP == "c" or CroP == "C":
</code>```

and same with elif part

replace

```<code>elif CorP == "p" or "P":
</code>```

with

```<code>elif CorP == "p" or CorP == "P":
</code>```

Body:
I am continuing on with a bigger project and for this part I am trying to use wallstreet to pull the implied volatility of a certain call or put for options trading. I am able to get it to work individually for calls and puts, but not when I combine them to make it one action.

input variables like aapl 180 call 5 days till expiration -> use an if elif statement for the functions for calls and puts to get the respective IV -> return that IV as a variable for further math in a different section

here is an example of the latest that I have. Any help is appreciated I am newer to coding so if this is obvious apologies.

And for reference my problem is that when I run the call and put functions separately they give two different numbers, but like this regardless of a P or C input, i get the value for calls.

Thanks.

from wallstreet import Call, Put
import datetime
from datetime import date

ticker = "tsla"
K = 900
today = date.today()
expiry = today + datetime.timedelta(days=5)
y = expiry.year
d = expiry.day
m = expiry.month
CorP = "P"

if CorP == "c" or "C":
    call = Call(ticker, d=d, m=m, y=y, strike=K)
    sigma = call.implied_volatility()
elif CorP == "p" or "P":
    put = Put(ticker, d=d, m=m, y=y, strike=K)
    sigma = put.implied_volatility()

print(sigma)

Body:
I believe there's a logic error in your code,

replace the line

if CorP == "c" or "C":

with

if CorP == "c" or CroP == "C":

and same with elif part

replace

elif CorP == "p" or "P":

with

elif CorP == "p" or CorP == "P":


问:
How can we use Python to load files into Azure Blob Storage or Azure Data Lake Storage?
I am relatively new to Azure. I am trying to figure out how to use Python to load files into an Azure storage account, such as Data Lake or Blob Storage. I read the info from the following two URLs, and I am stuck about how to proceed.

https://learn.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-directory-file-acl-python

https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python

Maybe I missed something from those resource, or they are not right for what I am trying to do. I just want to get a simple example working so I can start to understand the process better.  I would like to do either of the following.

copy a file from my desktop to Azure Blob Storage or Data Lake Storage

download a file from a URL and save it to Azure Blob Storage or Data Lake Storage

I want to run Python from Azure, so I want the code to run in a 'Runbook'. How can I do either item 1 or 2, as described above, or ideally both 1 and 2?

答:
You need to add the azure_storage_blob python package in your automation account

Then, you can use the python code below to upload file to azure blob storage from a URL:

```<code>from azure.storage.blob import BlobServiceClient
connect_str = "StorageAccountConnectString"
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
destination_blob = blob_service_client.get_blob_client("ContainerName","BlobName")
destination_blob.start_copy_from_url("URL")
</code>```

Body:
You need to add the azure_storage_blob python package in your automation account

Then, you can use the python code below to upload file to azure blob storage from a URL:

from azure.storage.blob import BlobServiceClient
connect_str = "StorageAccountConnectString"
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
destination_blob = blob_service_client.get_blob_client("ContainerName","BlobName")
destination_blob.start_copy_from_url("URL")


答:
You should use the lower() function to simplify your if statement

```<code>if CorP.lower() == "c": # Converts capital "C" to lower "c" and runs if statement
    call = Call(ticker, d=d, m=m, y=y, strike=K)
    sigma = call.implied_volatility()
elif CorP.lower() == "p": # Converts capital "P" to lower "p" and runs if statement
    put = Put(ticker, d=d, m=m, y=y, strike=K)
    sigma = put.implied_volatility()
</code>```

Title: Why is my if elif statement only working for my if statement?

Body:
You should use the lower() function to simplify your if statement

if CorP.lower() == "c": # Converts capital "C" to lower "c" and runs if statement
    call = Call(ticker, d=d, m=m, y=y, strike=K)
    sigma = call.implied_volatility()
elif CorP.lower() == "p": # Converts capital "P" to lower "p" and runs if statement
    put = Put(ticker, d=d, m=m, y=y, strike=K)
    sigma = put.implied_volatility()


问:
Trying to find guild member list for discord guilds
```<code>async def get_guild_members(guild_id: int):
    guild = bot.fetch_guild(guild_id)

    return guild.member_count

get_guild_members(789226204980707409)
</code>```

I'm using this code to try to find the memeber count of a guild on discord. WHen I run it it returns
<coroutine object get_guild_members at 0x7ffd518ef4c0>
What does this mean? How do I do it correctly?

答:
This problem stems from your lack of knowledge of asyncio. You don't call asynchronous functions like regular functions but rather use asyncio.run(coro()) or the await coro() syntax inside another async function.

REGULAR FUNCTION

def main():
    pass

main()
```
<p><strong>ASYNCIO FUNCTION</strong></p>
<pre class="lang-py prettyprint-override"><code>import asyncio

async def get_guild_members(guild_id: int):
    guild = await bot.fetch_guild(guild_id)

    return guild.member_count

member_count = asyncio.run(get_guild_members(78922624980707409))
</code>```

Body:
async def get_guild_members(guild_id: int):
    guild = bot.fetch_guild(guild_id)

    return guild.member_count

get_guild_members(789226204980707409)

I'm using this code to try to find the memeber count of a guild on discord. WHen I run it it returns
<coroutine object get_guild_members at 0x7ffd518ef4c0>
What does this mean? How do I do it correctly?

Body:
This problem stems from your lack of knowledge of asyncio. You don't call asynchronous functions like regular functions but rather use asyncio.run(coro()) or the await coro() syntax inside another async function.

REGULAR FUNCTION

def main():
    pass

main()

ASYNCIO FUNCTION

import asyncio

async def get_guild_members(guild_id: int):
    guild = await bot.fetch_guild(guild_id)

    return guild.member_count

member_count = asyncio.run(get_guild_members(78922624980707409))


问:
Currently you have no contract instances to interact with
I'm trying to write my first smart contract by copying code from a video online. The instructor could "Deploy" but for some reason I'm getting this error message even though the code is exactly the same.

答: I can confirm if all else fails, refresh the page. I ran into the same issue  and after refreshing the page everything was working correctly again. It was the first time I had ran into this issue, so I too was a little puzzled. I usually start a new browser session so it was not an issue before.</p>


问:
Xcode 4.2 Compilation Failed with prototype cell
I'm trying out the new Xcode 4.2 Beta and I'm wondering if my code is wrong or if I'm bumping in to an bug.

The new Storyboard feature is promising but extremely buggy at the moment. Right now I've created an simple project with a tableview. This tableview will be "Grouped style" containing UITextFields. The new "Prototype Cell" feature of storyboard let's you create a prototype cell in GUI that you can draw with the "Reuse identifier" in the method cellForRowAtIndexPath.
When I drag in a UITextField in this "prototype cell" and draw it out, it works great!

However! When I reference this textfield to an outlet in my code I get the error:
Uncategorized
Compilation failed. Unable to write to path:...(Path to DerivedData)

Why is this?
Is it a bug?
Anyone else get this?

答:
I don't have the perfect solution to your problem but I had the same and I found a way to make it works (without linking the outlet to the TableViewController).

Just try to recreate your view from scratch and Build & Run every time you add a component.

In order add a TableViewController => Test if it shows an empty table.

Design your custom cell and link your cell's Outlets to it. (Without forgeting to change the Class of your TableViewCell) => Again test it

Then change the Class of the TableViewController to your class and now you would be able to access to your cell's outlets.

It worked for me. I hope it will for you.


问:
MySQL: update specific property value of a JSON object in a JSON Array
I have MySQL DB with a table that has a JSON column.

The sample data in the columns looks as below:

[{"id": 1, "value": 23.4}, {"id": 2, "value": 54.3}, {"id": 3, "value": 4.33}]

I wanted to update the value property of all the objects in the column to 0.0(let's say)

My attempt:

update table_name set json_col = JSON_SET(json_col, '$[*].value', 0.0);

The error statement from MySQL:

ERROR 3149 (42000): In this situation, path expressions may not contain the * and ** tokens.

How can I make this work?

答:
You cannot perform multiple update. You must either update one-by-one value in recursive CTE or parse/replace/reconstruct:

UPDATE test
JOIN ( SELECT id, JSON_ARRAYAGG(JSON_REPLACE(object, '$.value', 0)) value
       FROM test
       CROSS JOIN JSON_TABLE( test.value,
                              '$[*]' COLUMNS (object JSON PATH '$')) jsontable
       GROUP BY id ) data_for_update USING (id)
SET test.value = data_for_update.value;
```

fiddle (with step-by-step explanations).

Body:
You cannot perform multiple update. You must either update one-by-one value in recursive CTE or parse/replace/reconstruct:

UPDATE test
JOIN ( SELECT id, JSON_ARRAYAGG(JSON_REPLACE(object, '$.value', 0)) value
       FROM test
       CROSS JOIN JSON_TABLE( test.value,
                              '$[*]' COLUMNS (object JSON PATH '$')) jsontable
       GROUP BY id ) data_for_update USING (id)
SET test.value = data_for_update.value;

fiddle (with step-by-step explanations).


问:
Store Kivy objects/ids in list
I need to store kivy object id-s (and some other info) in a list, but it does`nt seeme to work with kivy.
there are checkboxes for every button, witch should enable/disable the buttons.
the enabling/disabling should happen after a button is pressed (not immediately, like id could be done in kv file)
I could write a punch of if,elif statements and it would work like that, but I will have a lot of buttons and different button lists so I would like to go through the checkboxses with for loop.</p>
```<code>    #Here`s my python code:

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty

class MainLayout(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        chk1 = ObjectProperty(None)
        btn1 = ObjectProperty(None)
        chk2 = ObjectProperty(None)
        btn2 = ObjectProperty(None)
        chk3 = ObjectProperty(None)
        btn3 = ObjectProperty(None)
        chk4 = ObjectProperty(None)
        btn4 = ObjectProperty(None)

        #(checkbox id, button id, value)
        self.object_list = [(chk1, btn1, 1),
                            (chk2, btn2, 2),
                            (chk3, btn3, 3),
                            (chk4, btn4, 4)]

    def myfunc(self):
        for i in self.object_list:
            if i[0].active == True:
                i[1].disabled = False

            elif i[0].active == False:
                i[1].disabled = True

class CheckboxTestApp(App):
    pass

if __name__=='__main__':
    CheckboxTestApp().run()

#and here`s the .kv
MainLayout:

<MainLayout>:

    chk1 : chk1
    btn1 : btn1
    chk2 : chk2
    btn2 : btn2
    chk3 : chk3
    btn3 : btn3
    chk4 : chk4
    btn4 : btn4

    cols: 4
    CheckBox:
        id: chk1
        active: True
    Button:
        id: btn1
        text: '1'
        on_press: root.myfunc()

    CheckBox:
        id: chk2
        active: True
    Button:
        id: btn2
        text: '2'
        on_press: root.myfunc()

    CheckBox:
        id: chk3
        active: True
    Button:
        id: btn3
        text: '3'
        on_press: root.myfunc()

    CheckBox:
        id: chk4
        active: True
    Button:
        id: btn4
        text: '4'
        on_press: root.myfunc()
</code>```

答:
I found a solution to my problem using kivy built in dictionary ids.
I only updated the python code so here it is.</p>
```<code>#python code
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty

class MainLayout(GridLayout):
    objects = [('chk1', 'btn1', 1),
               ('chk2', 'btn2', 2),
               ('chk3', 'btn3', 3),
               ('chk4', 'btn4', 4)]

    def myfunc(self):
        for i in self.objects:
            if self.ids[i[0]].active == True:
                self.ids[i[1]].disabled = False

            elif self.ids[i[0]].active == False:
                self.ids[i[1]].disabled = True

class CheckboxTestApp(App):
    pass

if __name__=='__main__':
    CheckboxTestApp().run()
</code>```

Title: Store Kivy objects/ids in list

Body:
I need to store kivy object id-s (and some other info) in a list, but it does`nt seeme to work with kivy.
there are checkboxes for every button, witch should enable/disable the buttons.
the enabling/disabling should happen after a button is pressed (not immediately, like id could be done in kv file)
I could write a punch of if,elif statements and it would work like that, but I will have a lot of buttons and different button lists so I would like to go through the checkboxses with for loop.

    #Here`s my python code:

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty

class MainLayout(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        chk1 = ObjectProperty(None)
        btn1 = ObjectProperty(None)
        chk2 = ObjectProperty(None)
        btn2 = ObjectProperty(None)
        chk3 = ObjectProperty(None)
        btn3 = ObjectProperty(None)
        chk4 = ObjectProperty(None)
        btn4 = ObjectProperty(None)

        #(checkbox id, button id, value)
        self.object_list = [(chk1, btn1, 1),
                            (chk2, btn2, 2),
                            (chk3, btn3, 3),
                            (chk4, btn4, 4)]

    def myfunc(self):
        for i in self.object_list:
            if i[0].active == True:
                i[1].disabled = False

            elif i[0].active == False:
                i[1].disabled = True

class CheckboxTestApp(App):
    pass

if __name__=='__main__':
    CheckboxTestApp().run()

#and here`s the .kv
MainLayout:

<MainLayout>:

    chk1 : chk1
    btn1 : btn1
    chk2 : chk2
    btn2 : btn2
    chk3 : chk3
    btn3 : btn3
    chk4 : chk4
    btn4 : btn4

    cols: 4
    CheckBox:
        id: chk1
        active: True
    Button:
        id: btn1
        text: '1'
        on_press: root.myfunc()

    CheckBox:
        id: chk2
        active: True
    Button:
        id: btn2
        text: '2'
        on_press: root.myfunc()

    CheckBox:
        id: chk3
        active: True
    Button:
        id: btn3
        text: '3'
        on_press: root.myfunc()

    CheckBox:
        id: chk4
        active: True
    Button:
        id: btn4
        text: '4'
        on_press: root.myfunc()

Body:
I found a solution to my problem using kivy built in dictionary ids.
I only updated the python code so here it is.

#python code
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty

class MainLayout(GridLayout):
    objects = [('chk1', 'btn1', 1),
               ('chk2', 'btn2', 2),
               ('chk3', 'btn3', 3),
               ('chk4', 'btn4', 4)]

    def myfunc(self):
        for i in self.objects:
            if self.ids[i[0]].active == True:
                self.ids[i[1]].disabled = False

            elif self.ids[i[0]].active == False:
                self.ids[i[1]].disabled = True

class CheckboxTestApp(App):
    pass

if __name__=='__main__':
    CheckboxTestApp().run()


问:
Bound Multiple Times issue when using Hilt for UI Test, TestInstalln
I've created a fake urlprovider binding and annotated with TestInstallIN

```<code>@Module
@TestInstallIn(
    components = [SingletonComponent::class],
    replaces = [UrlModuleBindings::class]
)
abstract class FakeAppBindings {

    @Binds
    abstract fun bindsUrlProvider(urlProvider: FakeUrlProvider): UrlProvider
}
</code>```

my Prod UrlProvider looks like

```<code>@Module
@InstallIn(SingletonComponent::class)
abstract class UrlModuleBindings {

    @Binds
    abstract fun bindsUrlProvider(urlProvider: DefaultUrlProvider): UrlProvider
}
</code>```

when I'm running the UI test getting the error UrlProvider is bound multiple times:

As per the documentation everything seems correct, can I know what is the issue with this.

答:
Thanks to Brad, the issue was with the AppModule, I was using Includes whereas hilt doesn't need Includes as it already has InstallIn annotation for this purpose. Once I remove it the UI test starts to work.

More details.

https://github.com/google/dagger/issues/3209

Body:
I've created a fake urlprovider binding and annotated with TestInstallIN

@Module
@TestInstallIn(
    components = [SingletonComponent::class],
    replaces = [UrlModuleBindings::class]
)
abstract class FakeAppBindings {

    @Binds
    abstract fun bindsUrlProvider(urlProvider: FakeUrlProvider): UrlProvider
}

my Prod UrlProvider looks like

@Module
@InstallIn(SingletonComponent::class)
abstract class UrlModuleBindings {

    @Binds
    abstract fun bindsUrlProvider(urlProvider: DefaultUrlProvider): UrlProvider
}

when I'm running the UI test getting the error UrlProvider is bound multiple times:

As per the documentation everything seems correct, can I know what is the issue with this.


问:
What's syntax if i need to update some employee?
```<code>Emp_name = []
Emp_id = []
Emp_dep = []
num = 5
for i in range(num):
    x = input("enter the name of employees")
    Emp_name.append(x)

    i = input("enter the id of employees")
    Emp_id.append(i)

    d = input("enter the department of employees")
    Emp_dep.append(d)
delete = str(input(" Enter the name of employee you need to delete"))
if delete in Emp_name:
    pos = Emp_name.index(delete)
    Emp_name.pop(pos)
    Emp_id.pop(pos)
    Emp_dep.pop(pos)

print(Emp_name)
print(Emp_id)
print(Emp_dep)
</code>```

If I need to update some employee what's syntax tp fo that?
I am working in employee application

答:
to update employess I have modified your code and added update logic:

```<code>Emp_name = []
Emp_id = []
Emp_dep = []
num = 3
for i in range(num):
    x = input("enter the name of employees")
    Emp_name.append(x)

    i = input("enter the id of employees")
    Emp_id.append(i)

    d = input("enter the department of employees")
    Emp_dep.append(d)

#UPDATING employee

id = str(input(" Enter the id of employee you need to update"))
if id in Emp_id:
    pos = Emp_id.index(id)
    Emp_name[pos] = input("enter new name : ")
    Emp_id[pos] = input("enter new id : ")
    Emp_dep[pos] = input("enter new department : ")

print(Emp_name)
print(Emp_id)
print(Emp_dep)
</code>```

Use a class of Employee type and create objects of it . It will help you to manage employees much efficiently.

```<code>class Employee:
    def __init__(self, name="", id="", dept=""):
        self.name = name
        self.id = id
        self.dept = dept

    def __str__(self):
        return self.name + " " + self.id + " " + self.dept

employees = list()

num = 3

for i in range(num):
    name = input("enter the name of employees : ")
    id = input("enter the id of employees : ")
    dept = input("enter the department of employees : ")

    emp = Employee(name, id, dept)
    employees.append(emp)

for e in employees:
    print(e)

delete = input(" Enter the name of employee you need to delete : ")

for index, emp in enumerate(employees):
    if emp.name == delete:
        employees.pop(index)
        break

for e in employees:
    print(e)
</code>```

Output:

```<code>python/src/test/employee.py
enter the name of employees : dev
enter the id of employees : 1
enter the department of employees : dept
enter the name of employees : dev2
enter the id of employees : dept
enter the department of employees : dept
enter the name of employees : dev
enter the id of employees : 3
enter the department of employees : dept
dev 1 dept
dev2 dept dept
dev 3 dept
Enter the name of employee you need to delete : dev
dev2 dept dept
dev 3 dept
</code>```

Body:
Emp_name = []
Emp_id = []
Emp_dep = []
num = 5
for i in range(num):
    x = input("enter the name of employees")
    Emp_name.append(x)

    i = input("enter the id of employees")
    Emp_id.append(i)

    d = input("enter the department of employees")
    Emp_dep.append(d)
delete = str(input(" Enter the name of employee you need to delete"))
if delete in Emp_name:
    pos = Emp_name.index(delete)
    Emp_name.pop(pos)
    Emp_id.pop(pos)
    Emp_dep.pop(pos)

print(Emp_name)
print(Emp_id)
print(Emp_dep)

If I need to update some employee what's syntax tp fo that?
I am working in employee application

Body:
to update employess I have modified your code and added update logic:

Emp_name = []
Emp_id = []
Emp_dep = []
num = 3
for i in range(num):
    x = input("enter the name of employees")
    Emp_name.append(x)

    i = input("enter the id of employees")
    Emp_id.append(i)

    d = input("enter the department of employees")
    Emp_dep.append(d)

#UPDATING employee

id = str(input(" Enter the id of employee you need to update"))
if id in Emp_id:
    pos = Emp_id.index(id)
    Emp_name[pos] = input("enter new name : ")
    Emp_id[pos] = input("enter new id : ")
    Emp_dep[pos] = input("enter new department : ")

print(Emp_name)
print(Emp_id)
print(Emp_dep)

Use a class of Employee type and create objects of it . It will help you to manage employees much efficiently.

class Employee:
    def __init__(self, name="", id="", dept=""):
        self.name = name
        self.id = id
        self.dept = dept

    def __str__(self):
        return self.name + " " + self.id + " " + self.dept

employees = list()

num = 3

for i in range(num):
    name = input("enter the name of employees : ")
    id = input("enter the id of employees : ")
    dept = input("enter the department of employees : ")

    emp = Employee(name, id, dept)
    employees.append(emp)

for e in employees:
    print(e)

delete = input(" Enter the name of employee you need to delete : ")

for index, emp in enumerate(employees):
    if emp.name == delete:
        employees.pop(index)
        break

for e in employees:
    print(e)

Output:

python/src/test/employee.py
enter the name of employees : dev
enter the id of employees : 1
enter the department of employees : dept
enter the name of employees : dev2
enter the id of employees : dept
enter the department of employees : dept
enter the name of employees : dev
enter the id of employees : 3
enter the department of employees : dept
dev 1 dept
dev2 dept dept
dev 3 dept
Enter the name of employee you need to delete : dev
dev2 dept dept
dev 3 dept


问:
Why doesn't this Nested Serializer(ForeignKey) work?
```<code>class RFIDReaderSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = RFIDReader
        bind_state_choice = ProductEntityStateChoiceSerializer()
        # depth = 2
        fields = (
            "url", "pk", "reader_name", "reader_host", "reader_address", "reader_ip", "reader_port",
            "bind_state_choice",
            "bind_state_location"
        )
</code>```

Serializer

Nested Serializer

Model Graph

RestFul

答:
Any modification on any field should be outside of meta

class RFIDReaderSerializer(serializers.HyperlinkedModelSerializer):
    bind_state_choice = ProductEntityStateChoiceSerializer()

    class Meta:
        model = RFIDReader
        # depth = 2
        fields = (
            "url", "pk", "reader_name", "reader_host", "reader_address", "reader_ip", "reader_port",
            "bind_state_choice",
            "bind_state_location"
        )
```

Body:
class RFIDReaderSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = RFIDReader
        bind_state_choice = ProductEntityStateChoiceSerializer()
        # depth = 2
        fields = (
            "url", "pk", "reader_name", "reader_host", "reader_address", "reader_ip", "reader_port",
            "bind_state_choice",
            "bind_state_location"
        )

Serializer

Nested Serializer

Model Graph

RestFul


问:
How to break this recursive loop once I reach the last letter in my python code?
I would like to break the recursive loop once I reach the last letter of new. How can I do this?

Diction is a dictionary. The idea here is that I get a word there is an example below and I shrink it by matching the [i:i+1] positions of the word string with the dictionary until it gets down to one letter.

```<code>def eval(word):
    diction = {
        'br': 'y',
        'rb': 'y',
        'by': 'r',
        'yb': 'r',
        'yr': 'b',
        'ry': 'b',
        'bb': 'b',
        'yy': 'y',
        'rr': 'r',
    }
    new = ''
    i = 0
    while i < len(word) - 1:
        key1 = word[i:i + 2]
        i += 1
        new += diction[key1]
    return eval(new)

word = 'brybbr'
print(eval(word))
</code>```

答:
You need to provide the end condition.

In this code, I added a condition if len(new)==1: to finish the unlimited resursive calls.

In addition, I also added print(new) inside the eval() instead print(eval(word)) so that it can print new with each calling of eval().

def eval(word):
    diction = {
        'br': 'y',
        'rb': 'y',
        'by': 'r',
        'yb': 'r',
        'yr': 'b',
        'ry': 'b',
        'bb': 'b',
        'yy': 'y',
        'rr': 'r',
    }
    new = ''
    i = 0
    while i < (len(word) - 1):
        key1 = word[i:i + 2]
        i += 1
        new += diction[key1]
    print(new) # to print new for every `eval()` calling.
    if len(new)==1: # to stop endless resursive calling.
        return None
    else:
        return eval(new)

word = 'brybbr'
eval(word)
# ybrby
# ryyr
# byb
# rr
# r
#
```

Body:
I would like to break the recursive loop once I reach the last letter of new. How can I do this?

Diction is a dictionary. The idea here is that I get a word there is an example below and I shrink it by matching the [i:i+1] positions of the word string with the dictionary until it gets down to one letter.

def eval(word):
    diction = {
        'br': 'y',
        'rb': 'y',
        'by': 'r',
        'yb': 'r',
        'yr': 'b',
        'ry': 'b',
        'bb': 'b',
        'yy': 'y',
        'rr': 'r',
    }
    new = ''
    i = 0
    while i < len(word) - 1:
        key1 = word[i:i + 2]
        i += 1
        new += diction[key1]
    return eval(new)

word = 'brybbr'
print(eval(word))


问:
How to refresh plots without needing to close the previous plot?
How do I get VSCode to refresh the plot when making a new plot without needing to close the previous plot tab?
Ideally, it should open up a new tab with the new plot next to the old one.

Moreover, when using Httpgd, even tho the plot refreshes without me having to close the previous plot, it opens up in a separate window outside VSCode. How do I get it to open up as a new tab like in the gif above?

答:
I had the exact same problem and what fixed it for me was simply, in vscode, going into:

Files > Preferences > Settings > section Extensions > scroll down and find R:
find the section  "Plot: Use Httpgd" and check it, and restart Vscode.

I can't confirm but I believe it might have started after installing the httpgd package, because I had the behavior you desire before installation, and the exact same behavior you experience after httpgd installation. Of course if my solution works for you (I hope), it will work under httpgd after and not the base default VsCode/R-plot viewer as in your gif.


问:
Learning about Computer Vision
I am really intrigued by the field of computer vision and the potential it has. Are there any examples (preferably implemented in .NET) which I can study along with a reference book?</p>

答:
Here's a large collection of code, toolkits, and apps you might find useful

http://www.cs.cmu.edu/~cil/v-source.html

OwnerDisplayName: Ali Kazmi

ContentLicense: CC BY-SA 2.5

Title: Learning about Computer Vision

LastEditorDisplayName: Gortok