问:
Why doesn't react's test-util act() flush the job queue?
React design principles documentation states that "setState() is asynchronous". Although it does not mention useEffect, this documentation states:

What does useEffect do? By using this Hook, you tell React that your component needs to do something after render.

Which to me indicates it is also asynchronous.

The act() documentation states:

When writing UI tests, tasks like rendering, user events, or data fetching can be considered as “units” of interaction with a user interface. react-dom/test-utils provides a helper called act() that makes sure all updates related to these “units” have been processed and applied to the DOM before you make any assertions

Sunil Pai clarifies this a bit in his "Secrets of the act() API" article:

It guarantees 2 things for any code run inside its scope:

any state updates will be executed

any enqueued effects will be executed

Since state updates are asynchronous and act() gaurantees all states update will be executed, how can it do this without us having to call await in our tests?

And further, why doesn't act ensure other settled promises callbacks are executed as well?

Consider this example component:

```<code>function App() {
  const [foo, setFoo] = useState("");
  const [bar, setBar] = useState("");

  useEffect(() => {
    // Callback added to job queue as a microtask
    Promise.resolve().then(() => {
      setBar("bar");
    });
    // Making an asynchronous(?) state update
    setFoo(() => {
      return "foo";
    });
  }, []);

  return <p>{foo}{bar}</p>;
}
</code>```

And my test fails with Received: "foo":

```<code>test('foobar', async () => {
  act(() => {
    render(<App />, container);
  })
  expect(container.textContent).toBe("foobar");
});
</code>```

From above referenced documentation I've later understood that if you want to flush queued microtasks, you have the use the async version of act. But it doesn't explain how the synchronous act can flush reacts internal asynchronous logic without flushing my apps asynchronous logic. Act just feels like magic and a source to so much confusion for me.

答:
I believe the answer to this question is a rabbit hole which I'm not capable of fully understanding, let alone explaining to to any particular detail. The answer lies in Reacts scheduling implementation called React Fiber (introduced in react 16):

https://github.com/acdlite/react-fiber-architecture

Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.

[...]

Fiber is reimplementation of the stack, specialized for React components. You can think of a single fiber as a virtual stack frame.

The advantage of reimplementing the stack is that you can keep stack frames in memory and execute them however (and whenever) you want. This is crucial for accomplishing the goals we have for scheduling.

React Fiber works with the Channel Messaging API to perform small units of work asynchronously (explanation, source code, Github PR).

I assume it is because of this novel way of scheduling work to be performed that they can flush their asynchronous jobs in the scheduler (with synchronous act()) without having to await. Since we are not awaiting any async code, we are not flushing the runtime's event loop job queue. I think that is why we need to use the async version of act to both flush the job queue and the react scheduler.

I'll leave this question as unanswered in case someone can correct me or give a more in-depth answer.

Body:
React design principles documentation states that "setState() is asynchronous". Although it does not mention useEffect, this documentation states:

What does useEffect do? By using this Hook, you tell React that your component needs to do something after render.

Which to me indicates it is also asynchronous.

The act() documentation states:

When writing UI tests, tasks like rendering, user events, or data fetching can be considered as “units” of interaction with a user interface. react-dom/test-utils provides a helper called act() that makes sure all updates related to these “units” have been processed and applied to the DOM before you make any assertions

Sunil Pai clarifies this a bit in his "Secrets of the act() API" article:

It guarantees 2 things for any code run inside its scope:

any state updates will be executed

any enqueued effects will be executed

Since state updates are asynchronous and act() gaurantees all states update will be executed, how can it do this without us having to call await in our tests?

And further, why doesn't act ensure other settled promises callbacks are executed as well?

Consider this example component:

function App() {
  const [foo, setFoo] = useState("");
  const [bar, setBar] = useState("");

  useEffect(() => {
    // Callback added to job queue as a microtask
    Promise.resolve().then(() => {
      setBar("bar");
    });
    // Making an asynchronous(?) state update
    setFoo(() => {
      return "foo";
    });
  }, []);

  return
{foo}{bar}
;
}

And my test fails with Received: "foo":

test('foobar', async () => {
  act(() => {
    render(<App />, container);
  })
  expect(container.textContent).toBe("foobar");
});

From above referenced documentation I've later understood that if you want to flush queued microtasks, you have the use the async version of act. But it doesn't explain how the synchronous act can flush reacts internal asynchronous logic without flushing my apps asynchronous logic. Act just feels like magic and a source to so much confusion for me.


来源: stackexchange

问:
Create an array of strings
Is it possibe to create an array of strings in MATLAB within a for loop?

For example,

```<code>for i=1:10
Names(i)='Sample Text';
end
</code>```

I don't seem to be able to do it this way.

答:
You can create a character array that does this via a loop:

```
>> for i=1:10
Names(i,:)='Sample Text';
end
>> Names

Names =

Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
```

However, this would be better implemented using REPMAT:

```
>> Names = repmat('Sample Text', 10, 1)

Names =

Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
```

ContentLicense: CC BY-SA 3.0

Title: Create an array of strings

Body:
Is it possibe to create an array of strings in MATLAB within a for loop?

For example,

for i=1:10
Names(i)='Sample Text';
end

I don't seem to be able to do it this way.

Body:
You can create a character array that does this via a loop:

>> for i=1:10
Names(i,:)='Sample Text';
end
>> Names

Names =

Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text

However, this would be better implemented using REPMAT:

>> Names = repmat('Sample Text', 10, 1)

Names =

Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text


问:
Python exercise: lists sorting removing the nums
'Write a filter_ordered function that receives a list L1 of integers and returns a list L2 obtained starting from L1, eliminating all the elements that violate the growing order. In other words, an element of L1 must be inserted in L2 if and only if it is greater than all the elements that precede it in L1.

Example: If L1 = [1, 2, 5, 4, 7, 8, 3, 9] then filter_sorted (L1) returns the list L2 = [1, 2, 5, 7, 8, 9].'

this is my code:

```<code>def filtra_ordinati(l1):
    l2 = []
    for y in range(1,len(l1)):
        if l1[y-1] < l1[y]:
            l2.append(l1[y-1])
    return l2

L1 = [1, 2, 5, 4, 7, 8, 3, 9]
print(filtra_ordinati(L1))
</code>```

but gives me this output:

```<code>[1, 2, 4, 7, 3]
</code>```

what did I do wrong? (only list comprehension should be used)

答:
Change your function to:

```<code>def filtra_ordinati(l1):
    l2 = []
    for y in range(1,len(l1)):
        if l1[y-1] < l1[y]:
            print(f'I will add {l1[y-1]} because it smaller then {l1[y]}')
            l2.append(l1[y-1])
    return l2

L1 = [1, 2, 5, 4, 7, 8, 3, 9]
print(f'list is {L1}')
print(filtra_ordinati(L1))
</code>```

And you will see what you adding inside list and why.

Output will be:

```<code>list is [1, 2, 5, 4, 7, 8, 3, 9]
I will add 1 because it smaller then 2
I will add 2 because it smaller then 5
I will add 4 because it smaller then 7
I will add 7 because it smaller then 8
I will add 3 because it smaller then 9
[1, 2, 4, 7, 3]
</code>```

The correct function is:

```<code>def f(l):
  l2 = l[:1]
  for el in l:
    if el > l2[-1]:
      l2.append(el)
  return l2
</code>```

ContentLicense: CC BY-SA 4.0

Body:
'Write a filter_ordered function that receives a list L1 of integers and returns a list L2 obtained starting from L1, eliminating all the elements that violate the growing order. In other words, an element of L1 must be inserted in L2 if and only if it is greater than all the elements that precede it in L1.

Example: If L1 = [1, 2, 5, 4, 7, 8, 3, 9] then filter_sorted (L1) returns the list L2 = [1, 2, 5, 7, 8, 9].'

this is my code:

def filtra_ordinati(l1):
    l2 = []
    for y in range(1,len(l1)):
        if l1[y-1] < l1[y]:
            l2.append(l1[y-1])
    return l2

L1 = [1, 2, 5, 4, 7, 8, 3, 9]
print(filtra_ordinati(L1))

but gives me this output:

[1, 2, 4, 7, 3]

what did I do wrong? (only list comprehension should be used)

Body:
Change your function to:

def filtra_ordinati(l1):
    l2 = []
    for y in range(1,len(l1)):
        if l1[y-1] < l1[y]:
            print(f'I will add {l1[y-1]} because it smaller then {l1[y]}')
            l2.append(l1[y-1])
    return l2

L1 = [1, 2, 5, 4, 7, 8, 3, 9]
print(f'list is {L1}')
print(filtra_ordinati(L1))

And you will see what you adding inside list and why.

Output will be:

list is [1, 2, 5, 4, 7, 8, 3, 9]
I will add 1 because it smaller then 2
I will add 2 because it smaller then 5
I will add 4 because it smaller then 7
I will add 7 because it smaller then 8
I will add 3 because it smaller then 9
[1, 2, 4, 7, 3]

The correct function is:

def f(l):
  l2 = l[:1]
  for el in l:
    if el > l2[-1]:
      l2.append(el)
  return l2


问:
Getting wrong answer for simple algorithm with cycle detection
I am solving this problem, a part of the problem that is giving me troubles is formulated as follows:

a. Start from index i=0;

b. Jump to index i=A[i];

c. If the current index i is outside the valid bound of [0..N-1],
print “Out” and stop;

d. Else if the current index i is index N-1, print “Done” and stop;

e1. Otherwise, repeat step b;

e2. If doing this leads to an infinite loop, print “Cyclic” and
stop;

(all output are without the quotes)

arr is an array of non-negative integers:

let index = 0;
const seen = new Set([0]);
while (true) {
  index = arr[index];
  if (index > arr.length - 1) {
    console.log("Out");
    break;
  }
  if (index === arr.length - 1) {
    console.log("Done");
    break;
  }
  if (seen.has(index)) {
    console.log("Cyclic");
    break;
  }
  seen.add(index);
}
```

I am getting WA (Wrong Answer) on some hidden test cases, but I can't for the life of me come up with a failing test case.

1 2 3 4 5 0 -> Done

1 2 3 4 6 0 -> Out

1 0 0 -> Cyclic

Edit:

My C++ solution has exactly the same failed test cases, must really be something with my logic...

答:
I believe the issue is that the coded algorithm is not adhering to the requirement.  Specifically e1 indicates to repeat step b which fetches the next value, and **if doing this** leads to an infinite loop then print "Cycle".  The problem is that the code is actually doing it, rather than checking first...

So, as the current code is written, a test case of...

12344

...will return "Done" rather than "Cyclic"...

EDIT In the parlance code, this is what I'm suggesting (untested)...

```<code>let index = 0;
const seen = new Set([0]);
while (true) {
  index = arr[index];
  if (index > arr.length - 1) {
    console.log("Out");
    break;
  }
  if (index === arr.length - 1) {
    console.log("Done");
    break;
  }
  if (seen.has(index) || seen.has(arr[index])) {
    console.log("Cyclic");
    break;
  }
  seen.add(index);
}
</code>```

EDIT #2
Upon getting a chance to test my previously untested code just above, I discovered that it did not capture the nuance of my point.  So, in an effort to further clarify, below is the Current and Proposed algorithms, with sample cases to show the similarities and the difference.

The last case, where the cyclic entry is the final entry, is where step e2 reports "Cyclic" before step c is able to report "Done"...

Comments in the proposed() function show the steps of the algorithm...

function current( arr ) {
  let index = 0;
  const seen = new Set([0]);
  while (true) {
    index = arr[index];
    if (index > arr.length - 1) {
      console.log("Out");
      break;
    }
    if (index === arr.length - 1) {
      console.log("Done");
      break;
    }
    if (seen.has(index)) {
      console.log("Cyclic");
      break;
    }
    seen.add(index);
  }
}

function proposed( arr ) {
  // a. Start from index i=0;
  let index = 0;

  // b. Jump to index i=A[i];
  const seen = new Set( [ index ] );
  index = arr[ index ];

  while( true ) {
    // c. If the current index i is outside the valid bound of [0..N-1], print “Out” and stop;
    if ( index > arr.length - 1 ) {
      console.log( "Out" );
      break;
    }

    // d. Else if the current index i is index N-1, print “Done” and stop;
    if ( index === arr.length - 1 ) {
      console.log( "Done" );
      break;
    }

    // e1. Otherwise, repeat step b;
    seen.add( index );
    index = arr[ index ];

    // e2. If doing this leads to an infinite loop, print “Cyclic” and stop;
    if ( seen.has( arr[index] ) ) {
      console.log("Cyclic");
      break;
    }
  }
}

arr = [1,0,2];
console.log( arr );
current( arr );
proposed( arr );

arr = [1,2,3,4,5];
console.log( arr );
current( arr );
proposed( arr );

arr = [1,2,3,6,5];
console.log( arr );
current( arr );
proposed( arr );

arr=[1,2,3,4,0];
console.log( arr );
current( arr );
proposed( arr );```

Body:
I am solving this problem, a part of the problem that is giving me troubles is formulated as follows:

a. Start from index i=0;

b. Jump to index i=A[i];

c. If the current index i is outside the valid bound of [0..N-1],
print “Out” and stop;

d. Else if the current index i is index N-1, print “Done” and stop;

e1. Otherwise, repeat step b;

e2. If doing this leads to an infinite loop, print “Cyclic” and
stop;

(all output are without the quotes)

arr is an array of non-negative integers:

let index = 0;
const seen = new Set([0]);
while (true) {
  index = arr[index];
  if (index > arr.length - 1) {
    console.log("Out");
    break;
  }
  if (index === arr.length - 1) {
    console.log("Done");
    break;
  }
  if (seen.has(index)) {
    console.log("Cyclic");
    break;
  }
  seen.add(index);
}

I am getting WA (Wrong Answer) on some hidden test cases, but I can't for the life of me come up with a failing test case.

1 2 3 4 5 0 -> Done

1 2 3 4 6 0 -> Out

1 0 0 -> Cyclic

Edit:

My C++ solution has exactly the same failed test cases, must really be something with my logic...

Body:
I believe the issue is that the coded algorithm is not adhering to the requirement.  Specifically e1 indicates to repeat step b which fetches the next value, and **if doing this** leads to an infinite loop then print "Cycle".  The problem is that the code is actually doing it, rather than checking first...

So, as the current code is written, a test case of...

12344

...will return "Done" rather than "Cyclic"...

EDIT In the parlance code, this is what I'm suggesting (untested)...

let index = 0;
const seen = new Set([0]);
while (true) {
  index = arr[index];
  if (index > arr.length - 1) {
    console.log("Out");
    break;
  }
  if (index === arr.length - 1) {
    console.log("Done");
    break;
  }
  if (seen.has(index) || seen.has(arr[index])) {
    console.log("Cyclic");
    break;
  }
  seen.add(index);
}

EDIT #2
Upon getting a chance to test my previously untested code just above, I discovered that it did not capture the nuance of my point.  So, in an effort to further clarify, below is the Current and Proposed algorithms, with sample cases to show the similarities and the difference.

The last case, where the cyclic entry is the final entry, is where step e2 reports "Cyclic" before step c is able to report "Done"...

Comments in the proposed() function show the steps of the algorithm...

function current( arr ) {
  let index = 0;
  const seen = new Set([0]);
  while (true) {
    index = arr[index];
    if (index > arr.length - 1) {
      console.log("Out");
      break;
    }
    if (index === arr.length - 1) {
      console.log("Done");
      break;
    }
    if (seen.has(index)) {
      console.log("Cyclic");
      break;
    }
    seen.add(index);
  }
}

function proposed( arr ) {
  // a. Start from index i=0;
  let index = 0;

  // b. Jump to index i=A[i];
  const seen = new Set( [ index ] );
  index = arr[ index ];

  while( true ) {
    // c. If the current index i is outside the valid bound of [0..N-1], print “Out” and stop;
    if ( index > arr.length - 1 ) {
      console.log( "Out" );
      break;
    }

    // d. Else if the current index i is index N-1, print “Done” and stop;
    if ( index === arr.length - 1 ) {
      console.log( "Done" );
      break;
    }

    // e1. Otherwise, repeat step b;
    seen.add( index );
    index = arr[ index ];

    // e2. If doing this leads to an infinite loop, print “Cyclic” and stop;
    if ( seen.has( arr[index] ) ) {
      console.log("Cyclic");
      break;
    }
  }
}

arr = [1,0,2];
console.log( arr );
current( arr );
proposed( arr );

arr = [1,2,3,4,5];
console.log( arr );
current( arr );
proposed( arr );

arr = [1,2,3,6,5];
console.log( arr );
current( arr );
proposed( arr );

arr=[1,2,3,4,0];
console.log( arr );
current( arr );
proposed( arr );


问:
Flutter.io Android License Status Unknown
```<code>>[!] Android toolchain - develop for Android devices (Android SDK 27.0.3)
    >>• Android SDK a ..\Android\sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-27, build-tools 27.0.3
    • Java binary at C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b02)
    X Android license status unknown.
</code>```

I am getting an error with Android SDK when I run Flutter doctor, although I can still build/run it on my device. I was just curious about how to fix this issue. I believe I have the most updated version of the Android SDK downloaded, not sure what happened because I didn't have this issue last week.

##New Issues
After following several possible fixes in the comments it has led to a new problem. I installed newer versions of android sdk P, 8, and 7 along with a new jdk10. Still not updated enough apparently.

```<code>C:\Flutter\flutter>flutter doctor --android-licenses
A newer version of the Android SDK is required. To update, run:
C:\Users\tdmil\AppData\Local\Android\sdk\tools\bin\sdkmanager --update
</code>```

C:\Flutter\flutter>C:\users\username\appdata\local\android\sdk\tools\bin\sdkmanager.bat --update

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
        at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
        at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
        at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
        at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
        at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
        ... 5 more
</code>```

答:
In linux:20.10
Please make sure you set up the path for ANDROID_HOME, ANDROID_SDK_ROOT link

I have to update newest cmdline-tools:

```<code>path/to/sdkmanager --install "cmdline-tools;latest"
</code>```

to get your path/to/sdkmanager run :

```<code>which sdkmanager
</code>```

and then I can run :

```<code>flutter doctor --android-licenses
</code>```

Body:
>[!] Android toolchain - develop for Android devices (Android SDK 27.0.3)
    >>• Android SDK a ..\Android\sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-27, build-tools 27.0.3
    • Java binary at C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b02)
    X Android license status unknown.

I am getting an error with Android SDK when I run Flutter doctor, although I can still build/run it on my device. I was just curious about how to fix this issue. I believe I have the most updated version of the Android SDK downloaded, not sure what happened because I didn't have this issue last week.

##New Issues
After following several possible fixes in the comments it has led to a new problem. I installed newer versions of android sdk P, 8, and 7 along with a new jdk10. Still not updated enough apparently.

C:\Flutter\flutter>flutter doctor --android-licenses
A newer version of the Android SDK is required. To update, run:
C:\Users\tdmil\AppData\Local\Android\sdk\tools\bin\sdkmanager --update

C:\Flutter\flutter>C:\users\username\appdata\local\android\sdk\tools\bin\sdkmanager.bat --update

Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
        at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
        at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
        at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
        at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
        at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
        ... 5 more

Body:
In linux:20.10
Please make sure you set up the path for ANDROID_HOME, ANDROID_SDK_ROOT link

I have to update newest cmdline-tools:

path/to/sdkmanager --install "cmdline-tools;latest"

to get your path/to/sdkmanager run :

which sdkmanager

and then I can run :

flutter doctor --android-licenses


问:
Why does my pygame only display the first frame and not render the updates?
I'm trying to get a a set number of blocks move around on the screen and have collision
however it only draws the very first position of the blocks and doesn't draw any of the later frames, that is the acutal movement of the blocks

here is my code

https://github.com/Zippzy/pygame-testing

please help

答:
This part here is wrong. move returns a new, moved rect. You want to move the rectangles in place, which is move_ip.
So change

```<code>for i in objects:
    i.Rect.move(i.speed)
</code>```

to

```<code>for i in objects:
    i.Rect.move_ip(i.speed)
</code>```

Body:
This part here is wrong. move returns a new, moved rect. You want to move the rectangles in place, which is move_ip.
So change

for i in objects:
    i.Rect.move(i.speed)

to

for i in objects:
    i.Rect.move_ip(i.speed)


问:
How do I create a leaderboard from the stats in my Firebase Realtime Database?
I want to create a leaderboard in my app. The leaderboard should show the 10 best users who have the most high scores. My Firebase database looks like this:

Firebase Database:

I have already created an activity with 10 TextViews one below the other. Starting with the first TextView I want to change the text to:

"1st place | 'username' | 'highscore' score"

Now my question:

What is the easiest way for me to do this?

答:
To get the top 10 users with the highest score, you can use a query like this:

```<code>DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("Users");
Query top10Query = usersRef.orderByChild("highscore").limitToLast(10);
</code>```

Then read the matching data with something like this:

```<code>top10Query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
            Log.i("Firebase", userSnapshot.getKey());
            Log.i("Firebase", userSnapshot.child("highscore").getValue());
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
}
</code>```

The above will give you the top 10 scores, but in ascending order as Firebase has no option to return results in descending order. To display them in the correct order, you'll need to reverse the results in your code, or add them to the UI in the inverse order.

Body:
To get the top 10 users with the highest score, you can use a query like this:

DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("Users");
Query top10Query = usersRef.orderByChild("highscore").limitToLast(10);

Then read the matching data with something like this:

top10Query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
            Log.i("Firebase", userSnapshot.getKey());
            Log.i("Firebase", userSnapshot.child("highscore").getValue());
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
}

The above will give you the top 10 scores, but in ascending order as Firebase has no option to return results in descending order. To display them in the correct order, you'll need to reverse the results in your code, or add them to the UI in the inverse order.


问:
ShowMore Button for PHP-mySQL generated table
```<code><?php
 $nrows = mysqli_num_rows($result);
  for (;$i<$nrows;)
   {
    echo"<tr>";
    for ($j=0;$j<10&&$i<=$nrows;$j++)
    {
    $n = $i;
    $i=$i + 1;
    $k=$n%30;
    $row = mysqli_fetch_assoc($result);
    extract($row);
    echo "<td><table  width='100%' id=$Code>
                    <tr><td>$Code</td></tr>
                    <tr><td>$Name</td></tr>
                </table></td>";
    if ($k==0)break 2;

 }
 echo"</tr>";
}
?>
</code>```

This is simple code for a sample table that i am working on. It being called in external file with $nrows and $i defined produces 10*3 table of 30 results. And called twice 60 results and so on.

I wish to add a showmore button to call this file. I worked around with div and ajax

I got pagination script and tried to work with it and added this button to it. and tried to get next page with ajax.

```<code>if ($currentpage != $totalpages) {
echo"<p><div id='more'><input name='ShowMore' type='button' id='$nextpage' onclick='showmore(this.id)'  value='ShowMore' /></div></p>";}
</code>```

The problem with this button is that it work good just First page is there while after that for every click next page appears but in place of other page.

I know problem is with div id which is constant. Is there any way to change it everytime one click on showmore.
I am also this thinking to work with mysql limit but unable to find a way to pass it to next table.

Any sort of help is welcome.
Thanx in Advance.

答: Could you make a javascript onClick function that alters the div's id and put it on the show more link?</p>

Body:
<?php
 $nrows = mysqli_num_rows($result);
  for (;$i<$nrows;)
   {
    echo"
";
    for ($j=0;$j<10&&$i<=$nrows;$j++)
    {
    $n = $i;
    $i=$i + 1;
    $k=$n%30;
    $row = mysqli_fetch_assoc($result);
    extract($row);
    echo "

$Code

$Name

	";
    if ($k==0)break 2;

 }
 echo"
";
}
?>

This is simple code for a sample table that i am working on. It being called in external file with $nrows and $i defined produces 10*3 table of 30 results. And called twice 60 results and so on.

I wish to add a showmore button to call this file. I worked around with div and ajax

I got pagination script and tried to work with it and added this button to it. and tried to get next page with ajax.

if ($currentpage != $totalpages) {
echo"

<input name='ShowMore' type='button' id='$nextpage' onclick='showmore(this.id)'  value='ShowMore' />

";}

The problem with this button is that it work good just First page is there while after that for every click next page appears but in place of other page.

I know problem is with div id which is constant. Is there any way to change it everytime one click on showmore.
I am also this thinking to work with mysql limit but unable to find a way to pass it to next table.

Any sort of help is welcome.
Thanx in Advance.


问:
Test if file exists in a GN meta-build
GN Reference about inputs for actions:

For action and action_foreach targets, inputs should be the inputs to script
that don't vary. These should be all .py files that the script uses via
imports (the main script itself will be an implicit dependency of the action
so need not be listed).

For action targets, inputs and sources are treated the same, but from a style
perspective, it's recommended to follow the same rule as action_foreach and
put helper files in the inputs, and the data used by the script (if any) in
sources.

Note that another way to declare input dependencies from an action is to have
the action write a depfile (see "gn help depfile"). This allows the script to
dynamically write input dependencies, that might not be known until actually
executing the script. This is more efficient than doing processing while
running GN to determine the inputs, and is easier to keep in-sync than
hardcoding the list.

In my case one of inputs is optional, so I want to add it to the list only if it exists. I don't see a way to test for this in GN itself. I can use depfiles, but is this the only option?

答:
Build args are one solution, if whatever's invoking GN "knows" whether the optional input file is present:

BUILD.gn:

```<code>declare_args() {
  have_some_optional_input_file = false
}

action("my_action") {
  inputs = [ ... ] # list of your required inputs
  if (have_some_optional_input_file) {
    inputs += [ "my_optional_input.whatever" ]
  }
  ...
}
</code>```

If it's truly unknowable, there's always the exec_script "escape hatch": https://gn.googlesource.com/gn/+/master/docs/reference.md#func_exec_script

This lets you run an arbitrary script at configuration time, and GN will parse the output as if you'd written it in the BUILd.gn file directly.

Since GN needs to know your exact inputs for every build, you could do something like this:

BUILD.gn:

```<code>action("my_action") {
  inputs = [ ... ] + exec_script("find_optional_inputs.py", [], "list lines")
}
</code>```

Write your find_optional_inputs.py such that it returns a newline-delimited list of all files you want it to add to the input set.

Be careful, though, your exec_script statements will run every time you invoke GN, even if it's just for a non-mutating subcommand like desc or ls. Additionally, if your script is in a template, it will run once per instantiation. Your script will also run once per toolchain where it is referenced. You can add the --time argument to GN itself to see how long it takes, so at least you can keep an eye on it!

Title: Test if file exists in a GN meta-build

Body:
Build args are one solution, if whatever's invoking GN "knows" whether the optional input file is present:

BUILD.gn:

declare_args() {
  have_some_optional_input_file = false
}

action("my_action") {
  inputs = [ ... ] # list of your required inputs
  if (have_some_optional_input_file) {
    inputs += [ "my_optional_input.whatever" ]
  }
  ...
}

If it's truly unknowable, there's always the exec_script "escape hatch": https://gn.googlesource.com/gn/+/master/docs/reference.md#func_exec_script

This lets you run an arbitrary script at configuration time, and GN will parse the output as if you'd written it in the BUILd.gn file directly.

Since GN needs to know your exact inputs for every build, you could do something like this:

BUILD.gn:

action("my_action") {
  inputs = [ ... ] + exec_script("find_optional_inputs.py", [], "list lines")
}

Write your find_optional_inputs.py such that it returns a newline-delimited list of all files you want it to add to the input set.

Be careful, though, your exec_script statements will run every time you invoke GN, even if it's just for a non-mutating subcommand like desc or ls. Additionally, if your script is in a template, it will run once per instantiation. Your script will also run once per toolchain where it is referenced. You can add the --time argument to GN itself to see how long it takes, so at least you can keep an eye on it!


问:
Can't install Jekyll on Mint
I installed ruby and ruby gems, updated both of them, tried to install jekyll using the command

```<code>sudo gem install jekyll bundler
</code>```

it gave me this

```<code>Building native extensions.  This could take a while...
ERROR:  Error installing jekyll:
    ERROR: Failed to build gem native extension.

    current directory: /var/lib/gems/2.3.0/gems/ffi-1.9.14/ext/ffi_c
/usr/bin/ruby2.3 -r ./siteconf20161209-4826-wdshax.rb extconf.rb
checking for ffi.h... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/usr/bin/$(RUBY_BASE_NAME)2.3
    --with-ffi_c-dir
    --without-ffi_c-dir
    --with-ffi_c-include
    --without-ffi_c-include=${ffi_c-dir}/include
    --with-ffi_c-lib
    --without-ffi_c-lib=${ffi_c-dir}/lib
    --with-libffi-config
    --without-libffi-config
    --with-pkg-config
    --without-pkg-config
/usr/lib/ruby/2.3.0/mkmf.rb:456:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
You have to install development tools first.
    from /usr/lib/ruby/2.3.0/mkmf.rb:587:in `try_cpp'
    from /usr/lib/ruby/2.3.0/mkmf.rb:1091:in `block in have_header'
    from /usr/lib/ruby/2.3.0/mkmf.rb:942:in `block in checking_for'
    from /usr/lib/ruby/2.3.0/mkmf.rb:350:in `block (2 levels) in postpone'
    from /usr/lib/ruby/2.3.0/mkmf.rb:320:in `open'
    from /usr/lib/ruby/2.3.0/mkmf.rb:350:in `block in postpone'
    from /usr/lib/ruby/2.3.0/mkmf.rb:320:in `open'
    from /usr/lib/ruby/2.3.0/mkmf.rb:346:in `postpone'
    from /usr/lib/ruby/2.3.0/mkmf.rb:941:in `checking_for'
    from /usr/lib/ruby/2.3.0/mkmf.rb:1090:in `have_header'
    from extconf.rb:16:in `<main>'

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/ffi-1.9.14/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.3.0/gems/ffi-1.9.14 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/ffi-1.9.14/gem_make.out
Successfully installed bundler-1.13.6
Parsing documentation for bundler-1.13.6
Done installing documentation for bundler after 7 seconds
1 gem installed
</code>```

Here is what it says in the log file:

```<code>package configuration for libffi is not found
"gcc -o conftest -I/usr/include/x86_64-linux-gnu/ruby-2.3.0 -I/usr/include/ruby-2.3.0/ruby/backward -I/usr/include/ruby-2.3.0 -I. -Wdate-time -D_FORTIFY_SOURCE=2   -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -fPIC conftest.c  -L. -L/usr/lib/x86_64-linux-gnu -L. -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -fstack-protector -rdynamic -Wl,-export-dynamic     -lruby-2.3  -lpthread -lgmp -ldl -lcrypt -lm   -lc"
In file included from /usr/include/ruby-2.3.0/ruby/ruby.h:36:0,
                 from /usr/include/ruby-2.3.0/ruby.h:33,
                 from conftest.c:1:
/usr/include/ruby-2.3.0/ruby/defines.h:26:19: fatal error: stdio.h: No such file or directory
compilation terminated.
checked program was:
/* begin */
1: #include "ruby.h"
2:
3: int main(int argc, char **argv)
4: {
5:   return 0;
6: }
/* end */
</code>```

I'm running Linux Mint, and I can't find anything to help this problem. One gem of jekyll is installed and I'm able to create jekyll projects, but only partially and I can't run it on my local host and edit it.

Any more questions let me know and I'll try my best to help provide the details.

答:
I've been there. Some linux need custom treatment till get done to do something.
You can try to

bundle exec jekyll serve --trace
```

If you pass, you will find url like this: http://127.0.0.1:4000/

Title: Can't install Jekyll on Mint

Body:
I installed ruby and ruby gems, updated both of them, tried to install jekyll using the command

sudo gem install jekyll bundler

it gave me this

Building native extensions.  This could take a while...
ERROR:  Error installing jekyll:
    ERROR: Failed to build gem native extension.

    current directory: /var/lib/gems/2.3.0/gems/ffi-1.9.14/ext/ffi_c
/usr/bin/ruby2.3 -r ./siteconf20161209-4826-wdshax.rb extconf.rb
checking for ffi.h... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/usr/bin/$(RUBY_BASE_NAME)2.3
    --with-ffi_c-dir
    --without-ffi_c-dir
    --with-ffi_c-include
    --without-ffi_c-include=${ffi_c-dir}/include
    --with-ffi_c-lib
    --without-ffi_c-lib=${ffi_c-dir}/lib
    --with-libffi-config
    --without-libffi-config
    --with-pkg-config
    --without-pkg-config
/usr/lib/ruby/2.3.0/mkmf.rb:456:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
You have to install development tools first.
    from /usr/lib/ruby/2.3.0/mkmf.rb:587:in `try_cpp'
    from /usr/lib/ruby/2.3.0/mkmf.rb:1091:in `block in have_header'
    from /usr/lib/ruby/2.3.0/mkmf.rb:942:in `block in checking_for'
    from /usr/lib/ruby/2.3.0/mkmf.rb:350:in `block (2 levels) in postpone'
    from /usr/lib/ruby/2.3.0/mkmf.rb:320:in `open'
    from /usr/lib/ruby/2.3.0/mkmf.rb:350:in `block in postpone'
    from /usr/lib/ruby/2.3.0/mkmf.rb:320:in `open'
    from /usr/lib/ruby/2.3.0/mkmf.rb:346:in `postpone'
    from /usr/lib/ruby/2.3.0/mkmf.rb:941:in `checking_for'
    from /usr/lib/ruby/2.3.0/mkmf.rb:1090:in `have_header'
    from extconf.rb:16:in `'

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/ffi-1.9.14/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.3.0/gems/ffi-1.9.14 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/ffi-1.9.14/gem_make.out
Successfully installed bundler-1.13.6
Parsing documentation for bundler-1.13.6
Done installing documentation for bundler after 7 seconds
1 gem installed

Here is what it says in the log file:

package configuration for libffi is not found
"gcc -o conftest -I/usr/include/x86_64-linux-gnu/ruby-2.3.0 -I/usr/include/ruby-2.3.0/ruby/backward -I/usr/include/ruby-2.3.0 -I. -Wdate-time -D_FORTIFY_SOURCE=2   -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -fPIC conftest.c  -L. -L/usr/lib/x86_64-linux-gnu -L. -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -fstack-protector -rdynamic -Wl,-export-dynamic     -lruby-2.3  -lpthread -lgmp -ldl -lcrypt -lm   -lc"
In file included from /usr/include/ruby-2.3.0/ruby/ruby.h:36:0,
                 from /usr/include/ruby-2.3.0/ruby.h:33,
                 from conftest.c:1:
/usr/include/ruby-2.3.0/ruby/defines.h:26:19: fatal error: stdio.h: No such file or directory
compilation terminated.
checked program was:
/* begin */
1: #include "ruby.h"
2:
3: int main(int argc, char **argv)
4: {
5:   return 0;
6: }
/* end */

I'm running Linux Mint, and I can't find anything to help this problem. One gem of jekyll is installed and I'm able to create jekyll projects, but only partially and I can't run it on my local host and edit it.

Any more questions let me know and I'll try my best to help provide the details.

Body:
I've been there. Some linux need custom treatment till get done to do something.
You can try to

bundle exec jekyll serve --trace

If you pass, you will find url like this: http://127.0.0.1:4000/


问:
How does one insert statistical annotations (e.g. p-values) into a seaborn figure-level plot (e.g. catplot)?
Goal: Given a seaborn catplot (kind="bar") with multiple rows, grouped bars, and a mapped stripplot, how do I add statistical annotations (p-values).

The following code from @Trenton McKinney generates my figure without statistical annotation. I would like to insert statistical annotation into this figure:

```<code>import seaborn as sns

tips = sns.load_dataset("tips")

g = sns.catplot(x="sex", y="total_bill", hue="smoker", row="time", data=tips, kind="bar", ci = "sd",
    edgecolor="black", errcolor="black", errwidth=1.5, capsize = 0.1, height=4, aspect=.7,alpha=0.5)

g.map(sns.stripplot, 'sex', 'total_bill', 'smoker', hue_order=['Yes', 'No'], order=['Male', 'Female'],
  palette=sns.color_palette(), dodge=True, alpha=0.6, ec='k', linewidth=1)
</code>```

What I tried: I tried to use statannotations.Annotator.Annotator.plot_and_annotate_facets(). However, I was not able to get it working properly.

I also tried to use statannotations.Annotator.Annotator.new_plot(). However, this just worked for barplots but not for catplots. This is the corresponding code based on @r-beginners:

```<code>import seaborn as sns
from statannotations.Annotator import Annotator
%matplotlib inline
import matplotlib.pyplot as plt

df = sns.load_dataset("tips")

x="sex"
y="total_bill"
hue="smoker"
hue_order=['Yes', 'No']

pairs = [
    (("Male", "Yes"), ("Male", "No")),
    (("Female", "Yes"), ("Female", "No"))]

ax = sns.barplot(data=df, x=x, y=y, hue=hue, hue_order=hue_order, seed=2021, ci="sd",
    edgecolor="black", errcolor="black", errwidth=1.5, capsize = 0.1, alpha=0.5)

sns.stripplot(x=x, y=y, hue=hue, data=df, dodge=True, alpha=0.6, ax=ax)

annot = Annotator(None, pairs)

annot.new_plot(ax, pairs, plot='barplot',
           data=df, x=x, y=y, hue=hue, hue_order=hue_order, seed=2021)
annot.configure(test='Mann-Whitney', text_format='simple', loc='inside', verbose=2)
annot.apply_test().annotate()

plt.legend(loc='upper left', bbox_to_anchor=(1.03, 1), title=hue)
</code>```

Question: Does anyone know how to insert statistical annotation into a figure-level plot, preferably a catplot (kind="bar")?

答:
I think you can just iterate over the axes in the FacetGrid and apply the Annotator element wise.

Here is a short example with your provided code:

import seaborn as sns
from statannotations.Annotator import Annotator
%matplotlib inline

tips = sns.load_dataset("tips")

args = dict(x="sex", y="total_bill", data=tips, hue="smoker", hue_order=["Yes","No"], order=['Male', 'Female'])

g = sns.catplot(edgecolor="black", errcolor="black", errwidth=1.5, capsize = 0.1, height=4, aspect=.7,alpha=0.5, kind="bar", ci = "sd", row="time", **args)
g.map(sns.stripplot, args["x"], args["y"], args["hue"], hue_order=args["hue_order"], order=args["order"], palette=sns.color_palette(), dodge=True, alpha=0.6, ec='k', linewidth=1)

pairs = [
    (("Male", "Yes"), ("Male", "No")),
    (("Female", "Yes"), ("Female", "No"))
]

for ax_n in g.axes:
    for ax in ax_n:
        annot = Annotator(ax, pairs, **args)
        annot.configure(test='Mann-Whitney', text_format='simple', loc='inside', verbose=2)
        annot.apply_test().annotate()
```

This produces the following plot:

Body:
Goal: Given a seaborn catplot (kind="bar") with multiple rows, grouped bars, and a mapped stripplot, how do I add statistical annotations (p-values).

The following code from @Trenton McKinney generates my figure without statistical annotation. I would like to insert statistical annotation into this figure:

import seaborn as sns

tips = sns.load_dataset("tips")

g = sns.catplot(x="sex", y="total_bill", hue="smoker", row="time", data=tips, kind="bar", ci = "sd",
    edgecolor="black", errcolor="black", errwidth=1.5, capsize = 0.1, height=4, aspect=.7,alpha=0.5)

g.map(sns.stripplot, 'sex', 'total_bill', 'smoker', hue_order=['Yes', 'No'], order=['Male', 'Female'],
  palette=sns.color_palette(), dodge=True, alpha=0.6, ec='k', linewidth=1)

What I tried: I tried to use statannotations.Annotator.Annotator.plot_and_annotate_facets(). However, I was not able to get it working properly.

I also tried to use statannotations.Annotator.Annotator.new_plot(). However, this just worked for barplots but not for catplots. This is the corresponding code based on @r-beginners:

import seaborn as sns
from statannotations.Annotator import Annotator
%matplotlib inline
import matplotlib.pyplot as plt

df = sns.load_dataset("tips")

x="sex"
y="total_bill"
hue="smoker"
hue_order=['Yes', 'No']

pairs = [
    (("Male", "Yes"), ("Male", "No")),
    (("Female", "Yes"), ("Female", "No"))]

ax = sns.barplot(data=df, x=x, y=y, hue=hue, hue_order=hue_order, seed=2021, ci="sd",
    edgecolor="black", errcolor="black", errwidth=1.5, capsize = 0.1, alpha=0.5)

sns.stripplot(x=x, y=y, hue=hue, data=df, dodge=True, alpha=0.6, ax=ax)

annot = Annotator(None, pairs)

annot.new_plot(ax, pairs, plot='barplot',
           data=df, x=x, y=y, hue=hue, hue_order=hue_order, seed=2021)
annot.configure(test='Mann-Whitney', text_format='simple', loc='inside', verbose=2)
annot.apply_test().annotate()

plt.legend(loc='upper left', bbox_to_anchor=(1.03, 1), title=hue)

Question: Does anyone know how to insert statistical annotation into a figure-level plot, preferably a catplot (kind="bar")?

Body:
I think you can just iterate over the axes in the FacetGrid and apply the Annotator element wise.

Here is a short example with your provided code:

import seaborn as sns
from statannotations.Annotator import Annotator
%matplotlib inline

tips = sns.load_dataset("tips")

args = dict(x="sex", y="total_bill", data=tips, hue="smoker", hue_order=["Yes","No"], order=['Male', 'Female'])

g = sns.catplot(edgecolor="black", errcolor="black", errwidth=1.5, capsize = 0.1, height=4, aspect=.7,alpha=0.5, kind="bar", ci = "sd", row="time", **args)
g.map(sns.stripplot, args["x"], args["y"], args["hue"], hue_order=args["hue_order"], order=args["order"], palette=sns.color_palette(), dodge=True, alpha=0.6, ec='k', linewidth=1)

pairs = [
    (("Male", "Yes"), ("Male", "No")),
    (("Female", "Yes"), ("Female", "No"))
]

for ax_n in g.axes:
    for ax in ax_n:
        annot = Annotator(ax, pairs, **args)
        annot.configure(test='Mann-Whitney', text_format='simple', loc='inside', verbose=2)
        annot.apply_test().annotate()

This produces the following plot:


问:
angular cli : ng commands shows Invalid character error
I tried to find the version of angular cli after successful installation but it shows a Window Script Host model pop up with an error.

Installation:

Windows Script Host appears after I tried with

```<code>ng version
</code>```

答:
For anyone else running into this same issue, I had to delete the system environment variable for the Angular CLI and then restart my console window.

C:\Users\{user}\AppData\Roaming\npm\node_modules\@angular\cli\bin

Body:
I tried to find the version of angular cli after successful installation but it shows a Window Script Host model pop up with an error.

Installation:

Windows Script Host appears after I tried with

ng version


问:
count number of value per id in array
I have this script in php i want to get the number of value in the table
in below my script

```<code>$count = 0;

foreach ($info as $key => $value)
{
    foreach ($value as $c => $val)
    {
        var_dump($val) . "<br>";

        if (strcmp($val,"Tankh ") == 0)
        {
            $count++;
            //echo $count;
        }
    }

    // die();

    echo $count;
    return $count;
</code>```

var_dump the $val:

```<code>string(9) "Nomclient"
string(13) "Villeclient "
string(7) "Mohamed"
string(8) "Tankh "
string(6) "Fatima"
string(9) "Tankh "
string(6) "Brahim"
string(6) "Tankh "
string(5) "Jamal"
string(8) "Tankh "
string(5) "Ikram"
string(6) "Tankh "
string(6) "Karima"
string(5) "Rain"
</code>```

thanks in advance

答:
Perhaps you can leverage the existing function array_count_values for every $value instead of checking the individual values.

```<code>$info = [
    [
        "Nomclient", "Villeclient", "Mohamed", "Tankh", "Fatima", "Tankh", "Brahim", "Tankh", "Jamal", "Tankh", "Ikram", "Tankh", "Karima", "Rain"
    ]
];

$val_counts = array_map(function($value){
    return array_count_values($value);
}, $info);

print_r($val_counts);
</code>```

Output

```<code>Array
(
    [0] => Array
        (
            [Nomclient] => 1
            [Villeclient] => 1
            [Mohamed] => 1
            [Tankh] => 5
            [Fatima] => 1
            [Brahim] => 1
            [Jamal] => 1
            [Ikram] => 1
            [Karima] => 1
            [Rain] => 1
        )

)
</code>```

PHP demo

Title: count number of value per id in array

Body:
I have this script in php i want to get the number of value in the table
in below my script

$count = 0;

foreach ($info as $key => $value)
{
    foreach ($value as $c => $val)
    {
        var_dump($val) . "
";

        if (strcmp($val,"Tankh ") == 0)
        {
            $count++;
            //echo $count;
        }
    }

    // die();

    echo $count;
    return $count;

var_dump the $val:

string(9) "Nomclient"
string(13) "Villeclient "
string(7) "Mohamed"
string(8) "Tankh "
string(6) "Fatima"
string(9) "Tankh "
string(6) "Brahim"
string(6) "Tankh "
string(5) "Jamal"
string(8) "Tankh "
string(5) "Ikram"
string(6) "Tankh "
string(6) "Karima"
string(5) "Rain"

thanks in advance

Body:
Perhaps you can leverage the existing function array_count_values for every $value instead of checking the individual values.

$info = [
    [
        "Nomclient", "Villeclient", "Mohamed", "Tankh", "Fatima", "Tankh", "Brahim", "Tankh", "Jamal", "Tankh", "Ikram", "Tankh", "Karima", "Rain"
    ]
];

$val_counts = array_map(function($value){
    return array_count_values($value);
}, $info);

print_r($val_counts);

Output

Array
(
    [0] => Array
        (
            [Nomclient] => 1
            [Villeclient] => 1
            [Mohamed] => 1
            [Tankh] => 5
            [Fatima] => 1
            [Brahim] => 1
            [Jamal] => 1
            [Ikram] => 1
            [Karima] => 1
            [Rain] => 1
        )

)

PHP demo


问:
Microsoft Access Error 3061: Too few parameters. Expected 1
I am working on number 2 in my code. The idea here is to create a query that can archive data from one access database to another using the front end forms in access. I keep getting this error and cant figure it out. It seems to be the WHERE component in referencing my Form. The code in the prior step correctly creates the string to be inputted into the WHERE clause, and that is just a textbox on the form. The place where I got the base code from here:

https://www.everythingaccess.com/tutorials.asp?ID=Archive%3A-Move-records-to-another-table

This is the code below:

```<code>Sub DoArchive()

On Error GoTo Err_DoArchive
Dim ws As DAO.Workspace   'Current workspace (for transaction).
Dim db As DAO.Database    'Inside the transaction.
Dim bInTrans As Boolean   'Flag that transaction is active.
Dim strSql As String      'Action query statements.
Dim strMsg As String      'MsgBox message.
Dim CrdStrng As String   'Cord Code for reference
CrdStrng = [Forms]![0 - Front End - Macros-Mapping]![String_CORD]

Dim frm As Form, ctl As Control
Dim varItem As Variant
Dim strSql1 As String
Dim Delete_Txtbox As TextBox

'Step 1: Initialize database object inside a transaction.
Set ws = DBEngine(0)
ws.BeginTrans
bInTrans = True
Set db = ws(0)

Set frm = Forms("0 - Front End - Macros-Mapping")
Set ctl = frm![CORD Type Selector]
Set Delete_Txtbox = frm![String_CORD]

'Step 2: Select Types

strSql1 = "[Type]="
  'Assuming long [EmpID] is the bound field in lb
  'enumerate selected items and
  'concatenate to strSQL
  For Each varItem In ctl.ItemsSelected
      strSql1 = strSql1 & Chr(34) & ctl.ItemData(varItem) & Chr(34) & " Or [Type]="
  Next varItem

  'Trim the end of strSQL
  strSql1 = Left$(strSql1, Len(strSql1) - 11)

  Delete_Txtbox.Value = Right(strSql1, Len(strSql1) - 0)

MsgBox Delete_Txtbox.Value

'Step 3: Execute the append.
strSql = "INSERT INTO [***Master Data***]( [Operated/Non-Operated], Level2, Level3, Level4, [Underlying/Allocation], [Business  ID], [Team ID], Team_Name, businessName, BU, Category, Material, [Asset Type], Grp_Name, Account_No, Account_Desc, [Higher Level Grp_Name], [GFO View], [MI View], ActiveYear, ActiveMonth, Type, [Gross Amount], [Net Amount], [Local Currency Gross], [Sort Order], VnOFlag, [VO Probability], [Rvrs-Act-Accr], [Line Segment], Notes, [Budget Owner], [High Level Budget Owner], [Sr Level Budget Owner], [Act-MI-Fcst], [PC - CC] ) " & _
"IN ""C:\Data\Pipeline Detail\ArchiveDatabase.accdb"" " & _
"SELECT [***Detail Data Pivot Report***].[Operated/Non-Operated], [***Detail Data Pivot Report***].Level2, " & _
"[***Detail Data Pivot Report***].Level3, [***Detail Data Pivot Report***].Level4, [***Detail Data Pivot Report***].[Underlying/Allocation], " & _
"[***Detail Data Pivot Report***].[Business  ID], [***Detail Data Pivot Report***].[Team ID], [***Detail Data Pivot Report***].Team_Name, " & _
"[***Detail Data Pivot Report***].businessName, [***Detail Data Pivot Report***].BU, [***Detail Data Pivot Report***].Category, " & _
"[***Detail Data Pivot Report***].Material, [***Detail Data Pivot Report***].[Asset Type], [***Detail Data Pivot Report***].Grp_Name, " & _
"[***Detail Data Pivot Report***].Account_No, [***Detail Data Pivot Report***].Account_Desc, [***Detail Data Pivot Report***].[Higher Level Grp_Name], " & _
"[***Detail Data Pivot Report***].[GFO View], [***Detail Data Pivot Report***].[MI View], [***Detail Data Pivot Report***].ActiveYear, " & _
"[***Detail Data Pivot Report***].ActiveMonth, [***Detail Data Pivot Report***].Type, " & _
"[***Detail Data Pivot Report***].[Gross Amount], [***Detail Data Pivot Report***].[Net Amount], [***Detail Data Pivot Report***].[Local Currency Gross], " & _
"[***Detail Data Pivot Report***].[Sort Order], [***Detail Data Pivot Report***].VnOFlag, [***Detail Data Pivot Report***].[VO Probability], " & _
"[***Detail Data Pivot Report***].[Rvrs-Act-Accr], [***Detail Data Pivot Report***].[Line Segment], [***Detail Data Pivot Report***].Notes, " & _
"[***Detail Data Pivot Report***].[Budget Owner], [***Detail Data Pivot Report***].[High Level Budget Owner], " & _
"[***Detail Data Pivot Report***].[Sr Level Budget Owner] , [***Detail Data Pivot Report***].[Act-MI-Fcst], [***Detail Data Pivot Report***].[PC - CC] " & _
"FROM [***Detail Data Pivot Report***] " & _
"WHERE (CrdStrng);"
db.Execute strSql, dbFailOnError

'Step 3: Execute the append. (original code without fields entered)
'strSql = "INSERT INTO MyArchiveTable ( MyField, AnotherField, Field3 ) " & _
 '"IN ""C:\My Documents\MyArchive.mdb"" " & _
 '"SELECT SomeField, Field2, Field3 FROM MyTable WHERE (MyYesNoField = True);"
 'db.Execute strSql, dbFailOnError

'Step 4: Execute the delete.
strSql = "DELETE FROM [***Detail Data Pivot Report***] WHERE ([Forms]![0 - Front End - Macros-Mapping]![String_CORD]);"
db.Execute strSql, dbFailOnError

'Step 5: Get user confirmation to commit the change.
strMsg = "Archive " & db.RecordsAffected & " record(s)?"
If MsgBox(strMsg, vbOKCancel + vbQuestion, "Confirm") = vbOK Then
  ws.CommitTrans
  bInTrans = False
End If

Exit_DoArchive:
'Step 6: Clean up
On Error Resume Next
Set db = Nothing
If bInTrans Then   'Rollback if the transaction is active.
ws.rollback
End If
Set ws = Nothing
Exit Sub

Err_DoArchive:
MsgBox Err.Description, vbExclamation, "Archiving failed: Error " & Err.Number

Resume Exit_DoArchive

End Sub
</code>```

答:
Try with:

```<code>strSql1 = strSql1 & Chr(34) & ctl.ItemData(varItem) & Chr(34) & " Or [Type] = ''"
</code>```

or:

```<code>strSql1 = strSql1 & Chr(34) & ctl.ItemData(varItem) & Chr(34) & " Or [Type] Is Null"
</code>```

Body:
I am working on number 2 in my code. The idea here is to create a query that can archive data from one access database to another using the front end forms in access. I keep getting this error and cant figure it out. It seems to be the WHERE component in referencing my Form. The code in the prior step correctly creates the string to be inputted into the WHERE clause, and that is just a textbox on the form. The place where I got the base code from here:

https://www.everythingaccess.com/tutorials.asp?ID=Archive%3A-Move-records-to-another-table

This is the code below:

Sub DoArchive()

On Error GoTo Err_DoArchive
Dim ws As DAO.Workspace   'Current workspace (for transaction).
Dim db As DAO.Database    'Inside the transaction.
Dim bInTrans As Boolean   'Flag that transaction is active.
Dim strSql As String      'Action query statements.
Dim strMsg As String      'MsgBox message.
Dim CrdStrng As String   'Cord Code for reference
CrdStrng = [Forms]![0 - Front End - Macros-Mapping]![String_CORD]

Dim frm As Form, ctl As Control
Dim varItem As Variant
Dim strSql1 As String
Dim Delete_Txtbox As TextBox

'Step 1: Initialize database object inside a transaction.
Set ws = DBEngine(0)
ws.BeginTrans
bInTrans = True
Set db = ws(0)

Set frm = Forms("0 - Front End - Macros-Mapping")
Set ctl = frm![CORD Type Selector]
Set Delete_Txtbox = frm![String_CORD]

'Step 2: Select Types

strSql1 = "[Type]="
  'Assuming long [EmpID] is the bound field in lb
  'enumerate selected items and
  'concatenate to strSQL
  For Each varItem In ctl.ItemsSelected
      strSql1 = strSql1 & Chr(34) & ctl.ItemData(varItem) & Chr(34) & " Or [Type]="
  Next varItem

  'Trim the end of strSQL
  strSql1 = Left$(strSql1, Len(strSql1) - 11)

  Delete_Txtbox.Value = Right(strSql1, Len(strSql1) - 0)

MsgBox Delete_Txtbox.Value

'Step 3: Execute the append.
strSql = "INSERT INTO [***Master Data***]( [Operated/Non-Operated], Level2, Level3, Level4, [Underlying/Allocation], [Business  ID], [Team ID], Team_Name, businessName, BU, Category, Material, [Asset Type], Grp_Name, Account_No, Account_Desc, [Higher Level Grp_Name], [GFO View], [MI View], ActiveYear, ActiveMonth, Type, [Gross Amount], [Net Amount], [Local Currency Gross], [Sort Order], VnOFlag, [VO Probability], [Rvrs-Act-Accr], [Line Segment], Notes, [Budget Owner], [High Level Budget Owner], [Sr Level Budget Owner], [Act-MI-Fcst], [PC - CC] ) " & _
"IN ""C:\Data\Pipeline Detail\ArchiveDatabase.accdb"" " & _
"SELECT [***Detail Data Pivot Report***].[Operated/Non-Operated], [***Detail Data Pivot Report***].Level2, " & _
"[***Detail Data Pivot Report***].Level3, [***Detail Data Pivot Report***].Level4, [***Detail Data Pivot Report***].[Underlying/Allocation], " & _
"[***Detail Data Pivot Report***].[Business  ID], [***Detail Data Pivot Report***].[Team ID], [***Detail Data Pivot Report***].Team_Name, " & _
"[***Detail Data Pivot Report***].businessName, [***Detail Data Pivot Report***].BU, [***Detail Data Pivot Report***].Category, " & _
"[***Detail Data Pivot Report***].Material, [***Detail Data Pivot Report***].[Asset Type], [***Detail Data Pivot Report***].Grp_Name, " & _
"[***Detail Data Pivot Report***].Account_No, [***Detail Data Pivot Report***].Account_Desc, [***Detail Data Pivot Report***].[Higher Level Grp_Name], " & _
"[***Detail Data Pivot Report***].[GFO View], [***Detail Data Pivot Report***].[MI View], [***Detail Data Pivot Report***].ActiveYear, " & _
"[***Detail Data Pivot Report***].ActiveMonth, [***Detail Data Pivot Report***].Type, " & _
"[***Detail Data Pivot Report***].[Gross Amount], [***Detail Data Pivot Report***].[Net Amount], [***Detail Data Pivot Report***].[Local Currency Gross], " & _
"[***Detail Data Pivot Report***].[Sort Order], [***Detail Data Pivot Report***].VnOFlag, [***Detail Data Pivot Report***].[VO Probability], " & _
"[***Detail Data Pivot Report***].[Rvrs-Act-Accr], [***Detail Data Pivot Report***].[Line Segment], [***Detail Data Pivot Report***].Notes, " & _
"[***Detail Data Pivot Report***].[Budget Owner], [***Detail Data Pivot Report***].[High Level Budget Owner], " & _
"[***Detail Data Pivot Report***].[Sr Level Budget Owner] , [***Detail Data Pivot Report***].[Act-MI-Fcst], [***Detail Data Pivot Report***].[PC - CC] " & _
"FROM [***Detail Data Pivot Report***] " & _
"WHERE (CrdStrng);"
db.Execute strSql, dbFailOnError

'Step 3: Execute the append. (original code without fields entered)
'strSql = "INSERT INTO MyArchiveTable ( MyField, AnotherField, Field3 ) " & _
 '"IN ""C:\My Documents\MyArchive.mdb"" " & _
 '"SELECT SomeField, Field2, Field3 FROM MyTable WHERE (MyYesNoField = True);"
 'db.Execute strSql, dbFailOnError

'Step 4: Execute the delete.
strSql = "DELETE FROM [***Detail Data Pivot Report***] WHERE ([Forms]![0 - Front End - Macros-Mapping]![String_CORD]);"
db.Execute strSql, dbFailOnError

'Step 5: Get user confirmation to commit the change.
strMsg = "Archive " & db.RecordsAffected & " record(s)?"
If MsgBox(strMsg, vbOKCancel + vbQuestion, "Confirm") = vbOK Then
  ws.CommitTrans
  bInTrans = False
End If

Exit_DoArchive:
'Step 6: Clean up
On Error Resume Next
Set db = Nothing
If bInTrans Then   'Rollback if the transaction is active.
ws.rollback
End If
Set ws = Nothing
Exit Sub

Err_DoArchive:
MsgBox Err.Description, vbExclamation, "Archiving failed: Error " & Err.Number

Resume Exit_DoArchive

End Sub

Body:
Try with:

strSql1 = strSql1 & Chr(34) & ctl.ItemData(varItem) & Chr(34) & " Or [Type] = ''"

or:

strSql1 = strSql1 & Chr(34) & ctl.ItemData(varItem) & Chr(34) & " Or [Type] Is Null"


答:
Here is alternative solution:</p>
```<code>def filtra_ordinati(l1):
l2 = []

for i in range(0,len(l1)):
    if i == 0:
        l2.append(l1[i])
    if l1[i] > l1[i-1]:
        l2.append(l1[i])
return l2
</code>```

Title: Python exercise: lists sorting removing the nums

Body:
'Write a filter_ordered function that receives a list L1 of integers and returns a list L2 obtained starting from L1, eliminating all the elements that violate the growing order. In other words, an element of L1 must be inserted in L2 if and only if it is greater than all the elements that precede it in L1.

Example: If L1 = [1, 2, 5, 4, 7, 8, 3, 9] then filter_sorted (L1) returns the list L2 = [1, 2, 5, 7, 8, 9].'

this is my code:

def filtra_ordinati(l1):
    l2 = []
    for y in range(1,len(l1)):
        if l1[y-1] < l1[y]:
            l2.append(l1[y-1])
    return l2

L1 = [1, 2, 5, 4, 7, 8, 3, 9]
print(filtra_ordinati(L1))

but gives me this output:

[1, 2, 4, 7, 3]

what did I do wrong? (only list comprehension should be used)

Body:
Here is alternative solution:

def filtra_ordinati(l1):
l2 = []

for i in range(0,len(l1)):
    if i == 0:
        l2.append(l1[i])
    if l1[i] > l1[i-1]:
        l2.append(l1[i])
return l2


问:
Warning: Received `false` for a non-boolean attribute `border`. in react?
I. am getting below warning . I don't know where I am doing wrong .I am using style component in my demo application.

```<code>react_devtools_backend.js:4061 Warning: Received `false` for a non-boolean attribute `border`.

If you want to write it to the DOM, pass a string instead: border="false" or border={value.toString()}.

If you used to conditionally omit it with border={condition && value}, pass border={condition ? value : undefined} instead.
</code>```

I do like this . i create a component like this. I also added few console to debug. here is my debug statement

```<code> console.log('========',depth,depth === 1);
</code>```

debug statement output
======== 3 false

```<code>5MobileHeader.tsx:63 ======== 4 false
MobileHeader.tsx:63 ======== 3 false
3MobileHeader.tsx:63 ======== 4 false
</code>```

component call

<CardHeader border={depth === 1}>

component definition

```<code>interface CardHeaderProps {
  border: boolean;
}

export const CardHeader = styled(Card.Header)<CardHeaderProps>`
  background-color: transparent;
  border-radius: 0 !important;
  border: 0;
  padding: 10px 20px;

  ${props =>
    props.border &&
    css`
      border-bottom: 1px solid #dad8d8;
    `}
`;
</code>```

答:
The expression can be evaluated to boolean, try</p>
```<code>export const CardHeader = styled(Card.Header)<CardHeaderProps>`
  border-bottom: ${({hasBorder}) => hasBorder ? `1px solid #dad8d8` : `none` ;
`;
</code>```

Body:
I. am getting below warning . I don't know where I am doing wrong .I am using style component in my demo application.

react_devtools_backend.js:4061 Warning: Received `false` for a non-boolean attribute `border`.

If you want to write it to the DOM, pass a string instead: border="false" or border={value.toString()}.

If you used to conditionally omit it with border={condition && value}, pass border={condition ? value : undefined} instead.

I do like this . i create a component like this. I also added few console to debug. here is my debug statement

 console.log('========',depth,depth === 1);

debug statement output
======== 3 false

5MobileHeader.tsx:63 ======== 4 false
MobileHeader.tsx:63 ======== 3 false
3MobileHeader.tsx:63 ======== 4 false

component call

<CardHeader border={depth === 1}>

component definition

interface CardHeaderProps {
  border: boolean;
}

export const CardHeader = styled(Card.Header)<CardHeaderProps>`
  background-color: transparent;
  border-radius: 0 !important;
  border: 0;
  padding: 10px 20px;

  ${props =>
    props.border &&
    css`
      border-bottom: 1px solid #dad8d8;
    `}
`;

Body:
The expression can be evaluated to boolean, try

export const CardHeader = styled(Card.Header)<CardHeaderProps>`
  border-bottom: ${({hasBorder}) => hasBorder ? `1px solid #dad8d8` : `none` ;
`;


问:
SQL schema design question around relating 2 different types of ID's to one piece of information
I'm working on redesigning some parts of our schema, and I'm running into a problem where I just don't know a good clean way of doing something.  I have an event table such as:

```<code>Events
--------
event_id
</code>```

for each event, there could be n groups or users associated with it.  So there's a table relating Events to Users to reflect that one to many relationship such as:

```<code>EventUsers
----------
event_id
user_id
</code>```

The problem is that we also have a concept of groups.  We want to potentially tie n groups to an event in addition to users.  So, that user_id column isn't sufficient, because we need to store potentially either a user_id or a group_id.

I've thought of a variety of ways to handle this, but they all seem like a big hack.  For example, I could make that a participant_id and put in a participant_type column such as:

```<code>EventUsers
----------
event_id
participant_id
participant_type
</code>```

and if I wanted to get the events that user_id 10 was a part of, it could be something like:

```<code>select event_id
from EventUsers
where participant_id = 10
and participant_type = 1
</code>```

(assuming that somewhere participant_type 1 was defined to be a User).  But I don't like that from a philosophical point of view because when I look at the data, I don't know what the number in participant_id means unless I also look at the value in particpant_type.

I could also change EventUsers to be something like:

```<code>EventParticipants
-----------------
event_id
user_id
group_id
</code>```

and allow the values of user_id and group_id to be NULL if that record is dealing with the other type of information.

Of course, I could just break EventUsers and we'll call it EventGroups into 2 different tables but I'd like to keep who is tied to an event stored in one single place if there's a good logical way to do it.

So, am I overlooking a good way to accomplish this?

答:
There's no correct answer to this question (although I'm sure if you look hard enough you'll finds some purists that believe that their approach is the correct one).

Personally, I'm a fan of the second approach because it allows you to give columns names that accurately reflect the data they contain. This makes your SELECT statements (in particular when it comes to joining) a bit easier to understand. Yeah, you'll end up with a bunch of NULL values in the column that is unused, but that's not really a big deal.

However, if you'll be joining on this table a lot, it might be wise to go with the first approach, so that the column you join on is consistently the same. Also, if you anticipate new types of participant being added in the future, which would result in a third column in EventParticipants, then you might want to go with the first approach to keep the table narrow.

Body:
I'm working on redesigning some parts of our schema, and I'm running into a problem where I just don't know a good clean way of doing something.  I have an event table such as:

Events
--------
event_id

for each event, there could be n groups or users associated with it.  So there's a table relating Events to Users to reflect that one to many relationship such as:

EventUsers
----------
event_id
user_id

The problem is that we also have a concept of groups.  We want to potentially tie n groups to an event in addition to users.  So, that user_id column isn't sufficient, because we need to store potentially either a user_id or a group_id.

I've thought of a variety of ways to handle this, but they all seem like a big hack.  For example, I could make that a participant_id and put in a participant_type column such as:

EventUsers
----------
event_id
participant_id
participant_type

and if I wanted to get the events that user_id 10 was a part of, it could be something like:

select event_id
from EventUsers
where participant_id = 10
and participant_type = 1

(assuming that somewhere participant_type 1 was defined to be a User).  But I don't like that from a philosophical point of view because when I look at the data, I don't know what the number in participant_id means unless I also look at the value in particpant_type.

I could also change EventUsers to be something like:

EventParticipants
-----------------
event_id
user_id
group_id

and allow the values of user_id and group_id to be NULL if that record is dealing with the other type of information.

Of course, I could just break EventUsers and we'll call it EventGroups into 2 different tables but I'd like to keep who is tied to an event stored in one single place if there's a good logical way to do it.

So, am I overlooking a good way to accomplish this?


问:
Find No of Rows Having Value less than the value of present row
Imagine I have A table that looks like this:

id
value

1
2

2
4

3
1

4
0

5
0.2

I need to update the count_less_than column as the no of rows which have less value than current row value.

Output table would be like this:

id
value
count_less_than

1
2
3

2
4
4

3
1
2

4
0
0

5
0.2
1

what would be query???

答:
You can use a correlated sub-query:</p>
```<code>select *, (select Count(*) from t t2 where t2.value < t.value ) Count_Less_Than
from t;
</code>```

Body:
You can use a correlated sub-query:

select *, (select Count(*) from t t2 where t2.value < t.value ) Count_Less_Than
from t;


问:
Check for duplicates in a shopping cart and updating the quantity (ReactJS)
I have a shopping cart that is a nested list. I want to check if a certain item is already in the list before adding it again. If it is already in the list I just want to update the quantity. What am I doing wrong here, and how can I implement localstorage here (hypothetically)

Here is the function:

```<code>   function addToCart(e) {
    var updatedCart = [];
    if (cart.includes(e.target.innerText)) {
    console.log("Duplicate found");
    for (var i = 0; i < cart.length; i++) {
        if (cart[i][0] == e.target.innerText) {
        cart[i][1]++;
        updatedCart.push(cart[i]);
        i++;
        } else {
        i++;
        }
    }
    } else {
    setCart((cart) => [...cart, [e.target.innerText, 1]]);
    }
}
</code>```

答:
Or basically, just use a Map. Helps in performance optimisations as well.
Your cart structure would be like this:

```<code>{
  productId1:quantity1,
  productId2:quantity2,
  ...
  ..
}
</code>```

A small snippet :

```<code>      let map = new Map(state.cart);
      let qty = (map.get(id) || 0) + quantity; //if item is not present will just add the item, else update its quantity
      if (qty !== 0) {
        map.set(id, qty);
      } else {
        map.delete(id); //else delete the item from cart
      }
</code>```

Body:
I have a shopping cart that is a nested list. I want to check if a certain item is already in the list before adding it again. If it is already in the list I just want to update the quantity. What am I doing wrong here, and how can I implement localstorage here (hypothetically)

Here is the function:

   function addToCart(e) {
    var updatedCart = [];
    if (cart.includes(e.target.innerText)) {
    console.log("Duplicate found");
    for (var i = 0; i < cart.length; i++) {
        if (cart[i][0] == e.target.innerText) {
        cart[i][1]++;
        updatedCart.push(cart[i]);
        i++;
        } else {
        i++;
        }
    }
    } else {
    setCart((cart) => [...cart, [e.target.innerText, 1]]);
    }
}

Body:
Or basically, just use a Map. Helps in performance optimisations as well.
Your cart structure would be like this:

{
  productId1:quantity1,
  productId2:quantity2,
  ...
  ..
}

A small snippet :

      let map = new Map(state.cart);
      let qty = (map.get(id) || 0) + quantity; //if item is not present will just add the item, else update its quantity
      if (qty !== 0) {
        map.set(id, qty);
      } else {
        map.delete(id); //else delete the item from cart
      }


问:
Can't connect to MongoDB container from other Docker container
I have two containers linked together by Docker compose and I can successfully ping the container containing MongoDB from the one containing my node.js app using the hostname. However, when it comes to actually connecting to the database, node.js tells me the connection is refused. I am using Docker for Mac if that helps.

```<code>
    mongoose.connect("mongodb://mongo", {server: {auto_reconnect: true}}).catch(error => {
            console.log("DB CONNECTION ERROR");
            console.log(error)
        });

</code>
```

Here is my docker-compose.yml file:

```
    version: "3"

    services:
      mongo:
        image: mongo:latest
        volumes:
          - ./db:/data/db
        restart: always
        expose:
          - 27017
        ports:
          - 27017:27017
        container_name: mongo

      goose:
        depends_on:
          - mongo
        build: .
        volumes:
          - ./app/server/templates:/usr/src/app/app/server/templates
        expose:
          - 3005
        restart: always
        ports:
          - 3005:3005
        container_name: goose-compose

```

答:
Well i had a similar problem so all i had to do is creating a network in my docker-compose file

```<code>version: "3.7"

services:

  db:
    image: mongo:latest
    restart: always
    container_name: db
    ports:
      - "27018:27018"
    environment:
      MONGO_INITDB_DATABASE: db
    volumes:
      - db:/data/db
    networks:
      - container-network

  app:
    image: scruc43r/app:dev
    build:
      context: .
      target: dev
    container_name: app
    restart: always
    volumes:
      - .:/app
    ports:
      - "5000:5000"
      - "3000:3000"
    depends_on:
      - db
    environment:
      - MONGODB_URI=mongodb://db/db
    networks:
      - container-network

volumes:
  db:
    name: db

networks:
  container-network:
    name: container-network
    driver: bridge
</code>```

in your config file you access the connection using

```<code>const Db_URI = process.env.MONGO_URI || "mongodb://localhost:27018/db"
const ConnectionOptions = {

    autoIndex: true,
    autoCreate: true,
    useNewUrlParser: true,
    useUnifiedTopology: true,
}
</code>```

then in your main file you can connect

```<code>await mongoose.connect (Db_URI, ConnectionOptions)
.then(()=>{
console.log('DB Connectin Established Successfully');
})
.catch(err=>{
console.log(err);
})
</code>```

Body:
I have two containers linked together by Docker compose and I can successfully ping the container containing MongoDB from the one containing my node.js app using the hostname. However, when it comes to actually connecting to the database, node.js tells me the connection is refused. I am using Docker for Mac if that helps.

    mongoose.connect("mongodb://mongo", {server: {auto_reconnect: true}}).catch(error => {
            console.log("DB CONNECTION ERROR");
            console.log(error)
        });

Here is my docker-compose.yml file:

    version: "3"

    services:
      mongo:
        image: mongo:latest
        volumes:
          - ./db:/data/db
        restart: always
        expose:
          - 27017
        ports:
          - 27017:27017
        container_name: mongo

      goose:
        depends_on:
          - mongo
        build: .
        volumes:
          - ./app/server/templates:/usr/src/app/app/server/templates
        expose:
          - 3005
        restart: always
        ports:
          - 3005:3005
        container_name: goose-compose

Body:
Well i had a similar problem so all i had to do is creating a network in my docker-compose file

version: "3.7"

services:

  db:
    image: mongo:latest
    restart: always
    container_name: db
    ports:
      - "27018:27018"
    environment:
      MONGO_INITDB_DATABASE: db
    volumes:
      - db:/data/db
    networks:
      - container-network

  app:
    image: scruc43r/app:dev
    build:
      context: .
      target: dev
    container_name: app
    restart: always
    volumes:
      - .:/app
    ports:
      - "5000:5000"
      - "3000:3000"
    depends_on:
      - db
    environment:
      - MONGODB_URI=mongodb://db/db
    networks:
      - container-network

volumes:
  db:
    name: db

networks:
  container-network:
    name: container-network
    driver: bridge

in your config file you access the connection using

const Db_URI = process.env.MONGO_URI || "mongodb://localhost:27018/db"
const ConnectionOptions = {

    autoIndex: true,
    autoCreate: true,
    useNewUrlParser: true,
    useUnifiedTopology: true,
}

then in your main file you can connect

await mongoose.connect (Db_URI, ConnectionOptions)
.then(()=>{
console.log('DB Connectin Established Successfully');
})
.catch(err=>{
console.log(err);
})


问:
Deleting (12) from Df
I have a bigger df with several columns having values like: 12(1).

df.dtypes shows these columns are objects. I tried

df['Age'] = df['Age'].str.strip()

with out success. Added a code down low but it does not work when I add ()......
Any idea what I could do to change the values in the columns?

```<code>data = {'Name':['Tom', 'Nick', 'Krish', 'Jack'],
        'Age':['20 (1)', '21 (3)', '19 (2)', '18 (1)']}
df = pd.DataFrame(data)
</code>```

答:
Use replace. Unlike to str.replace, replace apply modifications in all columns.

```<code>>>> df.replace('\s*\(.*\)$', '', regex=True)
    Name Age
0    Tom  20
1   Nick  21
2  Krish  19
3   Jack  18
</code>```

Title: Deleting (12) from Df

Body:
I have a bigger df with several columns having values like: 12(1).

df.dtypes shows these columns are objects. I tried

df['Age'] = df['Age'].str.strip()

with out success. Added a code down low but it does not work when I add ()......
Any idea what I could do to change the values in the columns?

data = {'Name':['Tom', 'Nick', 'Krish', 'Jack'],
        'Age':['20 (1)', '21 (3)', '19 (2)', '18 (1)']}
df = pd.DataFrame(data)

Body:
Use replace. Unlike to str.replace, replace apply modifications in all columns.

>>> df.replace('\s*\(.*\)$', '', regex=True)
    Name Age
0    Tom  20
1   Nick  21
2  Krish  19
3   Jack  18


答:
You can use regular expressions to do so.

```<code>patter = r"\(\d+\)"
df["Age"] = df["Age"].str.replace(patter, "", regex=True).astype(int)

</code>```

The pattern variable matches any number of digits inside parentheses. Then you replace it with empty string. Finally, you convert it to an integer.

Title: Deleting (12) from Df

Body:
You can use regular expressions to do so.

patter = r"\(\d+\)"
df["Age"] = df["Age"].str.replace(patter, "", regex=True).astype(int)

The pattern variable matches any number of digits inside parentheses. Then you replace it with empty string. Finally, you convert it to an integer.


问:
I want to start using Rails 3 and Ruby 1.9 but how can I still run my Rails 2 apps?
I have some production Rails 2 apps. I want to start using Rails 3 and Ruby 1.9 for new apps I develop.

I'm using Passenger and Apache with REE (Ruby 1.8.7). I don't vendor anything -- I install gems on the system level and specify versions per app in environment.rb.

If understand it right, the problem is not so much the Rails and other gem versions (because each app can specify their own in environment.rb), but whether my Rails 2 apps and their gems will run under Ruby 1.9.

Do I have that right?

Based on Googling it appears that there may actually be a problem with some gems like Searchlogic and Ruby 1.9.

If so what would be the recommended solution?

I have looked into RVM and it looks fantastic for testing, experimentation, and development. But it doesn't look like it was designed help with a production setup.

As I understand it, when you install Passenger you compile it against one particular version of Ruby. That Ruby can be under RVM no problem, but Passenger can't use different Rubies for different apps.

答:
Look into RVM (Ruby Version Manager).  You can manage multiple ruby versions on the same box, and multiple gemsets for each.

http://beginrescueend.com/

Additionally, Bundler allows projects to maintain their own libraries of gems (and for me at least, obviates the need for using RVM gemsets)

http://gembundler.com/

Check the following link for Hongli Lai from Phusion explaining how to set up Passenger running on multiple versions of Ruby simultaneously by using Passenger standalone and reverse proxy.

http://blog.phusion.nl/2010/09/21/phusion-passenger-running-multiple-ruby-versions/


问:
Mapping Redux Store Data to FrontEnd
I'm looking to map a store I have to the frontend. Please see below:

When a user searches, it makes a request and dispatches and action. E.g if I look up 'Data', I get data for all jobs with Data in the title.

https://gyazo.com/e8c086fa6c929c70863abb4551127d21

As you can see in the store, I have an action and I have in my store the following: job search, which fetches roles. I'd like to map these roles out by title to the front end section.

Please see my code below:

```<code>export function SearchBarTrialRedux(props) {

    const [isExpanded, setExpanded] = useState(false);
    const [parentRef, isClickedOutside ] = useClickOutside();
    const inputRef = useRef();
    const [searchQuery, setSearchQuery] = useState("");
    const [isLoading, setLoading] = useState(false);
    const [jobPostings, setjobPostings] = useState([]);
    const [noRoles, setNoRoles] = useState(false)

    const expandedContainer = () => {
        setExpanded(true);
    }

    const collapseContainer = () => {
        setExpanded(false);
        setSearchQuery("");
         setLoading(false);
         setNoRoles(false);
        if (inputRef.current) inputRef.current.value = "";

      };

    useEffect(()=> {
        if(isClickedOutside)
            collapseContainer();
    }, [isClickedOutside])

    const [term, setTerm] = useState("")

    const dispatch = useDispatch();

    const changeHandler = (e) => {
        e.preventDefault();
        setLoading(true)
        fetchAsyncRoles(dispatch, term);
        setLoading(false)
    }

    return (
    <SearchBarContainer animate = {isExpanded ? "expanded" : "collapsed"}
                        variants={containerVariants} transition={containerTransition} ref={parentRef}>
        <SearchInputContainer>
            <SearchIconSpan>
                <SearchIcon/>
            </SearchIconSpan>
            <GeneralContainerForm onSubmit={changeHandler}>
            <SearchInput placeholder = "Search for Roles"
                                onFocus={expandedContainer}
                                ref={inputRef}
                                value={term}
                                onChange={(e)=> setTerm(e.target.value)}
                                />
            </GeneralContainerForm>
            <AnimatePresence>
                {isExpanded && (<CloseIconSpan  key="close-icon"
                                inital={{opacity:0, rotate: 0}}
                                animate={{opacity:1, rotate: 180}}
                                exit={{opacity:0, rotate: 0}}
                                transition={{duration: 0.2}}
                                onClick={collapseContainer}
                                onChange={(e)=> setTerm(e.target.value)}
                                >
                    <CloseIcon/>
                </CloseIconSpan>
                 )}
            </AnimatePresence>
        </SearchInputContainer>
        {isExpanded && <LineSeperator/>}
        {isExpanded && <SearchContent>

        {!isLoading && !noRoles && (
        <Typography color="gray" display="flex" flex="0.2" alignSelf="center" justifySelf="center">
                Start typing to search
        </Typography>
        )}

        {!isLoading && <>
            {jobPostings.map((roles) => (
                <JobSection
                    title={roles.title}
                />
            ))}
        </>}
        </SearchContent>}
    </SearchBarContainer>
    )
}

</code>```

What is the correct manner to do this? Is it mapstatetoprops? If so what's the proper way.

I am looking to implement further actions and the majority of the project is on the basis of this redux store concept, but I am quite new!

答:
You would not use mapStateToProps nowadays except in legacy class components.

Instead, you use useSelector. So if you want to select something from state.foo.bar, you do

const bar = useSelector(state => state.foo.bar)
```

If you are just learning Redux I would highly recommend that you follow the official Redux tutorial as a lot of other sources out there are quite outdated. Modern Redux does not use switch..case reducers, ACTION_TYPEs, immutable reducer logic, hand-written action creators, createStore or connect/mapStateToProps any more and is about 1/4 of the code of that old style of Redux using all these concepts.

Title: Mapping Redux Store Data to FrontEnd

Body:
I'm looking to map a store I have to the frontend. Please see below:

When a user searches, it makes a request and dispatches and action. E.g if I look up 'Data', I get data for all jobs with Data in the title.

https://gyazo.com/e8c086fa6c929c70863abb4551127d21

As you can see in the store, I have an action and I have in my store the following: job search, which fetches roles. I'd like to map these roles out by title to the front end section.

Please see my code below:

export function SearchBarTrialRedux(props) {

    const [isExpanded, setExpanded] = useState(false);
    const [parentRef, isClickedOutside ] = useClickOutside();
    const inputRef = useRef();
    const [searchQuery, setSearchQuery] = useState("");
    const [isLoading, setLoading] = useState(false);
    const [jobPostings, setjobPostings] = useState([]);
    const [noRoles, setNoRoles] = useState(false)

    const expandedContainer = () => {
        setExpanded(true);
    }

    const collapseContainer = () => {
        setExpanded(false);
        setSearchQuery("");
         setLoading(false);
         setNoRoles(false);
        if (inputRef.current) inputRef.current.value = "";

      };

    useEffect(()=> {
        if(isClickedOutside)
            collapseContainer();
    }, [isClickedOutside])

    const [term, setTerm] = useState("")

    const dispatch = useDispatch();

    const changeHandler = (e) => {
        e.preventDefault();
        setLoading(true)
        fetchAsyncRoles(dispatch, term);
        setLoading(false)
    }

    return (
    <SearchBarContainer animate = {isExpanded ? "expanded" : "collapsed"}
                        variants={containerVariants} transition={containerTransition} ref={parentRef}>
        <SearchInputContainer>
            <SearchIconSpan>
                <SearchIcon/>
            </SearchIconSpan>
            <GeneralContainerForm onSubmit={changeHandler}>
            <SearchInput placeholder = "Search for Roles"
                                onFocus={expandedContainer}
                                ref={inputRef}
                                value={term}
                                onChange={(e)=> setTerm(e.target.value)}
                                />
            </GeneralContainerForm>
            <AnimatePresence>
                {isExpanded && (<CloseIconSpan  key="close-icon"
                                inital={{opacity:0, rotate: 0}}
                                animate={{opacity:1, rotate: 180}}
                                exit={{opacity:0, rotate: 0}}
                                transition={{duration: 0.2}}
                                onClick={collapseContainer}
                                onChange={(e)=> setTerm(e.target.value)}
                                >
                    <CloseIcon/>
                </CloseIconSpan>
                 )}
            </AnimatePresence>
        </SearchInputContainer>
        {isExpanded && <LineSeperator/>}
        {isExpanded && <SearchContent>

        {!isLoading && !noRoles && (
        <Typography color="gray" display="flex" flex="0.2" alignSelf="center" justifySelf="center">
                Start typing to search
        </Typography>
        )}

        {!isLoading && <>
            {jobPostings.map((roles) => (
                <JobSection
                    title={roles.title}
                />
            ))}
        </>}
        </SearchContent>}
    </SearchBarContainer>
    )
}

What is the correct manner to do this? Is it mapstatetoprops? If so what's the proper way.

I am looking to implement further actions and the majority of the project is on the basis of this redux store concept, but I am quite new!

Body:
You would not use mapStateToProps nowadays except in legacy class components.

Instead, you use useSelector. So if you want to select something from state.foo.bar, you do

const bar = useSelector(state => state.foo.bar)

If you are just learning Redux I would highly recommend that you follow the official Redux tutorial as a lot of other sources out there are quite outdated. Modern Redux does not use switch..case reducers, ACTION_TYPEs, immutable reducer logic, hand-written action creators, createStore or connect/mapStateToProps any more and is about 1/4 of the code of that old style of Redux using all these concepts.


问:
How to make an text generator
I been stuck in this line of code trying to make a text generator that generates a random text with a vocabulary, like I'm trying to make a code that generates text with the letters ABCDE on uppercase and on lowercase and the numbers 12345, this is my code I been stuck on:

```<code>import string
import random # define the random module
S = 681  # number of characters in the string
#call random.choices() string module to find the string in Uppercase + numeric data.
ran = ''.join(random.choices(string.ascii_uppercase + string.digits + string.ascii_lowercase, k = S))
print("Generated text is : " + str(ran)) # print the random data
</code>```

If you could help I will be extremely thankful (I'm spanish so if I speak bad english thats why)

答:
Just put a list of your desired letters there.</p>
```<code>import string
import random # define the random module
S = 681  # number of characters in the string

letters = 'abcdefg'

ran = ''.join(random.choices(letters, k = S))
print("Generated text is : " + str(ran)) # print the random data
</code>```

Title: How to make an text generator

Body:
I been stuck in this line of code trying to make a text generator that generates a random text with a vocabulary, like I'm trying to make a code that generates text with the letters ABCDE on uppercase and on lowercase and the numbers 12345, this is my code I been stuck on:

import string
import random # define the random module
S = 681  # number of characters in the string
#call random.choices() string module to find the string in Uppercase + numeric data.
ran = ''.join(random.choices(string.ascii_uppercase + string.digits + string.ascii_lowercase, k = S))
print("Generated text is : " + str(ran)) # print the random data

If you could help I will be extremely thankful (I'm spanish so if I speak bad english thats why)

Body:
Just put a list of your desired letters there.

import string
import random # define the random module
S = 681  # number of characters in the string

letters = 'abcdefg'

ran = ''.join(random.choices(letters, k = S))
print("Generated text is : " + str(ran)) # print the random data