问:
Inverted Index in Python + Posting Lists for Query - I need help getting my code to work
I have been working on a code for creating an inverted Index in Python. I am a total beginner and my Code is not working yet.
The instructions for this assignment were clear: read multiple files at once, tokenize the text and remove duplicates. Stopwords do not have to be removed (for now), and stemming is also not required. Hashmaps are not allowed.
This is my code for the first part of this assignment:

```<code>import os
from collections import Counter

path= r'C:\Users\Name\Documents'
files = dict()
for filename in os.listdir(path):
    files_to_read = path + "\\" + filename
    corpus = open(files_to_read, "r", encoding="utf-8")
    text=corpus.read()
    files[filename]=text

def lower(text):
    text=text.lower()
    return text

def tokenize(str):
    tokens = dict()
    words = str.split()
    tokens= Counter(words)
    return tokens

def individualwords(dictionary):
    individual=list()
    for word in dictionary:
        if word not in individual:
            individual.append(word)
    return individual

def inverted_index():
    idx = {}
    for file in files:
        for keyword in keywords:
            idx.setdefault(keyword, [])
            if keyword in files[file]:
                idx[keyword].append(keyword_in_file[file])
    return idx

def getid():
    idt= {}
    counter=0
    for file in files:
        idt[file]= counter+1
        counter += 1
    return idt

keywords=[]
for file in files:
    files [file]= lower(files[file])
    dictionary= tokenize(files[file])
    keywords= individualwords(dictionary)

keyword_in_file = getid()
final_dictionary= inverted_index()
#print(final_dictionary)
</code>```

printing the whole thing works just fine - it shows me all words + the documents they are included in.

The second part, however, is where the issue seems to appear. I have to be able to serach for words by means of a query, e.g. 'fog' AND 'soup'. I also have to implement an OR option. The instructions for this part specifically said to use posting lists. This is my code so far:

```<code>def AND (l1, l2):
    result = []
    i1, i2 = 0,0
    while i1 < len(l1) and i2 < len(l2):
        doc1 = l1 [i1]
        doc2 = l2 [i2]
        if doc1 == doc2:
            yield doc1
            i1 += 1
            i2 += 1
        elif doc1 < doc2:
            i1+=1
        else: i2 += 1
    return result

def OR (list1, list2):
    result = list()
    len1 = len(list1)
    len2 = len(list2)
    if len1 >=len2:
        result = list1
        for search_word in list2:
            if search_word not in result:
                result.append(search_word)
    else:
        result = list2
        for search_word in list2:
            if search_word not in result:
                result.append(search_word)
    return result

query= str (input("Enter query: "))
while (query != "NULL"):
    data = query.split()
    op1 = list()
    op2 = list()
    temp = 0
    while temp < len(data):
        op2.append(data[temp])
        temp = temp+2
    temp = 1
    while temp < len(data):
        op1.append(data[temp])
        temp = temp+2

   #this is where an error occurs: "posting_lists.append(final_dictionary[search_word])", KeyError
    posting_lists = list()
    for search_word in op2:
        posting_lists.append(final_dictionary[search_word])

    result = list()
    if len(op1) == 1:
        if op1[0] == "and":
            result = AND(posting_lists[0], posting_lists[1])

        elif op1[0] == "or":
            result = OR(posting_lists[0], posting_lists[1])

    else:
        for i in range(0, len(op1)):
            for i in range(0, len(op1)):
                if op1[i]=="and" or op1[i]=="&":
                    result= AND(posting_lists[0], posting_lists[1])
                elif op1[i]=="or" or op1[i]=="|":
                    result= OR(posting_lists[0], posting_lists[1])

</code>```

Whenever I enter a search term, I keep getting a KeyError, saying that there is something wrong at posting_lists.append(final_dictionary[search_word])
and I have no idea what to do. I literally tried everything - I changed various things to be a list or a dictionary, etc. and nothing worked. I also read up on a lot of things but nothing seemed to help in this case.
I hope someone here can help me and explain what went wrong.

答:
I think you're on the right track by printing out final_dictionary.  You're getting the KeyError because the word you're looking for isn't in final_dictionary.  So then you would want to focus your debugging on inverted_index() to determine why the search word(s) you are expecting aren't being included in the dictionary.  I would print out each keyword to verify they are going to get added to idx.

I would also focus on this block of code:

keywords=[]
for file in files:
    files [file]= lower(files[file])
    dictionary= tokenize(files[file])
    keywords= individualwords(dictionary)  ### <<<=== ????
```

I think you want to add the individual words to keywords; it seems you are reassigning keywords with every iteration of the for loop.

Body:
I have been working on a code for creating an inverted Index in Python. I am a total beginner and my Code is not working yet.
The instructions for this assignment were clear: read multiple files at once, tokenize the text and remove duplicates. Stopwords do not have to be removed (for now), and stemming is also not required. Hashmaps are not allowed.
This is my code for the first part of this assignment:

import os
from collections import Counter

path= r'C:\Users\Name\Documents'
files = dict()
for filename in os.listdir(path):
    files_to_read = path + "\\" + filename
    corpus = open(files_to_read, "r", encoding="utf-8")
    text=corpus.read()
    files[filename]=text

def lower(text):
    text=text.lower()
    return text

def tokenize(str):
    tokens = dict()
    words = str.split()
    tokens= Counter(words)
    return tokens

def individualwords(dictionary):
    individual=list()
    for word in dictionary:
        if word not in individual:
            individual.append(word)
    return individual

def inverted_index():
    idx = {}
    for file in files:
        for keyword in keywords:
            idx.setdefault(keyword, [])
            if keyword in files[file]:
                idx[keyword].append(keyword_in_file[file])
    return idx

def getid():
    idt= {}
    counter=0
    for file in files:
        idt[file]= counter+1
        counter += 1
    return idt

keywords=[]
for file in files:
    files [file]= lower(files[file])
    dictionary= tokenize(files[file])
    keywords= individualwords(dictionary)

keyword_in_file = getid()
final_dictionary= inverted_index()
#print(final_dictionary)

printing the whole thing works just fine - it shows me all words + the documents they are included in.

The second part, however, is where the issue seems to appear. I have to be able to serach for words by means of a query, e.g. 'fog' AND 'soup'. I also have to implement an OR option. The instructions for this part specifically said to use posting lists. This is my code so far:

def AND (l1, l2):
    result = []
    i1, i2 = 0,0
    while i1 < len(l1) and i2 < len(l2):
        doc1 = l1 [i1]
        doc2 = l2 [i2]
        if doc1 == doc2:
            yield doc1
            i1 += 1
            i2 += 1
        elif doc1 < doc2:
            i1+=1
        else: i2 += 1
    return result

def OR (list1, list2):
    result = list()
    len1 = len(list1)
    len2 = len(list2)
    if len1 >=len2:
        result = list1
        for search_word in list2:
            if search_word not in result:
                result.append(search_word)
    else:
        result = list2
        for search_word in list2:
            if search_word not in result:
                result.append(search_word)
    return result

query= str (input("Enter query: "))
while (query != "NULL"):
    data = query.split()
    op1 = list()
    op2 = list()
    temp = 0
    while temp < len(data):
        op2.append(data[temp])
        temp = temp+2
    temp = 1
    while temp < len(data):
        op1.append(data[temp])
        temp = temp+2

   #this is where an error occurs: "posting_lists.append(final_dictionary[search_word])", KeyError
    posting_lists = list()
    for search_word in op2:
        posting_lists.append(final_dictionary[search_word])

    result = list()
    if len(op1) == 1:
        if op1[0] == "and":
            result = AND(posting_lists[0], posting_lists[1])

        elif op1[0] == "or":
            result = OR(posting_lists[0], posting_lists[1])

    else:
        for i in range(0, len(op1)):
            for i in range(0, len(op1)):
                if op1[i]=="and" or op1[i]=="&":
                    result= AND(posting_lists[0], posting_lists[1])
                elif op1[i]=="or" or op1[i]=="|":
                    result= OR(posting_lists[0], posting_lists[1])

Whenever I enter a search term, I keep getting a KeyError, saying that there is something wrong at posting_lists.append(final_dictionary[search_word])
and I have no idea what to do. I literally tried everything - I changed various things to be a list or a dictionary, etc. and nothing worked. I also read up on a lot of things but nothing seemed to help in this case.
I hope someone here can help me and explain what went wrong.

Body:
I think you're on the right track by printing out final_dictionary.  You're getting the KeyError because the word you're looking for isn't in final_dictionary.  So then you would want to focus your debugging on inverted_index() to determine why the search word(s) you are expecting aren't being included in the dictionary.  I would print out each keyword to verify they are going to get added to idx.

I would also focus on this block of code:

keywords=[]
for file in files:
    files [file]= lower(files[file])
    dictionary= tokenize(files[file])
    keywords= individualwords(dictionary)  ### <<<=== ????

I think you want to add the individual words to keywords; it seems you are reassigning keywords with every iteration of the for loop.


来源: stackexchange

问:
Is there any difference between these forms : returnType vs returnType &?
Consider these free standalone functions:

```<code>          std::vector<int>& f();   //reference
          std::vector<int>  g();   //value

/*const*/ std::vector<int>&  f1 = f();  //reference
          std::vector<int>   f2 = f();  //value

/*const*/ std::vector<int>&  g1 = g();  //reference
          std::vector<int>   g2 = g();  //value
</code>```

Is there any difference between :

f() and g(). Its easy question, but still I would like to hear some detail commentary on them, as it might help understanding the answer of the next questions.

f1 and f2. Will they be same original object from f(), or f2 will be a copy of the original? Uncommenting const will make any difference?

g1 and g2. Will they be same original object from g(), or g2 will be a copy of the original? Uncommenting const will make any difference?

What if f() and g() are member functions, and each returns member data, not some local variable? Will it make any difference in the answer of the above questions?

Please try including all the pitfalls and important points in your answer, and don't consider RVO or any other optimization by compiler. I want to know what C++ is, not what compilers do. If you talk about optimizations, please explicitly mention it, so that I dont mix language features with compiler features.

答:
f() returns a reference to an object; returning from it does not copy any object.  g() returns a copy of an object, at least conceptually.

```<code>std::vector<int>&  f1 = f();  //reference
</code>```

f1 refers to the object to which f() returned a reference.  No copies are made.  Const-qualification of the reference does not make a difference here (as far as copying is concerned; obviously it affects what can be done with the object).

```<code>std::vector<int>   f2 = f();  //value
</code>```

f2 is a copy of the object to which f() returned a reference.

```<code>std::vector<int>&  g1 = g();  //reference
</code>```

This is invalid.  A non-const reference cannot be bound to a temporary object.

If the reference is const-qualified, then this line is effectively the same as the next line:  a copy of the object returned by g() is made, the reference is bound to that copy, and that copy is given the lifetime of the reference (it is destroyed when the reference is "destroyed").

```<code>std::vector<int>   g2 = g();  //value
</code>```

g2 is a copy of the object returned by g().  Whether a copy is made (and how many copies may be made) depends on compiler optimizations.

What if f() and g() are member functions, and each returns member data, not some local variable?

If f() returns a reference to a local variable then the program is incorrect and yields undefined behavior if you attempt to use the reference because the referred-to object ceases to exist when the function returns.

If f() returns a reference to a member variable, a dynamically allocated object, or an object with static or thread local storage duration, then the reference is valid for the lifetime of that object (or to another object of the same type constructed at the same location in memory as the object to which the reference was returned, though the utility of this is limited to a select few scenarios).

It doesn't matter what g() returns because a copy is always made (at least conceptually).

ContentLicense: CC BY-SA 3.0

Body:
Consider these free standalone functions:

          std::vector<int>& f();   //reference
          std::vector<int>  g();   //value

/*const*/ std::vector<int>&  f1 = f();  //reference
          std::vector<int>   f2 = f();  //value

/*const*/ std::vector<int>&  g1 = g();  //reference
          std::vector<int>   g2 = g();  //value

Is there any difference between :

f() and g(). Its easy question, but still I would like to hear some detail commentary on them, as it might help understanding the answer of the next questions.

f1 and f2. Will they be same original object from f(), or f2 will be a copy of the original? Uncommenting const will make any difference?

g1 and g2. Will they be same original object from g(), or g2 will be a copy of the original? Uncommenting const will make any difference?

What if f() and g() are member functions, and each returns member data, not some local variable? Will it make any difference in the answer of the above questions?

Please try including all the pitfalls and important points in your answer, and don't consider RVO or any other optimization by compiler. I want to know what C++ is, not what compilers do. If you talk about optimizations, please explicitly mention it, so that I dont mix language features with compiler features.

Body:
f() returns a reference to an object; returning from it does not copy any object.  g() returns a copy of an object, at least conceptually.

std::vector<int>&  f1 = f();  //reference

f1 refers to the object to which f() returned a reference.  No copies are made.  Const-qualification of the reference does not make a difference here (as far as copying is concerned; obviously it affects what can be done with the object).

std::vector<int>   f2 = f();  //value

f2 is a copy of the object to which f() returned a reference.

std::vector<int>&  g1 = g();  //reference

This is invalid.  A non-const reference cannot be bound to a temporary object.

If the reference is const-qualified, then this line is effectively the same as the next line:  a copy of the object returned by g() is made, the reference is bound to that copy, and that copy is given the lifetime of the reference (it is destroyed when the reference is "destroyed").

std::vector<int>   g2 = g();  //value

g2 is a copy of the object returned by g().  Whether a copy is made (and how many copies may be made) depends on compiler optimizations.

What if f() and g() are member functions, and each returns member data, not some local variable?

If f() returns a reference to a local variable then the program is incorrect and yields undefined behavior if you attempt to use the reference because the referred-to object ceases to exist when the function returns.

If f() returns a reference to a member variable, a dynamically allocated object, or an object with static or thread local storage duration, then the reference is valid for the lifetime of that object (or to another object of the same type constructed at the same location in memory as the object to which the reference was returned, though the utility of this is limited to a select few scenarios).

It doesn't matter what g() returns because a copy is always made (at least conceptually).


问:
Is it possible to get json values as list from array of json in Postgres?
I use Postgresql 10 and suppose, that I have the following table:

```<code>CREATE TABLE test_table(id int8 NOT NULL, data jsonb);
</code>```

And inserted such values:

```<code>insert into test_table(id, data)
values (1, '{"external": [{"internal_1": "value_1", "internal_2": "some_value"}]}'),
       (2, '{"external": [{"internal_1": "value_2", "internal_2": "another_value"}]}'),
       (3, '{"external": [{"internal_1": "value_1", "internal_2": "other_value"}]}');
</code>```

The table after all:

```<code>id|                                data                                     |
--|-------------------------------------------------------------------------|
1 |{"external": [{"internal_1": "value_1", "internal_2": "some_value"}]}    |
2 |{"external": [{"internal_1": "value_2", "internal_2": "another_value"}]} |
3 |{"external": [{"internal_1": "value_1", "internal_2": "other_value"}]}   |
</code>```

The problem is that I need to have all internal values as an array

I tried the following query:

```<code>select data -> 'external'
from test_table;
</code>```

and the result is:

```<code>?column?                                                         |
-----------------------------------------------------------------|
[{"internal_1": "value_1", "internal_2": "some_value"}]          |
[{"internal_1": "value_2", "internal_2": "another_value"}]       |
[{"internal_1": "value_1", "internal_2": "other_value"}]         |
</code>```

But finally I need to have internal values as text array for each table row. Something like that:

```<code>?column?                       |
-------------------------------|
[value_1, some_value]          |
[value_2, another_value]       |
[value_1, other_value]         |
</code>```

Is it possible to write such query using postgres json functions and operators?

UPD!!
Number of internal keys could be different (internal_1, ..., internal_n) and we don’t know in advance names of keys (in my case they are: internal_1 and internal_2)

答:
One approach would be splitting the elements through going deep into each key individually in an explicit manner, and then using jsonb_build_array() function  :

```<code>SELECT jsonb_build_array(
       (data ->> 'external')::jsonb -> 0 ->> 'internal_1',
       (data ->> 'external')::jsonb -> 0 ->> 'internal_2')
  FROM test_table
</code>```

Or more dynamically (for the cases of having more or less internal keys) jsonb_each_text() might be used within a CROSS JOIN query to extract each key and then jsonb_agg() might be applied to combine them within arrays :

```<code>SELECT id,
       jsonb_agg(js.value)
  FROM test_table
 CROSS JOIN jsonb_each_text( ((data ->> 'external')::jsonb -> 0)::jsonb) AS js
 GROUP BY id
 ORDER BY id
</code>```

Demo

ContentLicense: CC BY-SA 4.0

Body:
I use Postgresql 10 and suppose, that I have the following table:

CREATE TABLE test_table(id int8 NOT NULL, data jsonb);

And inserted such values:

insert into test_table(id, data)
values (1, '{"external": [{"internal_1": "value_1", "internal_2": "some_value"}]}'),
       (2, '{"external": [{"internal_1": "value_2", "internal_2": "another_value"}]}'),
       (3, '{"external": [{"internal_1": "value_1", "internal_2": "other_value"}]}');

The table after all:

id|                                data                                     |
--|-------------------------------------------------------------------------|
1 |{"external": [{"internal_1": "value_1", "internal_2": "some_value"}]}    |
2 |{"external": [{"internal_1": "value_2", "internal_2": "another_value"}]} |
3 |{"external": [{"internal_1": "value_1", "internal_2": "other_value"}]}   |

The problem is that I need to have all internal values as an array

I tried the following query:

select data -> 'external'
from test_table;

and the result is:

?column?                                                         |
-----------------------------------------------------------------|
[{"internal_1": "value_1", "internal_2": "some_value"}]          |
[{"internal_1": "value_2", "internal_2": "another_value"}]       |
[{"internal_1": "value_1", "internal_2": "other_value"}]         |

But finally I need to have internal values as text array for each table row. Something like that:

?column?                       |
-------------------------------|
[value_1, some_value]          |
[value_2, another_value]       |
[value_1, other_value]         |

Is it possible to write such query using postgres json functions and operators?

UPD!!
Number of internal keys could be different (internal_1, ..., internal_n) and we don’t know in advance names of keys (in my case they are: internal_1 and internal_2)

Body:
One approach would be splitting the elements through going deep into each key individually in an explicit manner, and then using jsonb_build_array() function  :

SELECT jsonb_build_array(
       (data ->> 'external')::jsonb -> 0 ->> 'internal_1',
       (data ->> 'external')::jsonb -> 0 ->> 'internal_2')
  FROM test_table

Or more dynamically (for the cases of having more or less internal keys) jsonb_each_text() might be used within a CROSS JOIN query to extract each key and then jsonb_agg() might be applied to combine them within arrays :

SELECT id,
       jsonb_agg(js.value)
  FROM test_table
 CROSS JOIN jsonb_each_text( ((data ->> 'external')::jsonb -> 0)::jsonb) AS js
 GROUP BY id
 ORDER BY id

Demo


问:
How to write a calculated field using Microsoft Access expression builder?
I'm trying to write a query that will calculate "Shares short" divided by "Shares floating". See my table below. I've tried the following expression, but I just get a big fat error.

```<code>Expr1: [Shares]![SharesType]="Shares short"/[Shares]![SharesType]="Shares floating"
</code>```

I've also tried looking at Microsoft's expression tutorials (and the linked tutorials) but they're too general.

答:
This worked.

```<code>SELECT Companies.CompanyName, Sum(IIf([SharesType]="Shares short",[Shares],Null))/Sum(IIf([SharesType]="Shares floating",[Shares],Null)) AS [Short as % of Float]
FROM Companies INNER JOIN Shares ON Companies.CompanyID = Shares.[Company ID]
GROUP BY Companies.CompanyName;
</code>```

So my report now looks like this.

Body:
I'm trying to write a query that will calculate "Shares short" divided by "Shares floating". See my table below. I've tried the following expression, but I just get a big fat error.

Expr1: [Shares]![SharesType]="Shares short"/[Shares]![SharesType]="Shares floating"

I've also tried looking at Microsoft's expression tutorials (and the linked tutorials) but they're too general.

Body:
This worked.

SELECT Companies.CompanyName, Sum(IIf([SharesType]="Shares short",[Shares],Null))/Sum(IIf([SharesType]="Shares floating",[Shares],Null)) AS [Short as % of Float]
FROM Companies INNER JOIN Shares ON Companies.CompanyID = Shares.[Company ID]
GROUP BY Companies.CompanyName;

So my report now looks like this.


问:
Return 2D array using static keyword in C
I was trying to return 2D integer array from a function in C. I was able to return it using dynamic memory allocation using malloc() but I am unable but curious to understand how can we use static keyword to do it.

Below is the code snippet which successfully returns 2D array using static keyword,

```<code>int (*(get_2d_arr_using_static)())[10]    // Can someone explain me this statement in detail ?
{
    static int arr[10][10] = { { 1,2,3}, {4,5,6}, {7,8,9}};
    return arr;
}

int main()
{
  int (*arr)[10] =  get_2d_arr_using_static();  // Need some insights on this statement too
  printf("Result ( x: 3, y =3 ): \n");
  for (int i = 0; i < 3; i++)
  {
    for (int j = 0; j < 3; j++)
    {
      printf(" %d", arr[i][j]);
    }
    printf("\n");
  }
}
</code>```

I need some explanation on the commented statements.

答:
I was trying to return 2D integer array from a function in C.

There's the problem. A function cannot return an array in C.

You can return pointers though, and pointers may point to an element of an array.

That array may be allocated dynamically or statically. Returning a pointer to an automatic array declared within the function would be pointless because the lifetime of that array ends when it goes out of scope, so you would be returning a dangling pointer.

```<code>int (*(get_2d_arr_using_static)())[10]    // Can someone explain me this statement in detail ?
</code>```

This declares a function that returns a pointer to an array of 10 integers.

It should be noted that int[10][10] is an array of 10 arrays of 10 integers. As such, element of that array is an array of 10 integers, and the function returns a pointer to such element.

```<code>int (*arr)[10] =  get_2d_arr_using_static();  // Need some insights on this statement too
</code>```

This calls that function and initialises a pointer to an array of 10 integers.

It is possible to return an array by copy as well, but indirectly. It can be achieved by wrapping the array in a struct:

```<code>struct wrapper {
    int arr[10][10];
};

struct wrapper foo(void) {
     struct wrapper w;
     // fill the array or something
     return w;
}
</code>```

Since you tagged C++, I'll mention that C++ standard library has a template for such wrapper class: std::array.

Body:
I was trying to return 2D integer array from a function in C. I was able to return it using dynamic memory allocation using malloc() but I am unable but curious to understand how can we use static keyword to do it.

Below is the code snippet which successfully returns 2D array using static keyword,

int (*(get_2d_arr_using_static)())[10]    // Can someone explain me this statement in detail ?
{
    static int arr[10][10] = { { 1,2,3}, {4,5,6}, {7,8,9}};
    return arr;
}

int main()
{
  int (*arr)[10] =  get_2d_arr_using_static();  // Need some insights on this statement too
  printf("Result ( x: 3, y =3 ): \n");
  for (int i = 0; i < 3; i++)
  {
    for (int j = 0; j < 3; j++)
    {
      printf(" %d", arr[i][j]);
    }
    printf("\n");
  }
}

I need some explanation on the commented statements.

Body:
I was trying to return 2D integer array from a function in C.

There's the problem. A function cannot return an array in C.

You can return pointers though, and pointers may point to an element of an array.

That array may be allocated dynamically or statically. Returning a pointer to an automatic array declared within the function would be pointless because the lifetime of that array ends when it goes out of scope, so you would be returning a dangling pointer.

int (*(get_2d_arr_using_static)())[10]    // Can someone explain me this statement in detail ?

This declares a function that returns a pointer to an array of 10 integers.

It should be noted that int[10][10] is an array of 10 arrays of 10 integers. As such, element of that array is an array of 10 integers, and the function returns a pointer to such element.

int (*arr)[10] =  get_2d_arr_using_static();  // Need some insights on this statement too

This calls that function and initialises a pointer to an array of 10 integers.

It is possible to return an array by copy as well, but indirectly. It can be achieved by wrapping the array in a struct:

struct wrapper {
    int arr[10][10];
};

struct wrapper foo(void) {
     struct wrapper w;
     // fill the array or something
     return w;
}

Since you tagged C++, I'll mention that C++ standard library has a template for such wrapper class: std::array.


问:
How to flatten a nested dict and use inner values on collision
Question

For the following dictionary:

```<code>{'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}
</code>```

I want to create a new dictionary without the remove_me or world keys.

Edit update:

To summarise, I wanted to do the following:

If the values of an item are a nested dictionary. Update the new dictionary with the inner result while removing the current key value from the main dict.

If the values of an item are not a nested dictionary, update the new dictionary with the key, value.

The accepted answer covers this.

What have I tried?

```<code>{k:v for (k,v) in d.items() if not k == 'remove_me'}
</code>```

yields:

```<code>{'id': 1, 'label': 'hello'}
</code>```

not exactly what I need as I'm dropping the nested dict.

Desired output:

```<code>{'id': 1, 'label': 'hello','keep_me': 52}
</code>```

答:
dico = {'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}

# Just what you have done
new_dico = {k:v for (k,v) in dico.items() if not k == 'remove_me'}

# Plus this line
new_dico.update(dico['remove_me']['world'])

print(new_dico)
# {'id': 1, 'label': 'hello', 'keep_me': 52}
```

<p>Inspired by what I have read here, a flatten function for the main dict, whatever deep one of your key-dict is:</p>

<pre class="lang-py prettyprint-override"><code>dico = {'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}

def dFlatten(dico, d = {}):
    for k, v in dico.items():
        if isinstance(v, dict):
            dFlatten(v)
        else:
            d[k] = v
    return d
dico = dFlatten(dico)
print(dico)
# {'id': 1, 'label': 'hello', 'keep_me': 52}
</code>```

For instance with a deeper dico :

dico2 = {'id': 1, 'label': 'hello', 'stuff1': {'stuff2': {'remove_me': {'world': {'keep_me': 52}}}}}
dico2 = dFlatten(dico2)
print(dico2)
# {'id': 1, 'label': 'hello', 'keep_me': 52}
```

<p>With several deep keys with the same dFlatten function</p>

<pre class="lang-py prettyprint-override"><code>dico3 = {'id': 1, 'label': 'hello', 'deep': {'L1': {'L2': 52}}, 'remove_me': {'world': {'keep_me': 52}}}
dico3 = dFlatten(dico3)
print(dico3)
# {'id': 1, 'label': 'hello', 'keep_me': 52, 'L2': 52}
</code>```

Body:
Question

For the following dictionary:

{'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}

I want to create a new dictionary without the remove_me or world keys.

Edit update:

To summarise, I wanted to do the following:

If the values of an item are a nested dictionary. Update the new dictionary with the inner result while removing the current key value from the main dict.

If the values of an item are not a nested dictionary, update the new dictionary with the key, value.

The accepted answer covers this.

What have I tried?

{k:v for (k,v) in d.items() if not k == 'remove_me'}

yields:

{'id': 1, 'label': 'hello'}

not exactly what I need as I'm dropping the nested dict.

Desired output:

{'id': 1, 'label': 'hello','keep_me': 52}

Body:
dico = {'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}

# Just what you have done
new_dico = {k:v for (k,v) in dico.items() if not k == 'remove_me'}

# Plus this line
new_dico.update(dico['remove_me']['world'])

print(new_dico)
# {'id': 1, 'label': 'hello', 'keep_me': 52}

Inspired by what I have read here, a flatten function for the main dict, whatever deep one of your key-dict is:

dico = {'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}

def dFlatten(dico, d = {}):
    for k, v in dico.items():
        if isinstance(v, dict):
            dFlatten(v)
        else:
            d[k] = v
    return d
dico = dFlatten(dico)
print(dico)
# {'id': 1, 'label': 'hello', 'keep_me': 52}

For instance with a deeper dico :

dico2 = {'id': 1, 'label': 'hello', 'stuff1': {'stuff2': {'remove_me': {'world': {'keep_me': 52}}}}}
dico2 = dFlatten(dico2)
print(dico2)
# {'id': 1, 'label': 'hello', 'keep_me': 52}

With several deep keys with the same dFlatten function

dico3 = {'id': 1, 'label': 'hello', 'deep': {'L1': {'L2': 52}}, 'remove_me': {'world': {'keep_me': 52}}}
dico3 = dFlatten(dico3)
print(dico3)
# {'id': 1, 'label': 'hello', 'keep_me': 52, 'L2': 52}


问:
Postgres SQL to fill in time series gaps for multiple groups
I have a single table like this which spans 2 days of data capture:

```<code>   class   timestamp              count

   2       2020-05-20 03:10:00    4
   1       2020-05-21 07:45:00    2
   6       2020-05-20 09:20:00    1
   2       2020-05-21 11:30:00    1
   5       2020-05-21 21:50:00    3
   1       2020-05-21 07:45:00    5
   5       2020-05-20 14:55:00    2
</code>```

I would like to create output similar to that schema but with every 5 minute interval over the two days represented with count zeroed out if there is no matching timestamp.  All duplicate timestamps for a class need to be totaled for that timestamp entry.  All the unique classes need to be grouped and the order should be timestamp ascending.

Every unique class need to be treated that way - group by class, fill in the missing 5 minute times in order, sum any counts with the exact same timestamp in that group, order by timestamp.  The overall output should be ordered by class ascending.

Thanks for any assistance.

答:
Assume Yours table definition:

```<code>create table events(
    class       int,
    ts          timestamp,
    cnt         int
);
</code>```

Example query, make everything step by step:

```<code>with time_range as (
    select timestamp '2020-05-20 00:00:00' as start_time,   -- current_timestamp - interval '2 day'
           timestamp '2020-05-22 00:00:00' as end_time      -- current_timestamp
),
interested_events as (
    select e.class, e.ts, e.cnt
    from events e
    inner join time_range tr
        on (e.ts >= tr.start_time and e.ts < tr.end_time)
),
classes_having_events as (
    select distinct class
    from interested_events
),
periods as (
    select ts as period_start, ts + interval '5 minute' as period_end
    from generate_series(
        (select start_time from time_range),
        (select end_time from time_range) - interval '1 second',
        interval '5 minute') ts
)
select
    c.class,
    p.period_start ts,
    (select coalesce(sum(cnt), 0)
    from interested_events e
    where e.class = c.class
      and e.ts >= p.period_start
      and e.ts < p.period_end) as cnt
from classes_having_events as c
cross join periods as p
order by 2, 1;
</code>```

In time_range define time interval for witch events should be analyzed.

In interested_events events are selected based on previous defined time interval (time_range - start_time inclusive, end_time exclusive).

In classes_having_events set of classes are created. Every classes with at least one event in choosen time interval are included.

In periods there are 5 minute periods created.

Finally we cross join set of classes with periods and for every combination class and period calculate count of events.

Body:
I have a single table like this which spans 2 days of data capture:

   class   timestamp              count

   2       2020-05-20 03:10:00    4
   1       2020-05-21 07:45:00    2
   6       2020-05-20 09:20:00    1
   2       2020-05-21 11:30:00    1
   5       2020-05-21 21:50:00    3
   1       2020-05-21 07:45:00    5
   5       2020-05-20 14:55:00    2

I would like to create output similar to that schema but with every 5 minute interval over the two days represented with count zeroed out if there is no matching timestamp.  All duplicate timestamps for a class need to be totaled for that timestamp entry.  All the unique classes need to be grouped and the order should be timestamp ascending.

Every unique class need to be treated that way - group by class, fill in the missing 5 minute times in order, sum any counts with the exact same timestamp in that group, order by timestamp.  The overall output should be ordered by class ascending.

Thanks for any assistance.

Body:
Assume Yours table definition:

create table events(
    class       int,
    ts          timestamp,
    cnt         int
);

Example query, make everything step by step:

with time_range as (
    select timestamp '2020-05-20 00:00:00' as start_time,   -- current_timestamp - interval '2 day'
           timestamp '2020-05-22 00:00:00' as end_time      -- current_timestamp
),
interested_events as (
    select e.class, e.ts, e.cnt
    from events e
    inner join time_range tr
        on (e.ts >= tr.start_time and e.ts < tr.end_time)
),
classes_having_events as (
    select distinct class
    from interested_events
),
periods as (
    select ts as period_start, ts + interval '5 minute' as period_end
    from generate_series(
        (select start_time from time_range),
        (select end_time from time_range) - interval '1 second',
        interval '5 minute') ts
)
select
    c.class,
    p.period_start ts,
    (select coalesce(sum(cnt), 0)
    from interested_events e
    where e.class = c.class
      and e.ts >= p.period_start
      and e.ts < p.period_end) as cnt
from classes_having_events as c
cross join periods as p
order by 2, 1;

In time_range define time interval for witch events should be analyzed.

In interested_events events are selected based on previous defined time interval (time_range - start_time inclusive, end_time exclusive).

In classes_having_events set of classes are created. Every classes with at least one event in choosen time interval are included.

In periods there are 5 minute periods created.

Finally we cross join set of classes with periods and for every combination class and period calculate count of events.


问:
Centering the selected value of a DropdownButton
I am able to center the text items used in DropdownMenuItems provided to the DropDownButton, but how can the selected item be centered when the menu is closed?

答:
This worked for me: </p>

```<code>List<String> targetOptions = ['No target', '1', '2', '3', '4'];

 return DropdownButton<String>(
                        value: target,
                        selectedItemBuilder: (BuildContext context) {
                          return targetOptions.map<Widget>((String item) {
                            return SizedBox(width: 70, child: Center(child: Text(item, style: TextStyle(color: Colors.white))));
                          }).toList();
                        },
                        items: targetOptions.map((String value) {
                          return new DropdownMenuItem<String>(
                            value: value == 'No target' ? '0' : value,
                            child: Center(
                              child: new Text(
                                value,
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                          );
                        }).toList(),
                        onChanged: (val) {
                          SettingManager.put(SettingManager.SETTING_DAILY_TARGET, val);
                          setState(() {
                            target = val;
                          });
                        },
                      )
</code>```

Body:
This worked for me:

List<String> targetOptions = ['No target', '1', '2', '3', '4'];

 return DropdownButton<String>(
                        value: target,
                        selectedItemBuilder: (BuildContext context) {
                          return targetOptions.map<Widget>((String item) {
                            return SizedBox(width: 70, child: Center(child: Text(item, style: TextStyle(color: Colors.white))));
                          }).toList();
                        },
                        items: targetOptions.map((String value) {
                          return new DropdownMenuItem<String>(
                            value: value == 'No target' ? '0' : value,
                            child: Center(
                              child: new Text(
                                value,
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                          );
                        }).toList(),
                        onChanged: (val) {
                          SettingManager.put(SettingManager.SETTING_DAILY_TARGET, val);
                          setState(() {
                            target = val;
                          });
                        },
                      )


问:
1x1 pixel images while sharing link on linkedin
I am currently having quite problem at hand with linkedin sharing module.

While trying to share an article via link: http://www.rp.pl/Opinie/307189896-Friend-or-Foe.html

which contains opengraph image: http://www.rp.pl/storyimage/RP/20180718/EKO/307189896/AR/0/AR-307189896.jpg?minW=200&minH=200&exactW=600&exactH=351&exactFit=crop

via:

https://www.linkedin.com/shareArticle?mini=true&url=http://www.rp.pl/Opinie/307189896-Friend-or-Foe.html

The crawler result which I am getting containt 1x1 pixel images instead on thumbnail of provided og:image image (which works if provided to browser).

See image:

My first conclustion was that for some reason service providing images for url from og:image tag fed LinkedIn crawler with 1x1 pixel image. However after playing around with chromes dev tools and linkedin share page I have discovered that most likely LinkedIn crawler is getting expected image (the same that browser is getting when visiting link from og:image tag) because deep in LinkedIn share page there is proper image size which is not provided via page containing og:image tag - see image below:

Image size value is equal to contents-length header for that image.

So knowing that I started to play around with LinkedIn crawler to see how it reacts to absent images and corrupted ones.

For absent ones it behaves as expected - does not show this image in share page.
However for corrupted ones it provides 1x1 pixel.

For all above I am preatty sure that LinkedIn clrawler treats images provided by ours service as corrupted but I could not find any requirements list for images provided to LinkedIn crawler.

I was wondering if anyone else had similiar issue and maybe there is solution to that problem.

PS. Those same images work like a charm on facebook while sharing.

PPS. Some times non-working images in LinkedIn share are getting to work eventually - which might seem that these images are generally OK.

答:
It seems like your share URL and image are actually working just fine now:

There can be many, many reasons why an og:image tag might be ignored!  Fortunately, the LinkedIn team discovered this, and put together this useful tool for debugging how you're sharing: LinkedIn Post Inspector - For LinkedIn Sharing URLs.


问:
Group data, rename the object property and create new dataset in NodeJs
I'm new on Stackoverflow and also new in JS.
I'm lost on how to manipulate data and need help.
I have a dataset which has some duplicated quoteDate. I need to create a new dataset by adding the prices under the its date with the option as a property Name.

Please see below original data:

```<code>const dataSet = [
      {"quoteDate":20190925,"price":39926,"option":0},
      {"quoteDate":20191118,"price":43239,"option":0},
      {"quoteDate":20190925,"price":77946,"option":1},
      {"quoteDate":20191125,"price":43178,"option":0},
      {"quoteDate":20191202,"price":46992,"option":0},
      {"quoteDate":20191210,"price":84596,"option":1},
      {"quoteDate":20191202,"price":32256,"option":1},
      {"quoteDate":20191223,"price":32285,"option":0},
      {"quoteDate":20200429,"price":68173,"option":1},
]
</code>```

Here is the desire end result:

```<code>const newDataSet = [
      {"Date": "20190925","A": 39926,"B": 77946,},
      {"Date": "20191118","A": 43239,},
      {"Date": "20191125","A": 43178,},
      {"Date": "20191202","A": 46992,"B": 32256,},
      {"Date": "20191210","B": 84596,},
      {"Date": "20191223","A": 32285,},
      {"Date": "20200429","B": 68173,},
    ]
</code>```

I"ve been trying below code but no success :(

```<code>let newDataSet = Object.values(dataSet.reduce((a, {price, quoteDate, option})=>{
  if(!a[quoteDate] && a[option] === 0)
    a[quoteDate] = Object.assign({},{'A': price, Date: quoteDate });
  else if(!a[quoteDate] && a[option] === 1)
    a[quoteDate] = Object.assign({},{'B': price, Date: quoteDate });
  return a;
 },{}));
 console.log(newDataSet);
</code>```

That would be great if anyone can help me on this!

Thanks!

答:
Use object spread to add a new [quoteDate] to the accumulator, and include the previous value of [quoteDate]. Use computed property names, to set A or B as the name of the property according to option:

const dataSet = [{"quoteDate":20190925,"price":39926,"option":0},{"quoteDate":20191118,"price":43239,"option":0},{"quoteDate":20190925,"price":77946,"option":1},{"quoteDate":20191125,"price":43178,"option":0},{"quoteDate":20191202,"price":46992,"option":0},{"quoteDate":20191210,"price":84596,"option":1},{"quoteDate":20191202,"price":32256,"option":1},{"quoteDate":20191223,"price":32285,"option":0},{"quoteDate":20200429,"price":68173,"option":1}];

const newDataSet = Object.values(dataSet.reduce((a, {price, quoteDate, option}) => ({
  ...a, // spread the current accumulator
  [quoteDate]: { // add a property according to quoteDate
    ...a[quoteDate], // spread the current quoteDate - undefined or null values will be ignored
    Date: quoteDate, // create the date property
    [option ? 'B' : 'A']: price // create A or B property
  }
}),{}));

console.log(newDataSet);```
</div>
</div>
</p>

<p>Another option is to mutate the accumulator. It's especially important if you've got lots of items, and performance is important.</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>const dataSet = [{"quoteDate":20190925,"price":39926,"option":0},{"quoteDate":20191118,"price":43239,"option":0},{"quoteDate":20190925,"price":77946,"option":1},{"quoteDate":20191125,"price":43178,"option":0},{"quoteDate":20191202,"price":46992,"option":0},{"quoteDate":20191210,"price":84596,"option":1},{"quoteDate":20191202,"price":32256,"option":1},{"quoteDate":20191223,"price":32285,"option":0},{"quoteDate":20200429,"price":68173,"option":1}];

const newDataSet = Object.values(dataSet.reduce((a, {price, quoteDate, option})=>{
  a[quoteDate] = a[quoteDate] || { Date: quoteDate };

  a[quoteDate][option ? 'B' : 'A'] = price;

  return a;
},{}));

console.log(newDataSet);</code>```

Body:
I'm new on Stackoverflow and also new in JS.
I'm lost on how to manipulate data and need help.
I have a dataset which has some duplicated quoteDate. I need to create a new dataset by adding the prices under the its date with the option as a property Name.

Please see below original data:

const dataSet = [
      {"quoteDate":20190925,"price":39926,"option":0},
      {"quoteDate":20191118,"price":43239,"option":0},
      {"quoteDate":20190925,"price":77946,"option":1},
      {"quoteDate":20191125,"price":43178,"option":0},
      {"quoteDate":20191202,"price":46992,"option":0},
      {"quoteDate":20191210,"price":84596,"option":1},
      {"quoteDate":20191202,"price":32256,"option":1},
      {"quoteDate":20191223,"price":32285,"option":0},
      {"quoteDate":20200429,"price":68173,"option":1},
]

Here is the desire end result:

const newDataSet = [
      {"Date": "20190925","A": 39926,"B": 77946,},
      {"Date": "20191118","A": 43239,},
      {"Date": "20191125","A": 43178,},
      {"Date": "20191202","A": 46992,"B": 32256,},
      {"Date": "20191210","B": 84596,},
      {"Date": "20191223","A": 32285,},
      {"Date": "20200429","B": 68173,},
    ]

I"ve been trying below code but no success :(

let newDataSet = Object.values(dataSet.reduce((a, {price, quoteDate, option})=>{
  if(!a[quoteDate] && a[option] === 0)
    a[quoteDate] = Object.assign({},{'A': price, Date: quoteDate });
  else if(!a[quoteDate] && a[option] === 1)
    a[quoteDate] = Object.assign({},{'B': price, Date: quoteDate });
  return a;
 },{}));
 console.log(newDataSet);

That would be great if anyone can help me on this!

Thanks!

Body:
Use object spread to add a new [quoteDate] to the accumulator, and include the previous value of [quoteDate]. Use computed property names, to set A or B as the name of the property according to option:

const dataSet = [{"quoteDate":20190925,"price":39926,"option":0},{"quoteDate":20191118,"price":43239,"option":0},{"quoteDate":20190925,"price":77946,"option":1},{"quoteDate":20191125,"price":43178,"option":0},{"quoteDate":20191202,"price":46992,"option":0},{"quoteDate":20191210,"price":84596,"option":1},{"quoteDate":20191202,"price":32256,"option":1},{"quoteDate":20191223,"price":32285,"option":0},{"quoteDate":20200429,"price":68173,"option":1}];

const newDataSet = Object.values(dataSet.reduce((a, {price, quoteDate, option}) => ({
  ...a, // spread the current accumulator
  [quoteDate]: { // add a property according to quoteDate
    ...a[quoteDate], // spread the current quoteDate - undefined or null values will be ignored
    Date: quoteDate, // create the date property
    [option ? 'B' : 'A']: price // create A or B property
  }
}),{}));

console.log(newDataSet);

Another option is to mutate the accumulator. It's especially important if you've got lots of items, and performance is important.

const dataSet = [{"quoteDate":20190925,"price":39926,"option":0},{"quoteDate":20191118,"price":43239,"option":0},{"quoteDate":20190925,"price":77946,"option":1},{"quoteDate":20191125,"price":43178,"option":0},{"quoteDate":20191202,"price":46992,"option":0},{"quoteDate":20191210,"price":84596,"option":1},{"quoteDate":20191202,"price":32256,"option":1},{"quoteDate":20191223,"price":32285,"option":0},{"quoteDate":20200429,"price":68173,"option":1}];

const newDataSet = Object.values(dataSet.reduce((a, {price, quoteDate, option})=>{
  a[quoteDate] = a[quoteDate] || { Date: quoteDate };

  a[quoteDate][option ? 'B' : 'A'] = price;

  return a;
},{}));

console.log(newDataSet);


问:
Code in Merge Sort in C not working properly
```<code>int lb = 0, ub = 8, mid;   //ub=upper bound,lb=lower bound.
int i = 0, j = 0, k = 0;
int a[] = { 15, 5, 24, 8, 1, 3, 16, 10, 20 };
int b[10];

void mergeSort(int a[], int lb, int ub) {
    if (lb < ub) {
        mid = ((lb + ub) / 2);
        mergeSort(a, lb, mid);
        mergeSort(a, mid + 1, ub);
        merge(a, lb, mid, ub);
    }
}

void merge(int a[], int lb, int mid, int ub) {
    i = lb;
    j = mid + 1;
    k = lb;

    while (i <= mid && j <= ub) {
        if (a[i] <= a[j]) {
            b[k] = a[i];
            i++;
        } else {
            b[k] = a[j];
            j++;
        }
        k++;
    }

    if (i > mid) {
        while (j <= ub) {
            b[k] = a[j];
            j++;
            k++;
        }
    } else {
        while (i <= mid) {
            b[k] = a[i];
            i++;
            k++;
        }
    }

    for (k = lb; k <= ub; k++) {
        a[k] = b[k];
    }
}

void printList(int A[]) {
    for (k = 0; k <= 8; k++) {
        printf("%d\n", A[k]);
    }
    printf("done\n");
}

int main() {
    printList(a);
    mergeSort(a, 0, 8);
    printList(a);
}
</code>```

I think the code of mergesort and merge is not the problem, the problem is how I have checked the code many times but I cannot find the mistakes, so I hope someone could explain to me where is the problems, thanks for everyone who try to help!!

the output when I run the code:

```
5
15
8
1
3
16
10
20
24
done
```

which is not a sorted list.

答:
The problem is mid is a global variable, so it gets modified by the recursive call mergeSort(a, lb, mid); and a different value is used for the second recursive call mergeSort(a, mid + 1, ub); and yet a different value is used for the final call merge(a, lb, mid, ub); producing unexpected results, and potentially causing undefined behavior.

Do not use global variables. Define both arrays in main, make i, j, k and mid local variables in merge and mergeSort and pass the auxiliary array b to merge and mergeSort.

Here is a modified version:

```<code>#include <stdio.h>

void merge(int a[], int lb, int mid, int ub, int b[]) {
    int i = lb;
    int j = mid + 1;
    int k = lb;

    while (i <= mid && j <= ub) {
        if (a[i] <= a[j]) {
            b[k] = a[i];
            i++;
        } else {
            b[k] = a[j];
            j++;
        }
        k++;
    }
    if (i > mid) {
        while (j <= ub) {
            b[k] = a[j];
            j++;
            k++;
        }
    } else {
        while (i <= mid) {
            b[k] = a[i];
            i++;
            k++;
        }
    }
    for (k = lb; k <= ub; k++) {
        a[k] = b[k];
    }
}

void mergeSort(int a[], int lb, int ub, int b[]) {
    if (lb < ub) {
        int mid = (lb + ub) / 2;
        mergeSort(a, lb, mid, b);
        mergeSort(a, mid + 1, ub, b);
        merge(a, lb, mid, ub, b);
    }
}

void printList(int A[], int len) {
    for (int k = 0; k < len; k++) {
        printf(" %d", A[k]);
    }
    printf("\n");
}

int main() {
    int a[] = { 15, 5, 24, 8, 1, 3, 16, 10, 20 };
    int len = sizeof(a) / sizeof(a[0]);
    // make b a temporary array the same size as a
    int b[len];

    printf("before:");
    printList(a, len);
    mergeSort(a, 0, len - 1, b);
    printf("after:");
    printList(a, len);
    return 0;
}
</code>```

Output:

```
before: 15 5 24 8 1 3 16 10 20
after: 1 3 5 8 10 15 16 20 24
```

Note that is it less error prone to pass ub as the index to the element after the last one of the slice, this way the slice length is ub - lb and you do not need any confusing +1/-1 adjustments. Furthermore, there is no need to copy the remaining elements from the right half as they are already in the proper position in the destination array.

Here is a modified version with these simplifications:

#include <stdio.h>

void merge(int a[], int lb, int mid, int ub, int b[]) {
    int i = lb;
    int j = mid;
    int k = lb;

    while (i < mid && j < ub) {
        if (a[i] <= a[j]) {
            b[k++] = a[i++];
        } else {
            b[k++] = a[j++];
        }
    }
    while (i < mid) {
        b[k++] = a[i++];
    }
    for (i = lb; i < k; i++) {
        a[i] = b[i];
    }
}

void mergeSort(int a[], int lb, int ub, int b[]) {
    if (ub - lb >= 2) {
        int mid = lb + (ub - lb) / 2;
        mergeSort(a, lb, mid, b);
        mergeSort(a, mid, ub, b);
        merge(a, lb, mid, ub, b);
    }
}

void printList(int A[], int len) {
    for (int k = 0; k < len; k++) {
        printf(" %d", A[k]);
    }
    printf("\n");
}

int main() {
    int a[] = { 15, 5, 24, 8, 1, 3, 16, 10, 20 };
    int len = sizeof(a) / sizeof(a[0]);
    // make b a temporary array the same size as a
    int b[len];

    printf("before:");
    printList(a, len);
    mergeSort(a, 0, len, b);
    printf("after:");
    printList(a, len);
    return 0;
}
```

Body:
int lb = 0, ub = 8, mid;   //ub=upper bound,lb=lower bound.
int i = 0, j = 0, k = 0;
int a[] = { 15, 5, 24, 8, 1, 3, 16, 10, 20 };
int b[10];

void mergeSort(int a[], int lb, int ub) {
    if (lb < ub) {
        mid = ((lb + ub) / 2);
        mergeSort(a, lb, mid);
        mergeSort(a, mid + 1, ub);
        merge(a, lb, mid, ub);
    }
}

void merge(int a[], int lb, int mid, int ub) {
    i = lb;
    j = mid + 1;
    k = lb;

    while (i <= mid && j <= ub) {
        if (a[i] <= a[j]) {
            b[k] = a[i];
            i++;
        } else {
            b[k] = a[j];
            j++;
        }
        k++;
    }

    if (i > mid) {
        while (j <= ub) {
            b[k] = a[j];
            j++;
            k++;
        }
    } else {
        while (i <= mid) {
            b[k] = a[i];
            i++;
            k++;
        }
    }

    for (k = lb; k <= ub; k++) {
        a[k] = b[k];
    }
}

void printList(int A[]) {
    for (k = 0; k <= 8; k++) {
        printf("%d\n", A[k]);
    }
    printf("done\n");
}

int main() {
    printList(a);
    mergeSort(a, 0, 8);
    printList(a);
}

I think the code of mergesort and merge is not the problem, the problem is how I have checked the code many times but I cannot find the mistakes, so I hope someone could explain to me where is the problems, thanks for everyone who try to help!!

the output when I run the code:

5
15
8
1
3
16
10
20
24
done

which is not a sorted list.

Body:
The problem is mid is a global variable, so it gets modified by the recursive call mergeSort(a, lb, mid); and a different value is used for the second recursive call mergeSort(a, mid + 1, ub); and yet a different value is used for the final call merge(a, lb, mid, ub); producing unexpected results, and potentially causing undefined behavior.

Do not use global variables. Define both arrays in main, make i, j, k and mid local variables in merge and mergeSort and pass the auxiliary array b to merge and mergeSort.

Here is a modified version:

#include <stdio.h>

void merge(int a[], int lb, int mid, int ub, int b[]) {
    int i = lb;
    int j = mid + 1;
    int k = lb;

    while (i <= mid && j <= ub) {
        if (a[i] <= a[j]) {
            b[k] = a[i];
            i++;
        } else {
            b[k] = a[j];
            j++;
        }
        k++;
    }
    if (i > mid) {
        while (j <= ub) {
            b[k] = a[j];
            j++;
            k++;
        }
    } else {
        while (i <= mid) {
            b[k] = a[i];
            i++;
            k++;
        }
    }
    for (k = lb; k <= ub; k++) {
        a[k] = b[k];
    }
}

void mergeSort(int a[], int lb, int ub, int b[]) {
    if (lb < ub) {
        int mid = (lb + ub) / 2;
        mergeSort(a, lb, mid, b);
        mergeSort(a, mid + 1, ub, b);
        merge(a, lb, mid, ub, b);
    }
}

void printList(int A[], int len) {
    for (int k = 0; k < len; k++) {
        printf(" %d", A[k]);
    }
    printf("\n");
}

int main() {
    int a[] = { 15, 5, 24, 8, 1, 3, 16, 10, 20 };
    int len = sizeof(a) / sizeof(a[0]);
    // make b a temporary array the same size as a
    int b[len];

    printf("before:");
    printList(a, len);
    mergeSort(a, 0, len - 1, b);
    printf("after:");
    printList(a, len);
    return 0;
}

Output:

before: 15 5 24 8 1 3 16 10 20
after: 1 3 5 8 10 15 16 20 24

Note that is it less error prone to pass ub as the index to the element after the last one of the slice, this way the slice length is ub - lb and you do not need any confusing +1/-1 adjustments. Furthermore, there is no need to copy the remaining elements from the right half as they are already in the proper position in the destination array.

Here is a modified version with these simplifications:

#include <stdio.h>

void merge(int a[], int lb, int mid, int ub, int b[]) {
    int i = lb;
    int j = mid;
    int k = lb;

    while (i < mid && j < ub) {
        if (a[i] <= a[j]) {
            b[k++] = a[i++];
        } else {
            b[k++] = a[j++];
        }
    }
    while (i < mid) {
        b[k++] = a[i++];
    }
    for (i = lb; i < k; i++) {
        a[i] = b[i];
    }
}

void mergeSort(int a[], int lb, int ub, int b[]) {
    if (ub - lb >= 2) {
        int mid = lb + (ub - lb) / 2;
        mergeSort(a, lb, mid, b);
        mergeSort(a, mid, ub, b);
        merge(a, lb, mid, ub, b);
    }
}

void printList(int A[], int len) {
    for (int k = 0; k < len; k++) {
        printf(" %d", A[k]);
    }
    printf("\n");
}

int main() {
    int a[] = { 15, 5, 24, 8, 1, 3, 16, 10, 20 };
    int len = sizeof(a) / sizeof(a[0]);
    // make b a temporary array the same size as a
    int b[len];

    printf("before:");
    printList(a, len);
    mergeSort(a, 0, len, b);
    printf("after:");
    printList(a, len);
    return 0;
}


问:
How to pass data between 3 components on React?
Hey I am pretty noob at React. This props and State stuff are eating my head. Anyway, my problem is that,
I have 3 Componenets "LoginForm", "InputField", "SubmitButton"

What I need is, I want to pass "Username" and "Password" details to SubmitButton Component when the SubmitButton clicked. I tried and succeded to pass data from InputField to LoginForm whenever the inputfield value changes, but couldn't do the same to "SubmitButton" Component.

Thanks in Advance :)

The code is here as follows.

```<code>//LOGING FORM COMPONENT
class LoginForm extends React.Component {

    eventHandler = function (data) {
        console.log(data)
    }

    render() {
        return (

            <div>
                <InputField onChange={this.eventHandler}/>
                <SubmitButton/>
            </div>
        )
    }
}

export default LoginForm;

//INPUT FIELD COMPONENT

class InputField extends React.Component {
    constructor(props){
        super(props);
        this.state={
            username:'',
            password:''
        };
        this.handleChange=this.handleChange.bind(this)
    }

handleChange = e => {
    this.setState({ [e.target.name]: e.target.value }, () => {
      if (this.props.onChange) {
        this.props.onChange(this.state);
      }
    })
  };

    render() {
        return (
            <div>
                <div>
                    <input name='username' onChange={this.handleChange}></input>

                </div>
                <div>
                    <input name='password' type='password' onChange={this.handleChange}></input>

                </div>

            </div>

        )
    }
}

export default InputField;

//SUBMIT BUTTON COMPONENT

class Submit_Button extends React.Component {

    constructor(props){
        super(props);
        this.loginBtn=this.loginBtn.bind(this)

    }
    loginBtn = function (data) {

        //Empty Because, dont know what to code xD
    }

    render() {
        return (
            <div>
                <button onClick={this.loginBtn}>
                    Login</button>
                <svg class="bi bi-person" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                    <path fill-rule="evenodd" d="M13 14s1 0 1-1-1-4-6-4-6 3-6 4 1 1 1 1h10zm-9.995-.944v-.002.002zM3.022 13h9.956a.274.274 0 00.014-.002l.008-.002c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10c-2.29 0-3.516.68-4.168 1.332-.678.678-.83 1.418-.832 1.664a1.05 1.05 0 00.022.004zm9.974.056v-.002.002zM8 7a2 2 0 100-4 2 2 0 000 4zm3-2a3 3 0 11-6 0 3 3 0 016 0z" clip-rule="evenodd" />
                </svg>
            </div>

        )

    }
}
export default Submit_Button;
</code>```

SOLVED

```<code>class LoginForm extends React.Component {
    constructor(props){
        super(props);
        this.state={
            username:'',
            password:''
        };

    }

    eventHandler = (data) =>{
        console.log(data)
        this.setState({
            username:data.username,
            password:data.password

    },
    console.log(this.state.username))

    }

    render() {
        return (

            <div>
                <InputField onChange={this.eventHandler}/>
                <SubmitButton username={this.state.username} password={this.state.password}/>
            </div>
        )
    }
}

export default LoginForm;

class InputField extends React.Component {
    constructor(props){
        super(props);
        this.state={
            username:'',
            password:''
        };
        this.handleChange=this.handleChange.bind(this)
    }

handleChange = e => {
    this.setState({ [e.target.name]: e.target.value }, () => {
      if (this.props.onChange) {
        this.props.onChange(this.state);

      }
    },

    )
  };

    render() {
        return (
            <div>
                <div>
                    <input name='username' onChange={this.handleChange}></input>

                </div>
                <div>
                    <input name='password' type='password' onChange={this.handleChange}></input>

                </div>

            </div>

        )
    }
}

export default InputField;

class Submit_Button extends React.Component {

    constructor(props){
        super(props);
        this.loginBtn=this.loginBtn.bind(this)

    }
    loginBtn = function (data) {

        console.log( this.props.username, this.props.password)
    }

    render() {
        return (
            <div>
                <button onClick={this.loginBtn}>
                    Login</button>
                <svg className="bi bi-person" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                    <path fillRule="evenodd" d="M13 14s1 0 1-1-1-4-6-4-6 3-6 4 1 1 1 1h10zm-9.995-.944v-.002.002zM3.022 13h9.956a.274.274 0 00.014-.002l.008-.002c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10c-2.29 0-3.516.68-4.168 1.332-.678.678-.83 1.418-.832 1.664a1.05 1.05 0 00.022.004zm9.974.056v-.002.002zM8 7a2 2 0 100-4 2 2 0 000 4zm3-2a3 3 0 11-6 0 3 3 0 016 0z" clipRule="evenodd" />
                </svg>
            </div>

        )

    }
}
export default Submit_Button;
</code>```

答:
Basically, it is a good idea to pass data from one child to another through their parent.

in this case, you can move the state from InputField to LoginForm and connect inputs to the state through InputField's props and make them controlled components. (you can read more about controlled components from here)

then you can simply pass data from LoginForm's state to SubmitButton through its props.

Body:
Hey I am pretty noob at React. This props and State stuff are eating my head. Anyway, my problem is that,
I have 3 Componenets "LoginForm", "InputField", "SubmitButton"

What I need is, I want to pass "Username" and "Password" details to SubmitButton Component when the SubmitButton clicked. I tried and succeded to pass data from InputField to LoginForm whenever the inputfield value changes, but couldn't do the same to "SubmitButton" Component.

Thanks in Advance :)

The code is here as follows.

//LOGING FORM COMPONENT
class LoginForm extends React.Component {

    eventHandler = function (data) {
        console.log(data)
    }

    render() {
        return (

                <InputField onChange={this.eventHandler}/>
                <SubmitButton/>

        )
    }
}

export default LoginForm;

//INPUT FIELD COMPONENT

class InputField extends React.Component {
    constructor(props){
        super(props);
        this.state={
            username:'',
            password:''
        };
        this.handleChange=this.handleChange.bind(this)
    }

handleChange = e => {
    this.setState({ [e.target.name]: e.target.value }, () => {
      if (this.props.onChange) {
        this.props.onChange(this.state);
      }
    })
  };

    render() {
        return (

                    <input name='username' onChange={this.handleChange}></input>

                    <input name='password' type='password' onChange={this.handleChange}></input>

        )
    }
}

export default InputField;

//SUBMIT BUTTON COMPONENT

class Submit_Button extends React.Component {

    constructor(props){
        super(props);
        this.loginBtn=this.loginBtn.bind(this)

    }
    loginBtn = function (data) {

        //Empty Because, dont know what to code xD
    }

    render() {
        return (

                <button onClick={this.loginBtn}>
                    Login</button>
                <svg class="bi bi-person" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                    <path fill-rule="evenodd" d="M13 14s1 0 1-1-1-4-6-4-6 3-6 4 1 1 1 1h10zm-9.995-.944v-.002.002zM3.022 13h9.956a.274.274 0 00.014-.002l.008-.002c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10c-2.29 0-3.516.68-4.168 1.332-.678.678-.83 1.418-.832 1.664a1.05 1.05 0 00.022.004zm9.974.056v-.002.002zM8 7a2 2 0 100-4 2 2 0 000 4zm3-2a3 3 0 11-6 0 3 3 0 016 0z" clip-rule="evenodd" />
                </svg>

        )

    }
}
export default Submit_Button;

SOLVED

class LoginForm extends React.Component {
    constructor(props){
        super(props);
        this.state={
            username:'',
            password:''
        };

    }

    eventHandler = (data) =>{
        console.log(data)
        this.setState({
            username:data.username,
            password:data.password

    },
    console.log(this.state.username))

    }

    render() {
        return (

                <InputField onChange={this.eventHandler}/>
                <SubmitButton username={this.state.username} password={this.state.password}/>

        )
    }
}

export default LoginForm;

class InputField extends React.Component {
    constructor(props){
        super(props);
        this.state={
            username:'',
            password:''
        };
        this.handleChange=this.handleChange.bind(this)
    }

handleChange = e => {
    this.setState({ [e.target.name]: e.target.value }, () => {
      if (this.props.onChange) {
        this.props.onChange(this.state);

      }
    },

    )
  };

    render() {
        return (

                    <input name='username' onChange={this.handleChange}></input>

                    <input name='password' type='password' onChange={this.handleChange}></input>

        )
    }
}

export default InputField;

class Submit_Button extends React.Component {

    constructor(props){
        super(props);
        this.loginBtn=this.loginBtn.bind(this)

    }
    loginBtn = function (data) {

        console.log( this.props.username, this.props.password)
    }

    render() {
        return (

                <button onClick={this.loginBtn}>
                    Login</button>
                <svg className="bi bi-person" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                    <path fillRule="evenodd" d="M13 14s1 0 1-1-1-4-6-4-6 3-6 4 1 1 1 1h10zm-9.995-.944v-.002.002zM3.022 13h9.956a.274.274 0 00.014-.002l.008-.002c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10c-2.29 0-3.516.68-4.168 1.332-.678.678-.83 1.418-.832 1.664a1.05 1.05 0 00.022.004zm9.974.056v-.002.002zM8 7a2 2 0 100-4 2 2 0 000 4zm3-2a3 3 0 11-6 0 3 3 0 016 0z" clipRule="evenodd" />
                </svg>

        )

    }
}
export default Submit_Button;


问:
await messages, get a channel by the given ID
So i want that my poll command asks for the channel and the question in a conversation, but i haven't figured out how to get the channel when the user only gives the ID, i have figured out that i have to use .content but i still don't know how to implement it.

My code:

```<code>run: async(message, client, args) => {

  // Channel where the poll should take palce
  await message.channel.send(`Please provide a channel where the poll should take place or cancel this command with "cancel"!`)
  const response1 = await message.channel.awaitMessages(m => m.author.id === message.author.id, {max: 1});
  const channel = response1.first().mentions.channels.first() || response1.content.guild.channels.cache.get()

  if (!channel) {
    return message.channel.send(`You did not mention or provide the ID of a channel where the poll should take place!`)
  }

  // Channel where the poll should take palce
  await message.channel.send(`Please provide a question for the poll!`)
  const response2 = await message.channel.awaitMessages(m => m.author.id === message.author.id, {max: 1});
  let question = response2.first();

  if (!question) {
    return message.channel.send(`You did not specify your question!`)
  }

  const Embed = new Discord.MessageEmbed()
    .setTitle(`New poll!`)
    .setDescription(`${question}`)
    .setFooter(`${message.author.username} created this poll.`)
    .setColor(`0x0099ff`)
  let msg = await client.channels.cache.get(channel.id).send(Embed)
  await msg.react("")
  await msg.react("")
}
</code>```

And it is this line: response1.content.guild.channels.cache.get() that is writte wrong by me but idk what i have to change/where to add the .content so that it works.

Would be nice if someone can help me.

My message event for the args:

```<code>module.exports = async (client, message) => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;
    if (!message.guild) return;
    if (!message.member) message.member = await message.guild.fetchMember(message);
    const args = message.content.slice(prefix.length).split(/ +/g);
    const cmd = args.shift().toLowerCase();
    if (cmd.length == 0) return;
    let command = client.commands.get(cmd)
    if (!command) command = client.commands.get(client.aliases.get(cmd));
    if (command) {
        try {
            command.run(message, client, args)
        } catch (error) {
            console.error(error);
            message.reply('There was an error trying to execute that command!');
        }
    }
}
</code>```

答:
So i went around it with making another constructor means:

const ID = client.channels.cache.get(response1.first().content)
const channel = response1.first().mentions.channels.first() || ID

It works fine now

Body:
So i want that my poll command asks for the channel and the question in a conversation, but i haven't figured out how to get the channel when the user only gives the ID, i have figured out that i have to use .content but i still don't know how to implement it.

My code:

run: async(message, client, args) => {

  // Channel where the poll should take palce
  await message.channel.send(`Please provide a channel where the poll should take place or cancel this command with "cancel"!`)
  const response1 = await message.channel.awaitMessages(m => m.author.id === message.author.id, {max: 1});
  const channel = response1.first().mentions.channels.first() || response1.content.guild.channels.cache.get()

  if (!channel) {
    return message.channel.send(`You did not mention or provide the ID of a channel where the poll should take place!`)
  }

  // Channel where the poll should take palce
  await message.channel.send(`Please provide a question for the poll!`)
  const response2 = await message.channel.awaitMessages(m => m.author.id === message.author.id, {max: 1});
  let question = response2.first();

  if (!question) {
    return message.channel.send(`You did not specify your question!`)
  }

  const Embed = new Discord.MessageEmbed()
    .setTitle(`New poll!`)
    .setDescription(`${question}`)
    .setFooter(`${message.author.username} created this poll.`)
    .setColor(`0x0099ff`)
  let msg = await client.channels.cache.get(channel.id).send(Embed)
  await msg.react("")
  await msg.react("")
}

And it is this line: response1.content.guild.channels.cache.get() that is writte wrong by me but idk what i have to change/where to add the .content so that it works.

Would be nice if someone can help me.

My message event for the args:

module.exports = async (client, message) => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;
    if (!message.guild) return;
    if (!message.member) message.member = await message.guild.fetchMember(message);
    const args = message.content.slice(prefix.length).split(/ +/g);
    const cmd = args.shift().toLowerCase();
    if (cmd.length == 0) return;
    let command = client.commands.get(cmd)
    if (!command) command = client.commands.get(client.aliases.get(cmd));
    if (command) {
        try {
            command.run(message, client, args)
        } catch (error) {
            console.error(error);
            message.reply('There was an error trying to execute that command!');
        }
    }
}


问:
I'm trying to create an invite tracker using discord.py
Alright, my goal here is to create an invite tracker. Currently, you can run the command /invites and it'll tell you how many invites you have. Here's the code for it.

```<code>@client.command()
async def invites(ctx):
    totalInvites = 0
    for i in await ctx.guild.invites():
        if i.inviter == ctx.author:
            totalInvites += i.uses
    await ctx.send(f"{ctx.author.mention}, you've invited {totalInvites} member{'' if totalInvites == 1 else 's'}!")
</code>```

I'm wondering if there's a way I can find others' invites as well by doing /invites @user. Also, to go even further, could I possibly create a /leaderboards command? It should show an embed with a list of the top 10 people for invites along with how many invites they have. And I'd like it if there was a way to subtract the number of invites when someone leaves the server.

答:
@client.command()
async def invites(ctx, usr: discord.Member=None):
    if usr == None:
       user = ctx.author
    else:
       user = usr
    total_invites = 0
    for i in await ctx.guild.invites():
        if i.inviter == user:
            total_invites += i.uses
    await ctx.send(f"{user.name} has invited {totalInvites} member{'' if totalInvites == 1 else 's'}!")
```

I apologize that I was unable to actually run the code. If the above code produces an error please tell me.

Body:
Alright, my goal here is to create an invite tracker. Currently, you can run the command /invites and it'll tell you how many invites you have. Here's the code for it.

@client.command()
async def invites(ctx):
    totalInvites = 0
    for i in await ctx.guild.invites():
        if i.inviter == ctx.author:
            totalInvites += i.uses
    await ctx.send(f"{ctx.author.mention}, you've invited {totalInvites} member{'' if totalInvites == 1 else 's'}!")

I'm wondering if there's a way I can find others' invites as well by doing /invites @user. Also, to go even further, could I possibly create a /leaderboards command? It should show an embed with a list of the top 10 people for invites along with how many invites they have. And I'd like it if there was a way to subtract the number of invites when someone leaves the server.

Body:
@client.command()
async def invites(ctx, usr: discord.Member=None):
    if usr == None:
       user = ctx.author
    else:
       user = usr
    total_invites = 0
    for i in await ctx.guild.invites():
        if i.inviter == user:
            total_invites += i.uses
    await ctx.send(f"{user.name} has invited {totalInvites} member{'' if totalInvites == 1 else 's'}!")

I apologize that I was unable to actually run the code. If the above code produces an error please tell me.


问:
Google Static Maps Panning and Zooming
I've got a scenario where I have a website that utilizes Google Maps, and falls back to Static Maps if the user doesn't have JavaScript.

A client requirement is that the user should still be able to pan and zoom (assuming a page refresh for each zoom, or pan).

So each zoom or pan, the page will refresh, and on the server side I need to regenerate a static map based upon what the user is trying to do.

The way I'm initially generating the static map is passing in all of my markers (not defining a center point, or zoom, letting Google figure that out on their end) through the Google Static Maps URL.

The problem I'm running into is when I'm panning, how to get the bounds of the static map that Google generated, so I know what points to pan from.

Has anyone see this done? Or have any insight?

Programming language is Ruby.

Thanks!

答:
I don't think it's possible (although I'd love for someone to prove me wrong) to easily get the bounds of a map from the Static Maps API.

Your best bet may be to calculate an appropriate center, zoom, and map size based on the markers you want to show rather than relying on Static Maps to do it for you, and then handle/calculate zooming and panning based on that.

ContentLicense: CC BY-SA 2.5

Title: Google Static Maps Panning and Zooming


问:
Flutter Firebase delete subcollections not working
In my Firebase structure I have a collection and some sub-collections within it. I would like when I delete the collection, also delete the subcollections. I'm trying to do what's in the Firebase documentation: "To delete an entire collection or subcollection in Cloud Firestore, retrieve all the documents within the collection or subcollection and delete them". But is not working. I delete the collection and the subcollection still saved. My code:

```<code>    void deleteNestedSubcollections(String id) {

    Future<QuerySnapshot> books = libraryCollection.document(id).collection("Books").getDocuments();
    books.then((value) => value.documents.remove(value));

    Future<QuerySnapshot> catalogues = libraryCollection.document(id).collection("Catalogues").getDocuments();
    catalogues.then((value) => value.documents.remove(value));
  }
</code>```

EDIT 1

答:
To delete a document, you need to use the delete method:

```<code>
  void deleteNestedSubcollections(String id) {
    Future<QuerySnapshot> books =
        libraryCollection.document(id).collection("Books").getDocuments();
    books.then((value) {
      value.documents.forEach((element) {
        libraryCollection
            .document(id)
            .collection("Books")
            .document(element.documentID)
            .delete()
            .then((value) => print("success"));
      });
    });
  }
</code>```

Body:
In my Firebase structure I have a collection and some sub-collections within it. I would like when I delete the collection, also delete the subcollections. I'm trying to do what's in the Firebase documentation: "To delete an entire collection or subcollection in Cloud Firestore, retrieve all the documents within the collection or subcollection and delete them". But is not working. I delete the collection and the subcollection still saved. My code:

    void deleteNestedSubcollections(String id) {

    Future<QuerySnapshot> books = libraryCollection.document(id).collection("Books").getDocuments();
    books.then((value) => value.documents.remove(value));

    Future<QuerySnapshot> catalogues = libraryCollection.document(id).collection("Catalogues").getDocuments();
    catalogues.then((value) => value.documents.remove(value));
  }

EDIT 1

Body:
To delete a document, you need to use the delete method:

  void deleteNestedSubcollections(String id) {
    Future<QuerySnapshot> books =
        libraryCollection.document(id).collection("Books").getDocuments();
    books.then((value) {
      value.documents.forEach((element) {
        libraryCollection
            .document(id)
            .collection("Books")
            .document(element.documentID)
            .delete()
            .then((value) => print("success"));
      });
    });
  }


问:
What command to use to zoom out a plot in R?
I have a barplot and the names for the bars are all vertical on the x-axis. However, the names are fairly long and don't show completely in the plot. Is there any command I can use to zoom out the plot? I have already tried the package "zoom" and zm() but it doesn't work.</p>

答:
One way to handle this is to increase the margin size before plotting.   Here is a simple example.  First, to show the problem:

```<code>LongNames = c("RatherLongName_1", "RatherLongName_2",
            "RatherLongName_3", "RatherLongName_4")
barplot(1:4, names.arg=LongNames, las=3)
</code>```

Then with the margins adjusted.

```<code>par(mar=c(10,4,4,2))
barplot(1:4, names.arg=LongNames, las=3)
</code>```

Body:
One way to handle this is to increase the margin size before plotting.   Here is a simple example.  First, to show the problem:

LongNames = c("RatherLongName_1", "RatherLongName_2",
            "RatherLongName_3", "RatherLongName_4")
barplot(1:4, names.arg=LongNames, las=3)

Then with the margins adjusted.

par(mar=c(10,4,4,2))
barplot(1:4, names.arg=LongNames, las=3)


问:
How to detect the value of color picker in text input and show it in preview instantly?
I want to show a preview of plugin output with color changes instantly. For getting values from input text I will use the

keyup

changed

on click

functions.

But in case of color picker user is interacting with the color picker so the above functions are not working, obviously it will work only if user focus or enter some input so I used the setInterval function

```<code>setInterval(function () {
    var h = jQuery('#bgcolor').val();
    jQuery(".bat-gh").css("background", h);
}, 100);
</code>```

This is working perfectly fine I can show the output which the user is selecting.

Here is my question:

Will this create extra burden or load to my plugin or make the browser
non-responsive?

Any other alternative way to show the color values when user
changes?

答:
```<code>/* jQuery */
if( $('.stwpmodpop-cpicker').length ) {

    $('.stwpmodpop-cpicker').wpColorPicker({
        change: function( event, ui ) {
            var theColor = ui.color.toString();
            $(this).parent().parent().parent().siblings('.stwpmodpop-fillcolor').html( theColor );
        }
    });
}

/* HTML */
<p>
    <input type="text" class="form-control stwpmodpop-cpicker" name="colorpicker_example" value="" />
    <span class="stwpmodpop-fillcolor"></span>
</p>
</code>```

Body:
I want to show a preview of plugin output with color changes instantly. For getting values from input text I will use the

keyup

changed

on click

functions.

But in case of color picker user is interacting with the color picker so the above functions are not working, obviously it will work only if user focus or enter some input so I used the setInterval function

setInterval(function () {
    var h = jQuery('#bgcolor').val();
    jQuery(".bat-gh").css("background", h);
}, 100);

This is working perfectly fine I can show the output which the user is selecting.

Here is my question:

Will this create extra burden or load to my plugin or make the browser
non-responsive?

Any other alternative way to show the color values when user
changes?


问:
Pushing File into Android Device
I have developed an application which read text file. In Emulator I have push the file in
\Data\Data\PackageName\File.txt and its working fine. But when I try to push file in Device its generate the error Read Only File System. I have try to remount directory as writable but the same error. Please help me how can I push file into device.

答:
The folder you are trying is locked on non-rooted phones i.e no write permission and I guess the device you are trying on is not a rooted one. since emulator is sort of developer device which is said to be rooted that's why you can push file to that location.

So depending on your requirement you have to either use Assest folder or File system storage

Update: How to use assest folder

```<code>Resources r = getResources();
AssetManager assetManager = r.getAssets();
InputStream in = assetManager.open(filename);
</code>```

Title: Pushing File into Android Device

Body:
The folder you are trying is locked on non-rooted phones i.e no write permission and I guess the device you are trying on is not a rooted one. since emulator is sort of developer device which is said to be rooted that's why you can push file to that location.

So depending on your requirement you have to either use Assest folder or File system storage

Update: How to use assest folder

Resources r = getResources();
AssetManager assetManager = r.getAssets();
InputStream in = assetManager.open(filename);


问:
React Native - How to save map using AsyncStorage
I try to save user inputs as a JS map using AsyncStorage in my React Native app.

It shows no errors when saving, but I got "[object Map]" when I tried to get the data back.

There is the simplified version of my user map. the actual User object has way more properties than this, but the ID is always same as the map key.

```<code>const dataKey = 'user-data';
let data = new Map();
data.set(1, { name: 'John', id: 1, title: 'Mr.' })
data.set(2, { name: 'Johanna', id: 2, title: 'Miss.' })
</code>```

There is the code for saving the data.

```<code>async saveDate = (dataKey, data) => {
  try {
    await AsyncStorage.setItem(dataKey, data.toString());
  } catch (err) {
    console.log(err);
  }
}
</code>```

There will be more than 200 users in this map.

Any idea how to save complex data structure in react native?

答:
The provided answers will not quite work. You can't create the new Map after reading back json without parsing first. This works:

```<code>  saveData = async () => {
    const dataKey = 'user-data';
    let data = new Map();
    data.set(1, { name: 'John', id: 1, title: 'Mr.' })
    data.set(2, { name: 'Johanna', id: 2, title: 'Miss.' })

    try {
      await AsyncStorage.setItem(dataKey, JSON.stringify([...data]));
    } catch (err) {
      console.log(err);
    }

    const jsonData = await AsyncStorage.getItem(dataKey)
    const parseData = JSON.parse(jsonData)
    const mapData = new Map(parseData)

    console.log(mapData);
    //get a list of IDs
    console.log(Array.from(mapData.keys()));

}
</code>```

For 200 values this is a lot of overhead. I would consider using sprintf/sscanf libraries and just store a string, for instance one row of data per line.
This will only work if every row in the table has the same amount of elements and you don't change the layout. Of course it would all be on you to convert the string back to objects so you can recreate the Map. Just a thought!

Body:
I try to save user inputs as a JS map using AsyncStorage in my React Native app.

It shows no errors when saving, but I got "[object Map]" when I tried to get the data back.

There is the simplified version of my user map. the actual User object has way more properties than this, but the ID is always same as the map key.

const dataKey = 'user-data';
let data = new Map();
data.set(1, { name: 'John', id: 1, title: 'Mr.' })
data.set(2, { name: 'Johanna', id: 2, title: 'Miss.' })

There is the code for saving the data.

async saveDate = (dataKey, data) => {
  try {
    await AsyncStorage.setItem(dataKey, data.toString());
  } catch (err) {
    console.log(err);
  }
}

There will be more than 200 users in this map.

Any idea how to save complex data structure in react native?

Body:
The provided answers will not quite work. You can't create the new Map after reading back json without parsing first. This works:

  saveData = async () => {
    const dataKey = 'user-data';
    let data = new Map();
    data.set(1, { name: 'John', id: 1, title: 'Mr.' })
    data.set(2, { name: 'Johanna', id: 2, title: 'Miss.' })

    try {
      await AsyncStorage.setItem(dataKey, JSON.stringify([...data]));
    } catch (err) {
      console.log(err);
    }

    const jsonData = await AsyncStorage.getItem(dataKey)
    const parseData = JSON.parse(jsonData)
    const mapData = new Map(parseData)

    console.log(mapData);
    //get a list of IDs
    console.log(Array.from(mapData.keys()));

}

For 200 values this is a lot of overhead. I would consider using sprintf/sscanf libraries and just store a string, for instance one row of data per line.
This will only work if every row in the table has the same amount of elements and you don't change the layout. Of course it would all be on you to convert the string back to objects so you can recreate the Map. Just a thought!


问:
JAVA Method returns unexpected value
I am a very new java programmer, the below code is my first attempt at my own project.  I'm certain the code is a mess, please forgive me.

In the below code the user is prompted to enter 5 values between 1 and 50.
I am placing the input values into an int[].
I want to verify that the numbers are in range so I pass the value to a method.
MY ISSUE:
If the value is in range it gets returned then the for loop increments to repeat - Good Behavior
If an invalid value is entered the check is done, error message is displayed and the user is prompted to reenter a proper value.
If one invalid entry is made and a proper value is entered on the second attempt, a correct value is returned - Good Behavior
If two invalid entries are made the second invalid entry somehow gets passed back to the for loop and gets added to array - BAD Behavior

I am certain there is something simple I am missing.

```<code>public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("you get 5 elements between 01 & 50:");
    int a[] = new int[5];
    System.out.println("\nEnter all the elements:");
    for(int i = 0; i < 5;)
    {
        int b = in.nextInt();
        a[i] = checkNum(b);
        i++;
    }
    System.out.println("Numbers:" + Arrays.toString(a));
    in.close();
}

static int checkNum(int z) {
    Scanner s = new Scanner(System.in);
    if (z>0 && z<51) {
        return z;
    } else {
        System.out.println("Invalid Entry!! Enter a valid number between 01 & 50");
        int qz = s.nextInt();
        z = qz;
        checkNum(qz);
    }
    return z;
}
</code>```

答:
You could follow a simpler approach assuming the user will input numbers and not other characters (that would throw an exception),

```<code>    public static void main(String[] args) {
        System.out.print("you get 5 elements between 01 & 50:");

        Scanner in = new Scanner(System.in);
        int a[] = new int[5];

        int i = 0;
        do{
            System.out.println("Enter an element:");
            int b = in.nextInt();

            if (b > 0 && b < 51){
                a[i] = b;
                i++;
            }else{
                System.out.println("Invalid Entry!! Enter a valid number between 01 & 50");
            }
        }while(i < 5);

        in.close();
        System.out.println("Numbers:" + Arrays.toString(a));
    }
</code>```

Here you're asking for valid input until the threshold of 5 is reached. Because you don't know beforehand how many times the user will provide input, until the criteria are met, a do-while loop is used.

Title: JAVA Method returns unexpected value

Body:
I am a very new java programmer, the below code is my first attempt at my own project.  I'm certain the code is a mess, please forgive me.

In the below code the user is prompted to enter 5 values between 1 and 50.
I am placing the input values into an int[].
I want to verify that the numbers are in range so I pass the value to a method.
MY ISSUE:
If the value is in range it gets returned then the for loop increments to repeat - Good Behavior
If an invalid value is entered the check is done, error message is displayed and the user is prompted to reenter a proper value.
If one invalid entry is made and a proper value is entered on the second attempt, a correct value is returned - Good Behavior
If two invalid entries are made the second invalid entry somehow gets passed back to the for loop and gets added to array - BAD Behavior

I am certain there is something simple I am missing.

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("you get 5 elements between 01 & 50:");
    int a[] = new int[5];
    System.out.println("\nEnter all the elements:");
    for(int i = 0; i < 5;)
    {
        int b = in.nextInt();
        a[i] = checkNum(b);
        i++;
    }
    System.out.println("Numbers:" + Arrays.toString(a));
    in.close();
}

static int checkNum(int z) {
    Scanner s = new Scanner(System.in);
    if (z>0 && z<51) {
        return z;
    } else {
        System.out.println("Invalid Entry!! Enter a valid number between 01 & 50");
        int qz = s.nextInt();
        z = qz;
        checkNum(qz);
    }
    return z;
}

Body:
You could follow a simpler approach assuming the user will input numbers and not other characters (that would throw an exception),

    public static void main(String[] args) {
        System.out.print("you get 5 elements between 01 & 50:");

        Scanner in = new Scanner(System.in);
        int a[] = new int[5];

        int i = 0;
        do{
            System.out.println("Enter an element:");
            int b = in.nextInt();

            if (b > 0 && b < 51){
                a[i] = b;
                i++;
            }else{
                System.out.println("Invalid Entry!! Enter a valid number between 01 & 50");
            }
        }while(i < 5);

        in.close();
        System.out.println("Numbers:" + Arrays.toString(a));
    }

Here you're asking for valid input until the threshold of 5 is reached. Because you don't know beforehand how many times the user will provide input, until the criteria are met, a do-while loop is used.


问:
How to deserialize string with json.net - are there two versions of the library?
I want to deserialize a string (json) to an object (i'd like dynamic).

I use monodevelop and nuget packages

I have been looking for Json.net but also found Newtonsoft.Json.

And I could make a JArray by using Newtonsoft.Json.Linq.

I read on

Json.NET vs Newtonsoft.Json SerializationBinder is different

that these are two versions of the same library?

The main goal is to convert Json to Yaml.

答:
Newtonsoft.Json is most likely the one you want.  It has been known as "Json.Net" since it was first released in 2006 and has many features, including the LINQ-to-JSON API (JObject, JArrays, etc.).

However, in December 2018 (after the question you referenced was asked), another author unaffiliated with Newtonsoft released a completely different library on NuGet and called it Json.Net so now there is confusion.  This other library advertises itself as a "A Minimalistic JSON handler" so it intentionally does not have very many features.  It definitely does not have support for JArrays.