问:
Utilizing the <filesystem> library; visualStudios
I'll cut the the short of it. I'm attempting to understand the filesystem library but there's very little information I've been able to find. I managed to get it to compile and understand the filesystem::path type variable really well but don't seem to understand how to get filesystem::directory_iterator to work properly. I'm not sure if I'm using it for a purpose it wasn't design for. So here is what I'm attempting to do:

I wanted to create a program that opens every text file within a specified folder. For this I need to obtain the folder name and path but I want the program to be able to obtain this information on itself and dynamically so if I add or remove textFiles it'll have the logic to function.

I'm able to create a directory_iterator variable that it manages to hold the first file with me just giving it the directory like this:

```<code>const char address[]{ "C:\\Users\\c-jr8\\ProgramBranch\\PersonalPlatform\\log extruder\\logs" };

fs::directory_iterator myIterator(address);
</code>```

When testing the code in the folder I have four textFiles called "attempt 1" to "attempt 4". When reading the information on:

https://learn.microsoft.com/en-us/cpp/standard-library/directory-iterator-class?view=vs-2019#op_star

It mentions two functions to move the path object within the iterator to the next file. The first is increment(), which is the intendent method for iterating through the files, and operation++().

Now increment() hasn't been able to work for me cause it takes in a erro_code type variable and I haven't been able to find much information about how to implement this with the filesystem_errorcode variable or however it's meant to be used. The operation++() works beautifully and provides me with the path to every file but I was having issues with managing the code to detect when the operate++() functions leads to no other files. Once it iterates through every file it sorts of crashes when it keeps moving to the next. Here's that piece of code:

```<code>string tempString;
for (int i = 0; i < 5; i++) { //Here the limiting is 5 so it'll iterate onces more than the numbers of files unpurpose to see how it responses.
    tempString = myIterator.operator*().path().generic_string();
    ifstream tempFile(tempString);

    if (!tempFile.is_open()) {
        cout << "Looking at file: " << i + 1 << "; failed to open." << endl << endl;
        cin.get();
        return 0;
    }

    {
        //do things with file...
    }

    tempFile.close();
    myIterator.operator++();
}
</code>```

What I want if to find a way to stop the for loop once it the iterator goes off the final file.

whichever information about how the filesystem library works it would be very much appreciated.

答:
std::directory_iterator is a classic iterator that allows for iterating over ranges, and those are usually designated by a pair of iterators, one indicating the beginning of a sequence and another representing the past-the-end iterator.

Some iterator types, like those providing access to streams, don't have an actual end location in memory. A similar situation applies to a directory iterator. In such a case, the idiomatic approach is to use a default-constructed iterator object that will serve as an end indicator.

Having said that, you could rewrite your loop to:

for (fs::directory_iterator myIterator(address), end{}; myIterator != end; ++myIterator) {
```

<p>Alternatively, you can utilize a range-based for loop:</p>

```for (auto& p : fs::directory_iterator(address)) {
    tempString = p.path().generic_string();
    // ...
```

<p>Also, note that iterators' <em>interface</em> is supposed to look/behave like a pointer, hence it uses operator overloading to allow for concise syntax. So instead of:</p>

```myIterator.operator++();
```

<p>you should be using:</p>

```++myIterator;
```

<p>Similarly, instead of:</p>

```myIterator.operator*().path().generic_string();
```

<p>juse use:</p>

```(*myIterator).path().generic_string();
```

<p>or:</p>

```myIterator->path().generic_string();
```

Body:
I'll cut the the short of it. I'm attempting to understand the filesystem library but there's very little information I've been able to find. I managed to get it to compile and understand the filesystem::path type variable really well but don't seem to understand how to get filesystem::directory_iterator to work properly. I'm not sure if I'm using it for a purpose it wasn't design for. So here is what I'm attempting to do:

I wanted to create a program that opens every text file within a specified folder. For this I need to obtain the folder name and path but I want the program to be able to obtain this information on itself and dynamically so if I add or remove textFiles it'll have the logic to function.

I'm able to create a directory_iterator variable that it manages to hold the first file with me just giving it the directory like this:

const char address[]{ "C:\\Users\\c-jr8\\ProgramBranch\\PersonalPlatform\\log extruder\\logs" };

fs::directory_iterator myIterator(address);

When testing the code in the folder I have four textFiles called "attempt 1" to "attempt 4". When reading the information on:

https://learn.microsoft.com/en-us/cpp/standard-library/directory-iterator-class?view=vs-2019#op_star

It mentions two functions to move the path object within the iterator to the next file. The first is increment(), which is the intendent method for iterating through the files, and operation++().

Now increment() hasn't been able to work for me cause it takes in a erro_code type variable and I haven't been able to find much information about how to implement this with the filesystem_errorcode variable or however it's meant to be used. The operation++() works beautifully and provides me with the path to every file but I was having issues with managing the code to detect when the operate++() functions leads to no other files. Once it iterates through every file it sorts of crashes when it keeps moving to the next. Here's that piece of code:

string tempString;
for (int i = 0; i < 5; i++) { //Here the limiting is 5 so it'll iterate onces more than the numbers of files unpurpose to see how it responses.
    tempString = myIterator.operator*().path().generic_string();
    ifstream tempFile(tempString);

    if (!tempFile.is_open()) {
        cout << "Looking at file: " << i + 1 << "; failed to open." << endl << endl;
        cin.get();
        return 0;
    }

    {
        //do things with file...
    }

    tempFile.close();
    myIterator.operator++();
}

What I want if to find a way to stop the for loop once it the iterator goes off the final file.

whichever information about how the filesystem library works it would be very much appreciated.

Body:
std::directory_iterator is a classic iterator that allows for iterating over ranges, and those are usually designated by a pair of iterators, one indicating the beginning of a sequence and another representing the past-the-end iterator.

Some iterator types, like those providing access to streams, don't have an actual end location in memory. A similar situation applies to a directory iterator. In such a case, the idiomatic approach is to use a default-constructed iterator object that will serve as an end indicator.

Having said that, you could rewrite your loop to:

for (fs::directory_iterator myIterator(address), end{}; myIterator != end; ++myIterator) {

Alternatively, you can utilize a range-based for loop:

for (auto& p : fs::directory_iterator(address)) {
    tempString = p.path().generic_string();
    // ...

Also, note that iterators' interface is supposed to look/behave like a pointer, hence it uses operator overloading to allow for concise syntax. So instead of:

myIterator.operator++();

you should be using:

++myIterator;

Similarly, instead of:

myIterator.operator*().path().generic_string();

juse use:

(*myIterator).path().generic_string();

or:

myIterator->path().generic_string();


来源: stackexchange

问:
How to associate dynamic value with HTML elements?
I want to create a list which is clickable and which would allow me to take a survey when I click it.

```<code>{% extends "layout.html" %}

{% block title %}
    Take Survey
{% endblock %}

{% block main %}
    <div class="list-group">
      { for search in searches }
      <a href="\take" class="list-group-item">{{search.topic}}</a>
      { endfor }
    </div>
{% endblock %}
</code>```

When I click it I want it to go to a page which shows the questions of the survey whose topic was being shown.
I have created SQL tables for users,surveys,questions and options. Surveys are linked to users, questions are linked to surveys and options are linked to questions.

I just need a way to access the survey id({{search.id}}) in my take route where I could run a SQL query using the survey id to link everything.

Just a disclaimer, I am a beginner in HTML so please try to explain elaborately.

答:
There are multiple ways that you can do this with html, here are a few of them

create a hidden input with the value that u need, and later when u need it retrieve it from that input

```<code> <input type="hidden" id="searchId" name="searchId" value="3487">
</code>```

add a custom attribute to an element, and later when needed retrieve it from that element

```<code><div class="list-group">
      { for search in searches }
      <a href="\take" class="list-group-item">{{search.topic}} data-search-id="{{search.id}}"</a>
      { endfor }
    </div>
</code>```

There are also multiple ways you can do this without html

insert a script that has the search id, and later retrieve that id from javascript

```<code>{% block main %}
    <div class="list-group">
      { for search in searches }
      <a href="\take" class="list-group-item">{{search.topic}}</a>
      { endfor }
       <script>
       // just make sure that this variable is unique, so u dont cause errors or overwrite another variable by mistake
       const MY_APP_SEARCH_ID ={{search.id}}
       </script>
    </div>
{% endblock %}
</code>```

You could also generate a unique url for each survey

```<code> <a href="\take?searchId={{search.id}}" class="list-group-item">{{search.topic}} </a>
</code>```

and then handle that search id from the \take endpoint

ContentLicense: CC BY-SA 4.0

Body:
I want to create a list which is clickable and which would allow me to take a survey when I click it.

{% extends "layout.html" %}

{% block title %}
    Take Survey
{% endblock %}

{% block main %}

      { for search in searches }
      {{search.topic}}
      { endfor }

{% endblock %}

When I click it I want it to go to a page which shows the questions of the survey whose topic was being shown.
I have created SQL tables for users,surveys,questions and options. Surveys are linked to users, questions are linked to surveys and options are linked to questions.

I just need a way to access the survey id({{search.id}}) in my take route where I could run a SQL query using the survey id to link everything.

Just a disclaimer, I am a beginner in HTML so please try to explain elaborately.

Body:
There are multiple ways that you can do this with html, here are a few of them

create a hidden input with the value that u need, and later when u need it retrieve it from that input

 <input type="hidden" id="searchId" name="searchId" value="3487">

add a custom attribute to an element, and later when needed retrieve it from that element

<div class="list-group">
      { for search in searches }
      <a href="\take" class="list-group-item">{{search.topic}} data-search-id="{{search.id}}"</a>
      { endfor }
    </div>

There are also multiple ways you can do this without html

insert a script that has the search id, and later retrieve that id from javascript

{% block main %}
    <div class="list-group">
      { for search in searches }
      <a href="\take" class="list-group-item">{{search.topic}}</a>
      { endfor }
       <script>
       // just make sure that this variable is unique, so u dont cause errors or overwrite another variable by mistake
       const MY_APP_SEARCH_ID ={{search.id}}
       </script>
    </div>
{% endblock %}

You could also generate a unique url for each survey

 <a href="\take?searchId={{search.id}}" class="list-group-item">{{search.topic}} </a>

and then handle that search id from the \take endpoint


问:
Change value of new Date() 's time
I am fetching the value of today's date using this code below:

```<code>var today = new Date();
console.log(today);
</code>```

The value of console log is Sat May 30 2020 12:13:18 GMT+0530 (India Standard Time)

But what I want to achieve is, whatever the time is I want value as

var today_morning = Sat May 30 2020 09:30:00 GMT+0530 (India Standard Time)

How do I get this value in today_morning irrespective of what time value is in var today?

答:
Try using setHours()

var today = new Date();
console.log(today.toString());

today.setHours(9, 30, 0)
var today_morning = today;
console.log(today_morning.toString());```

Title: Change value of new Date() 's time

Body:
I am fetching the value of today's date using this code below:

var today = new Date();
console.log(today);

The value of console log is Sat May 30 2020 12:13:18 GMT+0530 (India Standard Time)

But what I want to achieve is, whatever the time is I want value as

var today_morning = Sat May 30 2020 09:30:00 GMT+0530 (India Standard Time)

How do I get this value in today_morning irrespective of what time value is in var today?


问:
Javers - Custom comparator for generic list - GENERIC_TYPE_NOT_PARAMETRIZED
I would like to compare a generic list which is defined in abstract class in object which inherits from that class, the thing is that I would like to implement custom comparator for that list's objects.

here is code of the abstract class:

```<code>class A<T extends GenericT, DM extends SomeOtherGeneric>{
private List<T> genericsT = new ArrayList()<>;
private DM otherGeneric;
}
</code>```

And here you can find class which I am comparing explicitly:

```<code>class ExtendsA extends A<ImplementationOfT, ImplementationOfOther>{
}
</code>```

what I am trying to do is to have registered such comparators:

```<code> javers.registerCustomType(ImplementationOfOther.class, new ImplementationOfOtherComparator()); // this one works as expected
 javers.registerCustomType(ImplementationOfA.class, new ImplementationOfAComparator()); //this one is not called
</code>```

So as you can see list genericsT is not compared in the way I would like to have it.

Here is also a warning which I get from javers:

```<code>09:40:26.945 [main] WARN org.javers.core.diff.appenders.CorePropertyChangeAppender - Unknown item type in
Set property: Field ListAsSetType:List<T> genericsT , declared in A. Defaulting to Object, see
CorePropertyChangeAppender.GENERIC_TYPE_NOT_PARAMETRIZED
</code>```

Is there any possibility to add custom comparator for implementation of ImplementationOfT which will be comparing list's elements genericsT when class ExtendsA is compared?

EDIT:
Looks like I can use javers.compareCollections(a.getGenericsT(), b.getGenericsT(), ImplementationOfT.class)
and mark the collection with @DiffIgnore
but change's affectedCoID gives me org.javers.core.graph.LiveGraphFactory$ListWrapper
Is there any way to set there my custom name?

答: Javers doesn't support all possible generic types in Java, there are limitations where things are getting too complex. Push your case here https://github.com/javers/javers/tree/master/javers-core/src/test/groovy/org/javers/core/cases then I will check why it doesn't work and will try to find a solution. </p>

Body:
I would like to compare a generic list which is defined in abstract class in object which inherits from that class, the thing is that I would like to implement custom comparator for that list's objects.

here is code of the abstract class:

class A<T extends GenericT, DM extends SomeOtherGeneric>{
private List<T> genericsT = new ArrayList()<>;
private DM otherGeneric;
}

And here you can find class which I am comparing explicitly:

class ExtendsA extends A<ImplementationOfT, ImplementationOfOther>{
}

what I am trying to do is to have registered such comparators:

 javers.registerCustomType(ImplementationOfOther.class, new ImplementationOfOtherComparator()); // this one works as expected
 javers.registerCustomType(ImplementationOfA.class, new ImplementationOfAComparator()); //this one is not called

So as you can see list genericsT is not compared in the way I would like to have it.

Here is also a warning which I get from javers:

09:40:26.945 [main] WARN org.javers.core.diff.appenders.CorePropertyChangeAppender - Unknown item type in
Set property: Field ListAsSetType:List<T> genericsT , declared in A. Defaulting to Object, see
CorePropertyChangeAppender.GENERIC_TYPE_NOT_PARAMETRIZED

Is there any possibility to add custom comparator for implementation of ImplementationOfT which will be comparing list's elements genericsT when class ExtendsA is compared?

EDIT:
Looks like I can use javers.compareCollections(a.getGenericsT(), b.getGenericsT(), ImplementationOfT.class)
and mark the collection with @DiffIgnore
but change's affectedCoID gives me org.javers.core.graph.LiveGraphFactory$ListWrapper
Is there any way to set there my custom name?


问:
Issue with taskAffinity and excludeFromRecents on Android 10
I have an application which is sometimes displaying notifications to users.
When pressing a notification, a "Dispatch" Activity is triggered which calls startActivities with some intents leading to proper activity depending on the notification payload.
Here is how it is declared in Manifest according to https://developer.android.com/training/notify-user/navigation#ExtendedNotification

```<code>            android:name=".DispatchActivity"
            android:taskAffinity=""
            android:excludeFromRecents="true"
            android:launchMode="singleTask" />
</code>```

When I press a notification, DispatchActivity is launched with Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK and launches a new activity with Intent.FLAG_ACTIVITY_NEW_TASK before it immediately calls finish(). If my application was already launched, the new activity (let's call it the second Activity) is launched on top of previous already launched activity so when you press Recents button, you can see my app only once.

This is actually the behaviour I want. The thing is, when I run the same code on Android 10 and press Recents button, I can see two instances of my app (well two tasks I guess)  :

If I press Recent button again to restore the second Activity, it just goes away and I only have the initial Activity. As if SecondActivity inherited from excludeFromRecents behaviour where this is not the case on other Android versions (I even tested on Android 11 preview and it's working as expected).

I tried removing taskAffinity="" for DispatchActivity in Manifest so it has same affinity as other Activities in the application, but I then have issues when receiving a notification with my app not launched where activities launched from DispatchActivity are going away like initially on Android 10 because of excludeFromRecents tag.

I'm running out of idea right now so if you have any solution or maybe have already met the problem I'm open for suggestions.

Thanks !

Here is the sample code if needed : https://github.com/LoicJ/MultiTaskBugSample.git

答:
The answer is android:noHistory="true" add this line to your activity in the manifest file it will provide your expected behavior.

Your final code may look like:

```<code><activity
        android:name=".DispatchActivity"
        android:excludeFromRecents="true"
        android:launchMode="singleTask"
        android:noHistory="true"
        android:taskAffinity="" />
</code>```

Body:
I have an application which is sometimes displaying notifications to users.
When pressing a notification, a "Dispatch" Activity is triggered which calls startActivities with some intents leading to proper activity depending on the notification payload.
Here is how it is declared in Manifest according to https://developer.android.com/training/notify-user/navigation#ExtendedNotification

            android:name=".DispatchActivity"
            android:taskAffinity=""
            android:excludeFromRecents="true"
            android:launchMode="singleTask" />

When I press a notification, DispatchActivity is launched with Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK and launches a new activity with Intent.FLAG_ACTIVITY_NEW_TASK before it immediately calls finish(). If my application was already launched, the new activity (let's call it the second Activity) is launched on top of previous already launched activity so when you press Recents button, you can see my app only once.

This is actually the behaviour I want. The thing is, when I run the same code on Android 10 and press Recents button, I can see two instances of my app (well two tasks I guess)  :

If I press Recent button again to restore the second Activity, it just goes away and I only have the initial Activity. As if SecondActivity inherited from excludeFromRecents behaviour where this is not the case on other Android versions (I even tested on Android 11 preview and it's working as expected).

I tried removing taskAffinity="" for DispatchActivity in Manifest so it has same affinity as other Activities in the application, but I then have issues when receiving a notification with my app not launched where activities launched from DispatchActivity are going away like initially on Android 10 because of excludeFromRecents tag.

I'm running out of idea right now so if you have any solution or maybe have already met the problem I'm open for suggestions.

Thanks !

Here is the sample code if needed : https://github.com/LoicJ/MultiTaskBugSample.git

Body:
The answer is android:noHistory="true" add this line to your activity in the manifest file it will provide your expected behavior.

Your final code may look like:

<activity
        android:name=".DispatchActivity"
        android:excludeFromRecents="true"
        android:launchMode="singleTask"
        android:noHistory="true"
        android:taskAffinity="" />


问:
Why does a child object call private method of the super class having main method?
In the below code, the child class object calls its getBankName() method but instead, the private method getBankName() of parent class is invoked.

```<code>public class Bank {
    private void getBankName() {
        System.out.println("Bank");
    }
    public static void main(String[] args) {
        Bank bank = new MyBank();
        bank.getBankName();
    }
}

class MyBank extends Bank {
    public void getBankName() {
        System.out.println("MyBank");
    }
}
</code>```

Further, if I change the access specifier of parent's method to public, then it works fine(child object calls its own method and prints 'MyBank'). Why is the invocation getting affected just because of the access specifier of the parent method??

答:
Private methods can't be overridden; they're entirely different items, like redeclared (shadowing) fields.

When the visibility of a method is not private, the compiler uses the invokevirtual instruction, which is responsible for finding the appropriate override and executing it. However, for a private method, the compiler uses invokespecial (see "Notes"), which explicitly does not allow for overrides.

Body:
In the below code, the child class object calls its getBankName() method but instead, the private method getBankName() of parent class is invoked.

public class Bank {
    private void getBankName() {
        System.out.println("Bank");
    }
    public static void main(String[] args) {
        Bank bank = new MyBank();
        bank.getBankName();
    }
}

class MyBank extends Bank {
    public void getBankName() {
        System.out.println("MyBank");
    }
}

Further, if I change the access specifier of parent's method to public, then it works fine(child object calls its own method and prints 'MyBank'). Why is the invocation getting affected just because of the access specifier of the parent method??


问:
Comparing runtimes
I am trying to get some accurate runtime comparisons of PHP vs Python (and potentially any other language that I have to include). Timing within a script is not my problem but timing within a script does not account for everything from the moment the request is made to run the script to output.

1) Is it actually worth taking such things into account?

2) Assuming it is worth taking it into account, how do I do this?

I'm using a Mac so I've got access to Linux commands and I'm not afraid to compile/create a command to help me, I just don't know how to write such a command.

答:
Well, you can use the "time" command to help:

```<code>you@yourmachine:~$ time echo "hello world"
hello world

real    0m0.000s
user    0m0.000s
sys 0m0.000s
you@yourmachine:~$
</code>```

And this will get around timing outside of the environment.

As for whether you need to actually time that extra work... that entirely depends on what you are doing.  I assume this is for some kind of web application of some sort, so it depends on how the framework you use actually works... does it cache some kind of compiled (or parsed) version of the script?  If so, then startup time will be totally irrelevant (since the first hit will be the only one that startup time exists in).

Also, make sure to run your tests in a loop so you can discount the first run (and include the cost on the first run in your report if you want).  I have done some tests in Java, and the first run is always slowest due to the JIT doing its job (and the same sort of hit may exist in PHP, Python and any other languages you try).

OwnerDisplayName: Teifion

ContentLicense: CC BY-SA 3.0

Title: Comparing runtimes

LastEditorDisplayName: hoyhoy

Body:
Well, you can use the "time" command to help:

you@yourmachine:~$ time echo "hello world"
hello world

real    0m0.000s
user    0m0.000s
sys 0m0.000s
you@yourmachine:~$

And this will get around timing outside of the environment.

As for whether you need to actually time that extra work... that entirely depends on what you are doing.  I assume this is for some kind of web application of some sort, so it depends on how the framework you use actually works... does it cache some kind of compiled (or parsed) version of the script?  If so, then startup time will be totally irrelevant (since the first hit will be the only one that startup time exists in).

Also, make sure to run your tests in a loop so you can discount the first run (and include the cost on the first run in your report if you want).  I have done some tests in Java, and the first run is always slowest due to the JIT doing its job (and the same sort of hit may exist in PHP, Python and any other languages you try).

OwnerDisplayName: Mike Stone

ContentLicense: CC BY-SA 2.5


问:
Programatic data binding
I am trying to get my head around the power and complexities of data binding. I'm working on a reasonably complex app that requires a view model to aggregate all of the disparate data, and then bind that model to the user controls.

My view model is structured to create numerous classes to manage the individual data elements, and I want to bind these classes together programatically, i.e outside the UI.

I need to bind data elements of two seemingly unrelated classes together. I can then bring the aggregate class data to the UI, using xaml.

In other words, classes "A and "B" each have a string declared as "Name". I want to achieve two way binding of these so that when either "Name" is changed, the binding takes care of the data update.

This task seems easy enough, but I have not been able to find any examples.

答:
When it comes to databinding this MSDN page is highly relevant.

You should note that bindings require the target property to be a DependecyProperty and that bindings are conceptually one-sided, they simply can go in both directions while only being set on one end.

You normally do not want DependencyProperties is your model because it requires it to inherit from DependencyObject. It might be better to achieve this relationship by referecing the same name-wrapping object in both classes.

Title: Programatic data binding


问:
How to restructure an array of single-element associative arrays into grouped subarrays?
I have an associative array:

```<code>Array (
[0] => Array ( [term_title] => black )
[1] => Array ( [color_quantity] => 2 )
[2] => Array ( [color_price] => 22 )
[3] => Array ( [term_title] => blue )
[4] => Array ( [color_quantity] => 3 )
[5] => Array ( [color_price] => 33 ))
</code>```

How can I change it into:

```<code>Array (
[0] => Array ( [term_title] => black, [color_quantity] => 2, [color_price] => 22 )
[1] => Array ( [term_title] => blue, [color_quantity] => 3, [color_price] => 33 ) )
</code>```

I try the following code:

```<code>$post = array();
for($i = 0; $i < 2; $i++){
    foreach($feild_data as $data){
        $post[$i][$data['name']] = $data['value'];
    }
}
</code>```

but it repeat the last index two times. i.e.

```<code>Array (
[0] => Array ( [term_title] => blue, [color_quantity] => 3, [color_price] => 33 )
[1] => Array ( [term_title] => blue, [color_quantity] => 3, [color_price] => 33 ) )
</code>```

答:
Not sure from where name and value came in $data['name'] and $data['value'], but you can use array_chunk to divide them in chunks and assign them to $posts.

```<code><?php

$posts = array();
foreach(array_chunk($field_data,3) as $data){
    $temp = [];
    foreach($data as $field){
        foreach($field as $key => $value){
            $temp[$key] = $value;
        }
    }

    $posts[] = $temp;
}

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

Body:
I have an associative array:

Array (
[0] => Array ( [term_title] => black )
[1] => Array ( [color_quantity] => 2 )
[2] => Array ( [color_price] => 22 )
[3] => Array ( [term_title] => blue )
[4] => Array ( [color_quantity] => 3 )
[5] => Array ( [color_price] => 33 ))

How can I change it into:

Array (
[0] => Array ( [term_title] => black, [color_quantity] => 2, [color_price] => 22 )
[1] => Array ( [term_title] => blue, [color_quantity] => 3, [color_price] => 33 ) )

I try the following code:

$post = array();
for($i = 0; $i < 2; $i++){
    foreach($feild_data as $data){
        $post[$i][$data['name']] = $data['value'];
    }
}

but it repeat the last index two times. i.e.

Array (
[0] => Array ( [term_title] => blue, [color_quantity] => 3, [color_price] => 33 )
[1] => Array ( [term_title] => blue, [color_quantity] => 3, [color_price] => 33 ) )

Body:
Not sure from where name and value came in $data['name'] and $data['value'], but you can use array_chunk to divide them in chunks and assign them to $posts.

<?php

$posts = array();
foreach(array_chunk($field_data,3) as $data){
    $temp = [];
    foreach($data as $field){
        foreach($field as $key => $value){
            $temp[$key] = $value;
        }
    }

    $posts[] = $temp;
}

print_r($posts);


问:
File rename if file already exists more than one time
I have a working code which will take a file eg, "photo.png" and move it into a folder. If it already exists it will rename it "1_photo.png" although if you have another photo name "photo.png" it will rename it to the file "1_photo.png" that already exits and will not work. I would like to know what the solution is for this. </p>

```<code>        Dim grade As String
        grade = (FolderBrowserDialog1.SelectedPath)
        grade = My.Settings.SD

        My.Computer.FileSystem.CreateDirectory(
grade + ("\Pictures"))

        Dim filePaths = IO.Directory.GetFiles(grade, "*.png")

        For Each filePath In filePaths
            Dim filename = IO.Path.GetFileName(filePath)
            Dim newPath = IO.Path.Combine(grade + ("\Pictures"), filename)

            If IO.File.Exists(newPath) Then
                Dim dr = MessageBox.Show($"File {newPath} exists, do you want to keep both files? The recently moved file will have a number added to its name", "", MessageBoxButtons.YesNoCancel)

                Select Case dr
                    Case DialogResult.Cancel
                        Continue For

                    Case DialogResult.No
                        IO.File.Delete(newPath)

                    Case DialogResult.Yes

                        If IO.File.Exists(newPath) Then
                            Dim rn As New Random
                            My.Computer.FileSystem.RenameFile(newPath, "1_" + filename)

                            IO.File.Move(filePath, newPath)

                            MessageBox.Show("Pictures Compiled and Cleaned")

                            Return
                        End If

                End Select

            End If

            IO.File.Move(filePath, newPath)
</code>```

答:
You make a loop conditional on the file existing:

```<code>Dim filename = "a.png"
Dim dirname = "c:\temp"

Dim filePath = Path.Combine(dirname, filename)

Dim i as Integer = 1
While(IO.File.Exists(filePath))
  filePath = Path.Combine(dirname, i & "_" & filename)
  i += 1
End While
</code>```

Eventually, the loop will find a filePath that doesn't exist.

Putting a number at the start of a filename is probably a bad idea by the way. I recommend you put it at the end:

```<code>filePath = Path.Combine(dirname, Path.ChangeExtension(filename, i & Path.GetExtension(filename)))
</code>```

This makes files like photo.png, photo.1.png, photo.2.png, photo.3.png...

I would wrap it up in a function that finds a filename that doesn't clash:

```<code>Function GetRelatedNonExistantFilepath(Dim desiredPath as String) As String()

    Dim filename =  Path.GetFilenameWithoutExtension(desiredPath)
    Dim ext = Path.GetExtension(desiredPath)
    Dim dirname = Path.GetDirectoryName(desiredPath)

    Dim filePath = desiredPath

    Dim i as Integer = 1
    While(IO.File.Exists(filePath))
      filePath = Path.Combine(dirname, filename & "_" & i & ext)
      i += 1
    End While

    Return filePath
End Function
</code>```

You'd hence use it like:

```<code>    'want to move to c:\temp\photo.png but it might exist
    Dim dest = "c:\temp\photo.png"

    Dim actualDest = GetRelatedNonExistantFilepath(dest)

    'move file to actual dest
    IO.FIle.Move(sourcePath, actualDest)
</code>```

Body:
I have a working code which will take a file eg, "photo.png" and move it into a folder. If it already exists it will rename it "1_photo.png" although if you have another photo name "photo.png" it will rename it to the file "1_photo.png" that already exits and will not work. I would like to know what the solution is for this.

        Dim grade As String
        grade = (FolderBrowserDialog1.SelectedPath)
        grade = My.Settings.SD

        My.Computer.FileSystem.CreateDirectory(
grade + ("\Pictures"))

        Dim filePaths = IO.Directory.GetFiles(grade, "*.png")

        For Each filePath In filePaths
            Dim filename = IO.Path.GetFileName(filePath)
            Dim newPath = IO.Path.Combine(grade + ("\Pictures"), filename)

            If IO.File.Exists(newPath) Then
                Dim dr = MessageBox.Show($"File {newPath} exists, do you want to keep both files? The recently moved file will have a number added to its name", "", MessageBoxButtons.YesNoCancel)

                Select Case dr
                    Case DialogResult.Cancel
                        Continue For

                    Case DialogResult.No
                        IO.File.Delete(newPath)

                    Case DialogResult.Yes

                        If IO.File.Exists(newPath) Then
                            Dim rn As New Random
                            My.Computer.FileSystem.RenameFile(newPath, "1_" + filename)

                            IO.File.Move(filePath, newPath)

                            MessageBox.Show("Pictures Compiled and Cleaned")

                            Return
                        End If

                End Select

            End If

            IO.File.Move(filePath, newPath)

Body:
You make a loop conditional on the file existing:

Dim filename = "a.png"
Dim dirname = "c:\temp"

Dim filePath = Path.Combine(dirname, filename)

Dim i as Integer = 1
While(IO.File.Exists(filePath))
  filePath = Path.Combine(dirname, i & "_" & filename)
  i += 1
End While

Eventually, the loop will find a filePath that doesn't exist.

Putting a number at the start of a filename is probably a bad idea by the way. I recommend you put it at the end:

filePath = Path.Combine(dirname, Path.ChangeExtension(filename, i & Path.GetExtension(filename)))

This makes files like photo.png, photo.1.png, photo.2.png, photo.3.png...

I would wrap it up in a function that finds a filename that doesn't clash:

Function GetRelatedNonExistantFilepath(Dim desiredPath as String) As String()

    Dim filename =  Path.GetFilenameWithoutExtension(desiredPath)
    Dim ext = Path.GetExtension(desiredPath)
    Dim dirname = Path.GetDirectoryName(desiredPath)

    Dim filePath = desiredPath

    Dim i as Integer = 1
    While(IO.File.Exists(filePath))
      filePath = Path.Combine(dirname, filename & "_" & i & ext)
      i += 1
    End While

    Return filePath
End Function

You'd hence use it like:

    'want to move to c:\temp\photo.png but it might exist
    Dim dest = "c:\temp\photo.png"

    Dim actualDest = GetRelatedNonExistantFilepath(dest)

    'move file to actual dest
    IO.FIle.Move(sourcePath, actualDest)


问:
Npm install keeps on showing on other device as soon as a dependency is installed
My problem is that whenever I install any dependency using npm install --save then the dependency gets installed but, after I push my code on git and someone else pulls the code, he faces the issue that dependency is missing. Then that person needs to do npm install again to install the dependency. How to solve this? What command should I run so that the dependency is added automatically to the other persons desktop?

答:
You could do that, but you should not be doing that. IF u want to do that then all what you have to do is to track the node_modules folder from git, however again this is extremely not recommended.

The normal flow is to do what you exactly did, you declare the packages, and later anyone that wants to work on the project, they have to reinstall them.

There are many reasons that the normal flow is like what you described, and that it is not recommended to push node_modules to git, here are some of them:

pushing these modules will make the repo size extremely large

pushing these modules will make working between different people harder, because each update will cause conflicts in files you do not own

pushing these might make your project not work across different operating systems, some packages when installed have os specific code

pushing these will make it later hard to integrate with many automatic tools like ci/cd flows/ static linets, and many other tools


问:
Rmarkdown rendering error in math with underscores
I am trying to display a formula in RMarkdown with two underscores (one inside a {}-bracket).
The preview in Rstudio works as expected and the formula is rendered correctly.
In the rendered document (HTML), the code is, however, not rendered correctly but instead the parts of the equation between the underscores are put into italics as if they were normal text and not within a formula environment.

An MWE is given by this

```<code>$$
w = \frac{1}{x_1}\sum y_{1}
$$
</code>```

which gets rendered to this

We see that the parts between the underscores are displayed in italic and the formula is not rendered but its source code is displayed.

A solution is to escape the underscores (breaks the preview, but gets rendered correctly)

```<code>$$
w = \frac{1}{x\_1}\sum y\_{1}
$$
</code>```

Note that only escaping one underscore works as well!

Is this expected behavior or a bug in the knitr engine?

Is there a solution that solves this in both the preview as well as the final document?

Edit

I use xaringan and xaringanthemer, not sure if this causes the error. Nonetheless, here is my header

```<code>title: "MWE"
output:
  xaringan::moon_reader:
    lib_dir: libs
    css: xaringan-themer.css
    nature:
      highlightStyle: github
      highlightLines: true
      countIncrementalSlides: false
</code>```

答:
The solution can be found in the official documentation:

Limitations:

1) The source code of a LaTeX math expression must be in one line, unless it is inside a pair of double dollar signs, in which case the starting $$ must appear in the very beginning of a line, followed immediately by a non-space character, and the ending $$ must be at the end of a line, led by a non-space character;

There should not be spaces after the opening $ or before the closing $.

Math does not work on the title slide (see #61 for a workaround).

So, just write:

```<code>$$w = \frac{1}{x_1}\sum y_{1}$$
</code>```

Body:
I am trying to display a formula in RMarkdown with two underscores (one inside a {}-bracket).
The preview in Rstudio works as expected and the formula is rendered correctly.
In the rendered document (HTML), the code is, however, not rendered correctly but instead the parts of the equation between the underscores are put into italics as if they were normal text and not within a formula environment.

An MWE is given by this

$$
w = \frac{1}{x_1}\sum y_{1}
$$

which gets rendered to this

We see that the parts between the underscores are displayed in italic and the formula is not rendered but its source code is displayed.

A solution is to escape the underscores (breaks the preview, but gets rendered correctly)

$$
w = \frac{1}{x\_1}\sum y\_{1}
$$

Note that only escaping one underscore works as well!

Is this expected behavior or a bug in the knitr engine?

Is there a solution that solves this in both the preview as well as the final document?

Edit

I use xaringan and xaringanthemer, not sure if this causes the error. Nonetheless, here is my header

title: "MWE"
output:
  xaringan::moon_reader:
    lib_dir: libs
    css: xaringan-themer.css
    nature:
      highlightStyle: github
      highlightLines: true
      countIncrementalSlides: false

Body:
The solution can be found in the official documentation:

Limitations:

1) The source code of a LaTeX math expression must be in one line, unless it is inside a pair of double dollar signs, in which case the starting $$ must appear in the very beginning of a line, followed immediately by a non-space character, and the ending $$ must be at the end of a line, led by a non-space character;

There should not be spaces after the opening $ or before the closing $.

Math does not work on the title slide (see #61 for a workaround).

So, just write:

$$w = \frac{1}{x_1}\sum y_{1}$$


问:
Phonegap: Set base href but still Include local JS/CSS/Images
I am making remote ajax calls in my phonegap index.html file and the response is an html snippet including relative references to javascript, css and image files on the remote server. In order for the relative references to function properly I include a <base href="http://myserver.com" /> tag in my index.html file.

This works as expected.

However, I would like to also include local CSS/JS/Image files stored in the www directory of my Phonegap Application. As I set the base href to http://myserver.com I can no longer include them using relative URLs (e.g. ).

My question is: How can I reference these files?

I am hoping that something like this will work (as I am still posting this question, it is not quite that simple):

Thanks in advance!

答:
Local images I reference with </p>

```<code>./assets/img/img.png
</code>```

<p>and then when I am getting something on the server I remove the starting dot. So when I am testing my application, I use an asset_path variable that either has the dot or not (in your case you could put the full URL). </p>

Body:
Local images I reference with

./assets/img/img.png

and then when I am getting something on the server I remove the starting dot. So when I am testing my application, I use an asset_path variable that either has the dot or not (in your case you could put the full URL).


问:
Android wear: keeping display on
On my watchface I need sometimes do wait a relative long time for data. During this wait cycle I think, it would be nice to keep the display on.

Unfortunately I didn't got it running with the same way I got it on my mobile phone (using PowerManager.WakeLock).

Can someone suggest me a right way to do that?

Thanks a lot

Luca

答:
Use Window flag: as long as this window is visible to the user, keep the device's screen turned on and bright.

```<code>getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

</code>```

If it doesn't work check this link Keep your app visible on Wear It might help you.

Title: Android wear: keeping display on

Body:
Use Window flag: as long as this window is visible to the user, keep the device's screen turned on and bright.

getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

If it doesn't work check this link Keep your app visible on Wear It might help you.


问:
zsh: abort pipenv shell
On attempts to install psycopg2, postgresql, django-Heroku, gunicorn, I am now getting the below error. Unable to successfully run pipenv shell or pipenv install; can't run python manage.py runserver, which means I can't open my project! Appreciate anyone who can reach out with fix for this issue.</p>

```<code>dyld: Library not loaded: @executable_path/../.Python
  Referenced from: /usr/local/Cellar/pipenv/2018.11.26_3/libexec/bin/python3.8
  Reason: image not found
zsh: abort      pipenv shell
</code>```

答:
i think pipenv in not properly installed. try
brew install pipenv # if you have brew installed
pip3 install pipenv # if you don't have brew installed

Title: zsh: abort pipenv shell

Body:
On attempts to install psycopg2, postgresql, django-Heroku, gunicorn, I am now getting the below error. Unable to successfully run pipenv shell or pipenv install; can't run python manage.py runserver, which means I can't open my project! Appreciate anyone who can reach out with fix for this issue.

dyld: Library not loaded: @executable_path/../.Python
  Referenced from: /usr/local/Cellar/pipenv/2018.11.26_3/libexec/bin/python3.8
  Reason: image not found
zsh: abort      pipenv shell


问:
Laravel unexpected redirects ( 302 )
I have started a new Laravel 5.2 project, using laravel new MyApp, and added authentication via php artisan make:auth. This is intended to be a members only website, where the first user is seeded, and creates the rest (no manual user creation/password reset/etc).

These are the routes I have currently defined:

```<code> Route::group(['middleware' => 'web'], function () {
  // Authentication Routes...
  Route::get( 'user/login',  ['as' => 'user.login',     'uses' => 'Auth\AuthController@showLoginForm']);
  Route::post('user/login',  ['as' => 'user.doLogin',   'uses' => 'Auth\AuthController@login'        ]);

  Route::group(['middleware' => 'auth'], function() {
    // Authenticated user routes
    Route::get( '/', ['as'=>'home', 'uses'=> 'HomeController@index']);
    Route::get( 'user/{uid?}', ['as' => 'user.profile',   'uses' => 'Auth\AuthController@profile' ]);
    Route::get( 'user/logout', ['as' => 'user.logout',    'uses' => 'Auth\AuthController@logout'  ]);
    Route::get( '/user/add',   ['as' => 'user.add',       'uses' => 'Auth\AuthController@showAddUser']);

    [...]
  });
});
</code>```

I can login just fine, however I'm experiencing some very "funky" behavior - when I try to logout ( via the built-in logout method that was created via artisan ), the page does a 302 redirect to home, and I am still logged in.

What's more, while almost all pages (not listed here) work as expected, user.add also produces a 302 to the home page.

Do note the homepage is declared to the AuthController as $redirectTo, if that makes any difference

I found out about the redirects via the debugbar.  Any idea on what to look for ?

答:
I too experienced this issue in the login page which worked fine previously. So thought have a look at the directory permissions and it resulted the following:

```<code>drwxr-xr-x  7 user user     4096 Jun 27  2019 storage
</code>```

So storage directory has 755 permission which means only the owner has write access, Since that directory owned by "user" others like laravel can't write into it.

Changing the directory to 777 with this cmd resolved my issue:

```<code>sudo chmod 777 -R PROJECT_PATH/storage
</code>```

The right way,

Since making that directory world-writable isn't the right way, make that directory owned by apache and set 775 to storage.. and it worked again.

```<code>sudo chown -R user:www-data PROJECT_PATH/storage
sudo chmod 775 -R PROJECT_PATH/storage
</code>```

Title: Laravel unexpected redirects ( 302 )

Body:
I have started a new Laravel 5.2 project, using laravel new MyApp, and added authentication via php artisan make:auth. This is intended to be a members only website, where the first user is seeded, and creates the rest (no manual user creation/password reset/etc).

These are the routes I have currently defined:

 Route::group(['middleware' => 'web'], function () {
  // Authentication Routes...
  Route::get( 'user/login',  ['as' => 'user.login',     'uses' => 'Auth\AuthController@showLoginForm']);
  Route::post('user/login',  ['as' => 'user.doLogin',   'uses' => 'Auth\AuthController@login'        ]);

  Route::group(['middleware' => 'auth'], function() {
    // Authenticated user routes
    Route::get( '/', ['as'=>'home', 'uses'=> 'HomeController@index']);
    Route::get( 'user/{uid?}', ['as' => 'user.profile',   'uses' => 'Auth\AuthController@profile' ]);
    Route::get( 'user/logout', ['as' => 'user.logout',    'uses' => 'Auth\AuthController@logout'  ]);
    Route::get( '/user/add',   ['as' => 'user.add',       'uses' => 'Auth\AuthController@showAddUser']);

    [...]
  });
});

I can login just fine, however I'm experiencing some very "funky" behavior - when I try to logout ( via the built-in logout method that was created via artisan ), the page does a 302 redirect to home, and I am still logged in.

What's more, while almost all pages (not listed here) work as expected, user.add also produces a 302 to the home page.

Do note the homepage is declared to the AuthController as $redirectTo, if that makes any difference

I found out about the redirects via the debugbar.  Any idea on what to look for ?

Body:
I too experienced this issue in the login page which worked fine previously. So thought have a look at the directory permissions and it resulted the following:

drwxr-xr-x  7 user user     4096 Jun 27  2019 storage

So storage directory has 755 permission which means only the owner has write access, Since that directory owned by "user" others like laravel can't write into it.

Changing the directory to 777 with this cmd resolved my issue:

sudo chmod 777 -R PROJECT_PATH/storage

The right way,

Since making that directory world-writable isn't the right way, make that directory owned by apache and set 775 to storage.. and it worked again.

sudo chown -R user:www-data PROJECT_PATH/storage
sudo chmod 775 -R PROJECT_PATH/storage


问:
Getting python2 error in nodejs installation in Ubuntu 20.04
I've updated to the new Ubuntu 20.04LTS version and all my node installations have gone. So to install node I have tried the following 2 methods:

1.sudo apt update

sudo apt install nodejs npm

curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -

sudo apt install nodejs

While installing nodejs I'm getting the error : nodejs : Depends: python2-minimal but it is not installable . Unable to correct problems, you have held broken packages.

screenshot

答:
You need to install python2. Steps in Ubuntu 20

sudo add-apt-repository universe

sudo apt-get update

sudo apt-get install python2
This will install python2 successfully. Now you can continue with normal nodejs installation


问:
Codemirror Clike Mode Doesn't seem to work
I am trying to use CodeMirror in my project with the clike mode for vertex and fragment snippets, but for some reason the syntax highlighting doesn't work for anything but numbers and string literals. The javascript syntax highlighter works fine.

I load all of the relevant files:

  <link   rel="stylesheet" href="js/third-party/codemirror/lib/codemirror.css">

```

<p>I create a textarea in the index.html:</p>

<pre class="lang-html prettyprint-override"><code>  <textarea id = "WEEE"></textarea>
</code>```

Then I initialize an editor:

```<code>    <script>
  const myTextarea = document.getElementById("WEEE");
  var editor = CodeMirror.fromTextArea(myTextarea, {
    lineNumbers: true,
    mode:   "clike"
  });
</script>
</code>```

The result is no syntax highlighting. The online examples clearly still work. CodeMirror.modes returns a list of modes, and clike seems to be fully loaded. What am I missing?

答:
For clike (c-like), we have different modes for different languages

For C

mode: "text/x-csrc"

For Cpp

mode: "text/x-c++src"

For Java

mode: "text/x-java"

For Objective-C

mode: "text/x-objectivec"

Body:
I am trying to use CodeMirror in my project with the clike mode for vertex and fragment snippets, but for some reason the syntax highlighting doesn't work for anything but numbers and string literals. The javascript syntax highlighter works fine.

I load all of the relevant files:

  <link   rel="stylesheet" href="js/third-party/codemirror/lib/codemirror.css">

I create a textarea in the index.html:

  <textarea id = "WEEE"></textarea>

Then I initialize an editor:

The result is no syntax highlighting. The online examples clearly still work. CodeMirror.modes returns a list of modes, and clike seems to be fully loaded. What am I missing?


问:
ls and dir doesn't show anything on debian 10
I've installed debian 10 32bit on a laptop and tried to use ls but then it prints nothing.
And when I use ls -a I get this:

```<code>root@acer-aspire-one:~# ls  //This prints nothing
root@acer-aspire-one:~# ls -a
.  ..  .bashrc  .profile
</code>```

And dir doesn't show anything either

```<code>root@acer-aspire-one:~# dir  //This prints nothing
root@acer-aspire-one:~# dir -a
.  ..  .bashrc  .profile
</code>```

答:
Your current path is ~, which is the current user's (root) home folder.
That folder is empty an a fresh installation apart from a few hidden files which ls -a is showing.

So ls is doing its job.

To make it list a specific path, for example the /, you can run ls / or first cd into that path like this:

```<code>cd /
ls
</code>```

Body:
I've installed debian 10 32bit on a laptop and tried to use ls but then it prints nothing.
And when I use ls -a I get this:

root@acer-aspire-one:~# ls  //This prints nothing
root@acer-aspire-one:~# ls -a
.  ..  .bashrc  .profile

And dir doesn't show anything either

root@acer-aspire-one:~# dir  //This prints nothing
root@acer-aspire-one:~# dir -a
.  ..  .bashrc  .profile

Body:
Your current path is ~, which is the current user's (root) home folder.
That folder is empty an a fresh installation apart from a few hidden files which ls -a is showing.

So ls is doing its job.

To make it list a specific path, for example the /, you can run ls / or first cd into that path like this:

cd /
ls


问:
RenderBox was not laid out: RenderPadding#882e9 relayoutBoundary=up5
I'm developing an app in flutter and this is my code:

Code 1:

Code 2:

Code 3:

The error I'm getting is:

答: Wrap your ListView inside a Container/SizedBox and provide height to it.</p>


问:
Caching variables in function with Jupyter
I have two cells. In the first one I set a variable and call a function,  and the second one contains the function definition which makes use of this variable.

When I refresh first cell, the output is always the same despite the value of variable changing. Only when I rerun the cell with the function definition does the output changes

```<code>In[]:  window=241
       window_t=count_frame_indeces2()
       window_t

Out[]: 241

In[]:  def count_frame_indeces2(window_f=window):
           return window_f
</code>```

Even if I change window to 22, output after rerunning this cell the output is still 241. How to avoid caching variable in this function?

答:
I found another solution using Facade pattern. I know it's redundant but I don't want to change definition of original function.

```<code>def count_frame_indeces2(window_f=window):
    return window_f

def count_frame():
    return count_frame_indeces2(window)
</code>```

Body:
I have two cells. In the first one I set a variable and call a function,  and the second one contains the function definition which makes use of this variable.

When I refresh first cell, the output is always the same despite the value of variable changing. Only when I rerun the cell with the function definition does the output changes

In[]:  window=241
       window_t=count_frame_indeces2()
       window_t

Out[]: 241

In[]:  def count_frame_indeces2(window_f=window):
           return window_f

Even if I change window to 22, output after rerunning this cell the output is still 241. How to avoid caching variable in this function?

Body:
I found another solution using Facade pattern. I know it's redundant but I don't want to change definition of original function.

def count_frame_indeces2(window_f=window):
    return window_f

def count_frame():
    return count_frame_indeces2(window)


问:
Iterate through dictionary returns None even the value was found
I am trying to get the values from data but the function below always give me None. I included the print inside the loop so that I could actually see that the condition is correct, not sure why its returning None instead. But the value being printed is correct.

```<code>data = {
    'test1': {
        'test1.1': {
            'a': 'a',
            'b': 'b'
        }
    },
    'test2': {
        'test2.1': {
            'test2.2': {
                'c': 'c',
                'd': 'd'
            }
        },
        'test_list': [1,2,3]
    }
}

def get_dict(key, dict_data):
    for k, v in dict_data.items():
        if k == key and isinstance(v, dict):
            print(v)
            return v
        else:
            if isinstance(v, dict):
                return get_dict(key, v) # <-- added return, same result
</code>```

get_dict('test1', data) returns OK

get_dict('test1.1', data) returns None but shoud have {'a': 'a', 'b': 'b'}

get_dict('test2', data) returns OK

get_dict('test2.1', data) returns None but should return {'test2.2': {'c': 'c', 'd': 'd'}}

答:
You should continue to look into other dicts as well.

The code below assumes no hierarchy:

def get_dict(key, dict_data):
    for k, v in dict_data.items():
        if k == key and isinstance(v, dict):
            return v
        elif isinstance(v, dict):
            ret = get_dict(key, v)
            if ret is not None:
                return ret
    return None
```

Body:
I am trying to get the values from data but the function below always give me None. I included the print inside the loop so that I could actually see that the condition is correct, not sure why its returning None instead. But the value being printed is correct.

data = {
    'test1': {
        'test1.1': {
            'a': 'a',
            'b': 'b'
        }
    },
    'test2': {
        'test2.1': {
            'test2.2': {
                'c': 'c',
                'd': 'd'
            }
        },
        'test_list': [1,2,3]
    }
}

def get_dict(key, dict_data):
    for k, v in dict_data.items():
        if k == key and isinstance(v, dict):
            print(v)
            return v
        else:
            if isinstance(v, dict):
                return get_dict(key, v) # <-- added return, same result

get_dict('test1', data) returns OK

get_dict('test1.1', data) returns None but shoud have {'a': 'a', 'b': 'b'}

get_dict('test2', data) returns OK

get_dict('test2.1', data) returns None but should return {'test2.2': {'c': 'c', 'd': 'd'}}


问:
How to set custom colors for components (toolbar, seekbar,actionbar, etc.) when switching day/night mode?
I'm trying to change some colors of the components of my application by setting a custom theme for day mode and night mode, like this:

in values/styles.xml (day mode):

```<code><resources>

    <!-- Base application theme. -->
    <style name="MyTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
...
</resources>
</code>```

Same file in values/styles.xml (night)

I want to change the color of some parts of the UI (seekbar bar, toolbar, action bar title, floating buttons etc.) but I don't know which color corresponds to each element and I'm kinda going crazy googling here and there for tricky solutions for any component I need to change the color too. Is there any guideline or good visual example on where to check all of this? For instance, right now it's taking a long time for me to figure out how to change the popupmenu background or the actionbar menu background since there's no attributes in the menu files. I'm new to android development so any kind of guidance regarding this would be very welcomed.

答:
You used Theme.MaterialComponents.DayNight.... where DayNight is more of a adaptive dynamic theme which changes to material design default color. If you need more control to color and styles, do as follows:

Your Day theme inside values/styles.xml should extend from Theme.MaterialComponents.Light.DarkActionBar

Your Night theme inside values-night/styles.xml should extend from Theme.MaterialComponents as it is well-suited for the Dark Mode.

I want to change the color of some parts of the UI (seekbar bar, toolbar, action bar title, floating buttons etc.)

Regarding this, if you want app-wide changes then you can follow this method of styling(almost all views styling can be done this way):

```<code><resources>
            <!-- Base application theme. -->
            <style name="MyTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
                <!-- Customize your theme here. -->
                <item name="seekBarStyle">@style/MySeekBarStyle</item>
                <item name="toolbarStyle">@style/MyToolBarStyle</item>
                <item name="actionBarStyle">@style/MyActionBarStyle</item>
              <item name="floatingActionButtonStyle">@MyFloatingActionButtonStyle</item>
                <!--   a sample toolbar styling, choose parent with care -->
                <!--    your AppTheme inheriting from MaterialComponents but toolbar
                <!--   inheriting from platform theme-->
                <!--    may case weird visual effects-->
    <style name="MyToolBarStyle" parent="Widget.MaterialComponents.Toolbar">
            <item name="titleTextColor">@color/lightWhite</item>
            <item name="subtitleTextColor">@color/lightWhite</item>
        </style>
        </resources>
</code>```

If you want to style each for eg. ToolBar differently, you can use style="@style/MyToolBarStyle" attributes in your layout files to give each of them different shape, colour and other material effects as you want.

About Colors:
Normally, you can play with these colour attributes in your styles.xml to change the complete look and feel of your app.

```<code> <!-- primary colour of your brand and its variants -->
        <item name="colorPrimary">@color/colorPrimary700</item>
        <item name="colorPrimaryDark">@color/colorPrimary900</item>
        <item name="colorPrimaryVariant">@color/colorPrimary500</item>

        <!-- colour which contrasts from your primary colour -->
        <item name="colorAccent">@color/colorAccent</item>

        <!--secondary colour of your brand and its variants -->
        <item name="colorSecondary">@color/colorSecondary700</item>
        <item name="colorSecondaryVariant">@color/colorSecondary500</item>

        <!--background color for your root layout file -->
        <item name="android:colorBackground">@android:color/white</item>

        <!--background color of children view -->
        <item name="colorSurface">@color/lightWhite</item>

        <!--color to show error mostly it will be red or orange
        <item name="colorError">@color/colorErrorAlternate</item>

        <!-- These are colors which constrasts colors defined for -->
        <!-- primary, secondary, bg, surface, error respectively. -->
        <!-- For eg: TextViews in Toolbar colored with colorPrimary -->
        <!-- will use colorOnPrimary as their text color -->

        <item name="colorOnPrimary">@color/lightWhite</item>
        <item name="colorOnSecondary">@color/lightDark</item>
        <item name="colorOnBackground">@color/lightDark</item>
        <item name="colorOnSurface">@color/lightDark</item>
        <item name="colorOnError">@color/lightDark</item>
</code>```

Important Links:

Official Material Design guide for designing dark theme

Official Material Design guide for developing dark theme

Using switchpreference to switch theme

Nick Butcher's Medium Blog : you will know more about colours here

Body:
I'm trying to change some colors of the components of my application by setting a custom theme for day mode and night mode, like this:

in values/styles.xml (day mode):

<resources>

Body:
You used Theme.MaterialComponents.DayNight.... where DayNight is more of a adaptive dynamic theme which changes to material design default color. If you need more control to color and styles, do as follows:

Your Day theme inside values/styles.xml should extend from Theme.MaterialComponents.Light.DarkActionBar

Your Night theme inside values-night/styles.xml should extend from Theme.MaterialComponents as it is well-suited for the Dark Mode.

I want to change the color of some parts of the UI (seekbar bar, toolbar, action bar title, floating buttons etc.)

Regarding this, if you want app-wide changes then you can follow this method of styling(almost all views styling can be done this way):

<resources>
            <!-- Base application theme. -->
            <style name="MyTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
                <!-- Customize your theme here. -->
                <item name="seekBarStyle">@style/MySeekBarStyle</item>
                <item name="toolbarStyle">@style/MyToolBarStyle</item>
                <item name="actionBarStyle">@style/MyActionBarStyle</item>
              <item name="floatingActionButtonStyle">@MyFloatingActionButtonStyle</item>
                <!--   a sample toolbar styling, choose parent with care -->
                <!--    your AppTheme inheriting from MaterialComponents but toolbar
                <!--   inheriting from platform theme-->
                <!--    may case weird visual effects-->
    <style name="MyToolBarStyle" parent="Widget.MaterialComponents.Toolbar">
            <item name="titleTextColor">@color/lightWhite</item>
            <item name="subtitleTextColor">@color/lightWhite</item>
        </style>
        </resources>

If you want to style each for eg. ToolBar differently, you can use style="@style/MyToolBarStyle" attributes in your layout files to give each of them different shape, colour and other material effects as you want.

About Colors:
Normally, you can play with these colour attributes in your styles.xml to change the complete look and feel of your app.

 <!-- primary colour of your brand and its variants -->
        <item name="colorPrimary">@color/colorPrimary700</item>
        <item name="colorPrimaryDark">@color/colorPrimary900</item>
        <item name="colorPrimaryVariant">@color/colorPrimary500</item>

        <!-- colour which contrasts from your primary colour -->
        <item name="colorAccent">@color/colorAccent</item>

        <!--secondary colour of your brand and its variants -->
        <item name="colorSecondary">@color/colorSecondary700</item>
        <item name="colorSecondaryVariant">@color/colorSecondary500</item>

        <!--background color for your root layout file -->
        <item name="android:colorBackground">@android:color/white</item>

        <!--background color of children view -->
        <item name="colorSurface">@color/lightWhite</item>

        <!--color to show error mostly it will be red or orange
        <item name="colorError">@color/colorErrorAlternate</item>

        <!-- These are colors which constrasts colors defined for -->
        <!-- primary, secondary, bg, surface, error respectively. -->
        <!-- For eg: TextViews in Toolbar colored with colorPrimary -->
        <!-- will use colorOnPrimary as their text color -->

        <item name="colorOnPrimary">@color/lightWhite</item>
        <item name="colorOnSecondary">@color/lightDark</item>
        <item name="colorOnBackground">@color/lightDark</item>
        <item name="colorOnSurface">@color/lightDark</item>
        <item name="colorOnError">@color/lightDark</item>

Important Links:

Official Material Design guide for designing dark theme

Official Material Design guide for developing dark theme

Using switchpreference to switch theme

Nick Butcher's Medium Blog : you will know more about colours here


问:
Cross-referencing within documents with R Markdown
I have a very simple document in R Markdown. Here is the code:

```<code>---
title: "Untitled"
output: html_document
---

# R Markdown {#r-mkdw}

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. I want to cross-reference the Header of this text with \@ref(r-mkdw).
</code>```

But the cross-reference as the manual specifies doesn't work.

答:
The "standard" rmarkdown package with html_output does not support cross referencing. You have to use, e.g. the package bookdown which provides the format html_document2.

```<code>---
title: "Untitled"
output:
  bookdown::html_document2
---
</code>```

Body:
I have a very simple document in R Markdown. Here is the code:

---
title: "Untitled"
output: html_document
---

# R Markdown {#r-mkdw}

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. I want to cross-reference the Header of this text with \@ref(r-mkdw).

But the cross-reference as the manual specifies doesn't work.

Body:
The "standard" rmarkdown package with html_output does not support cross referencing. You have to use, e.g. the package bookdown which provides the format html_document2.

---
title: "Untitled"
output:
  bookdown::html_document2
---


问:
how to stop function save in jquery
When Save button clicked, I want to make sure date exist or not.

I tried to use return false , e.stopPropagation() , e.stopImmediatePropagation() and none of those works to stop execute saveEvent. As you can see in my example, button save  will always be executed. I want to stop that stop the SaveEvent . Could you help?

```<code>       $('#btnSave').click(function () {

                var StartDate = $('#txtStart').val();

                $.ajax({
                    type: "POST",
                    url: "/Home/Checkdate",
                    data: '{StartDate: "' + StartDate + '" }',

                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        var message = $("#message");
                        if (response) {
                            //Email available.
                            message.css("color", "green");
                            message.html(" date is not exist ");
                        }
                        else {
                            message.css("color", "red");
                            message.html("date existe ");
                            alert('date existe');

                            return;

                        }

                    }
                });

         var data = {

                    EventID: $('#hdEventID').val(),
                    EventTitle: $('#txtSubject').val().trim(),
                    StartDate: $('#txtStart').val().trim(),
                    EndDate: $('#chkIsFullDay').is(':checked') ? null : $('#txtEnd').val().trim(),
                    EventDescription: $('#txtDescription').val(),
                    ThemeColor: $('#ddThemeColor').val(),
                    IsFullDay: $('#chkIsFullDay').is(':checked')
                }

                    SaveEvent(data);

                // call function for submit data to the server
            })
</code>```

答:
The  call to SaveEvent needs to be inside the if (response) { block inside your "success" callback by the looks of it.

It seems that is the place where you verify the status of the date, so that should also be the place where you run the Save command.

Title: how to stop function save in jquery

Body:
When Save button clicked, I want to make sure date exist or not.

I tried to use return false , e.stopPropagation() , e.stopImmediatePropagation() and none of those works to stop execute saveEvent. As you can see in my example, button save  will always be executed. I want to stop that stop the SaveEvent . Could you help?

       $('#btnSave').click(function () {

                var StartDate = $('#txtStart').val();

                $.ajax({
                    type: "POST",
                    url: "/Home/Checkdate",
                    data: '{StartDate: "' + StartDate + '" }',

                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        var message = $("#message");
                        if (response) {
                            //Email available.
                            message.css("color", "green");
                            message.html(" date is not exist ");
                        }
                        else {
                            message.css("color", "red");
                            message.html("date existe ");
                            alert('date existe');

                            return;

                        }

                    }
                });

         var data = {

                    EventID: $('#hdEventID').val(),
                    EventTitle: $('#txtSubject').val().trim(),
                    StartDate: $('#txtStart').val().trim(),
                    EndDate: $('#chkIsFullDay').is(':checked') ? null : $('#txtEnd').val().trim(),
                    EventDescription: $('#txtDescription').val(),
                    ThemeColor: $('#ddThemeColor').val(),
                    IsFullDay: $('#chkIsFullDay').is(':checked')
                }

                    SaveEvent(data);

                // call function for submit data to the server
            })


问:
How do we calculate difference and percent difference between two columns in tableau
]Difference and percent Difference must be calculated.

I cannot do Apr20-MAy20 because it is not always the same. I need to show the current month and previous month

So I did a relative filter to just show the current month and previous month.
So the difference of two columns should automatically change when the month changes.

Now how do I get the same month of prior year, how do I filter ?

I also need to calculate the difference of current year same month and previous year same month.

Thank you in advance for any help!

When I do table across difference, the difference value is overwriting the existing May and Apr month values as the below screen shot, how to show the difference in another column

Currently:

Below is Expected:

答:
Sounds like you should create a custom filter for the dates. You want:

This month this year

This month last year

Last month this year

There are a number of ways you could do this. I'll give one example and will assume there aren't any future dates in your data set.

```<code>[DateFilter]: DATETRUNC('month',[YourDateField])>=DATETRUNC('month',DATEADD('month',-1,TODAY())) OR DATETRUNC('month',[YourDateField])=DATETRUNC('month',DATEADD('year',-1,TODAY()))
</code>```

Put the to the filters shelf, set to True, and it should keep the months you want.

Then you can just use the standard table calculations to calculate Difference and Percent Difference.

Note, the formula isn't tested, just typed directly into here, let me know if it doesn't work

Based on your comments look at creating separate calculations for to YoY / MoM / etc calculation. That also means creating calculated fields to isolate the Current Month, Previous Month, etc.

For example, the current month:

```<code>[isCM]: DATETRUNC('month',[YourDateField]) = DATETRUNC('month',TODAY())
</code>```

The previous month:

```<code>[isPM]: DATETRUNC('month',[YourDateField]) = DATETRUNC('month',DATEADD('month',-1,TODAY()))
</code>```

Then month on month, something like:

```<code>[MoM]: (SUM([Measure])*INT([isCM]))/(SUM([Measure])*INT([isPM]))
</code>```

To make your table check this article about using the placeholder technique to create tables in Tableau

Body:
Sounds like you should create a custom filter for the dates. You want:

This month this year

This month last year

Last month this year

There are a number of ways you could do this. I'll give one example and will assume there aren't any future dates in your data set.

[DateFilter]: DATETRUNC('month',[YourDateField])>=DATETRUNC('month',DATEADD('month',-1,TODAY())) OR DATETRUNC('month',[YourDateField])=DATETRUNC('month',DATEADD('year',-1,TODAY()))

Put the to the filters shelf, set to True, and it should keep the months you want.

Then you can just use the standard table calculations to calculate Difference and Percent Difference.

Note, the formula isn't tested, just typed directly into here, let me know if it doesn't work

Based on your comments look at creating separate calculations for to YoY / MoM / etc calculation. That also means creating calculated fields to isolate the Current Month, Previous Month, etc.

For example, the current month:

[isCM]: DATETRUNC('month',[YourDateField]) = DATETRUNC('month',TODAY())

The previous month:

[isPM]: DATETRUNC('month',[YourDateField]) = DATETRUNC('month',DATEADD('month',-1,TODAY()))

Then month on month, something like:

[MoM]: (SUM([Measure])*INT([isCM]))/(SUM([Measure])*INT([isPM]))

To make your table check this article about using the placeholder technique to create tables in Tableau


问:
Merging all the colunms in R with colunm names
I have the following data

```<code>> df
X1  X2  X3
1   3   4
1   0   0
1   1   0
</code>```

and I want to merge all the column so that the final output will be

```<code>new colName
1     X1
1     X1
1     X1
3     X2
0     X2
1     X2
4     X3
0     X3
0     X3
</code>```

答:
You can try stack

```<code>> setNames(stack(df),c("new","colName"))
  new colName
1   1      X1
2   1      X1
3   1      X1
4   3      X2
5   0      X2
6   1      X2
7   4      X3
8   0      X3
9   0      X3
</code>```

Data

```<code>> dput(df)
structure(list(X1 = c(1L, 1L, 1L), X2 = c(3L, 0L, 1L), X3 = c(4L,
0L, 0L)), class = "data.frame", row.names = c(NA, -3L))
</code>```

Body:
I have the following data

> df
X1  X2  X3
1   3   4
1   0   0
1   1   0

and I want to merge all the column so that the final output will be

new colName
1     X1
1     X1
1     X1
3     X2
0     X2
1     X2
4     X3
0     X3
0     X3

Body:
You can try stack

> setNames(stack(df),c("new","colName"))
  new colName
1   1      X1
2   1      X1
3   1      X1
4   3      X2
5   0      X2
6   1      X2
7   4      X3
8   0      X3
9   0      X3

Data

> dput(df)
structure(list(X1 = c(1L, 1L, 1L), X2 = c(3L, 0L, 1L), X3 = c(4L,
0L, 0L)), class = "data.frame", row.names = c(NA, -3L))


问:
Redirect to a script that uses /dev/tty
I am writing a git hook that might require human input. According to this answer one has to use exec < /dev/tty in that script. This does the job, but now there is no possibility to redirect the standard output to that hook (for test purposes). I guess the problem can be narrowed down to a question: how to send a message to /dev/tty in such a way that another process will read it? Not sure if this is even possible.

Here is the minimum reproducible example:

# file: target.sh

exec < /dev/tty # we want to use /dev/tty
read -p  "Type a message: " message
echo "The message ${message}"

```

<p>I tried several solutions like this:</p>

<pre class="lang-sh prettyprint-override"><code>echo -e "foo\n"| tee /dev/tty | source target.sh
</code>```

And it actually prints the message in the console after the read prompt, but the message variable remains unset. Is there any way to fix it?

答:
You could make the input file an optional parameter:

```<code>#!/bin/bash

input_file=${1:-/dev/tty}
read -p  "Type a message: " message < "${input_file}"
echo "The message ${message}"

# other stuff ...
</code>```

Now test the command like this:

```<code>your_script
your_script <(echo foo)
some_cmd | your_script
some_cmd | your_script <(echo foo)
</code>```

PS: The syntax <(echo foo) which I'm using is a so called process substitution.

Title: Redirect to a script that uses /dev/tty

Body:
I am writing a git hook that might require human input. According to this answer one has to use exec < /dev/tty in that script. This does the job, but now there is no possibility to redirect the standard output to that hook (for test purposes). I guess the problem can be narrowed down to a question: how to send a message to /dev/tty in such a way that another process will read it? Not sure if this is even possible.

Here is the minimum reproducible example:

# file: target.sh

exec < /dev/tty # we want to use /dev/tty
read -p  "Type a message: " message
echo "The message ${message}"

I tried several solutions like this:

echo -e "foo\n"| tee /dev/tty | source target.sh

And it actually prints the message in the console after the read prompt, but the message variable remains unset. Is there any way to fix it?

Body:
You could make the input file an optional parameter:

#!/bin/bash

input_file=${1:-/dev/tty}
read -p  "Type a message: " message < "${input_file}"
echo "The message ${message}"

# other stuff ...

Now test the command like this:

your_script
your_script <(echo foo)
some_cmd | your_script
some_cmd | your_script <(echo foo)

PS: The syntax <(echo foo) which I'm using is a so called process substitution.


问:
Can someone please point out what's wrong here
I made sure to have all the exceptions I think are needed but it keeps giving me this error:

exception FileNotFoundException has already been caught
catch(FileNotFoundException fnfe)

```<code>public class SNIDDb
{
  private char delimiter;
  private String name;
  private BufferedReader br;

  public SNIDDb(String name, char delimiter)
  {
    this.name=name;
    this.delimiter=delimiter;
    try
    {
      FileReader fr= new FileReader(name);
      br= new BufferedReader(fr);
    }
    catch(IOException i)
    {
      System.out.println(i.getMessage());
    }
    catch(FileNotFoundException fnfe)
    {
      System.out.print(fnfe.getMessage());
    }
  }
</code>```

答:
If you look at the definition of FileNotFoundException you will see it is

```<code>public class FileNotFoundException extends IOException {
</code>```

So by catching the base class IOException you are already, in effect, catching the derived exception, hence the error you are seeing.

However, if you further look at the FileReader constructor you are calling, it only throws FileNotFoundException so you actually don't need to catch IOException in and can remove that catch clause and fix your error.

Body:
I made sure to have all the exceptions I think are needed but it keeps giving me this error:

exception FileNotFoundException has already been caught
catch(FileNotFoundException fnfe)

public class SNIDDb
{
  private char delimiter;
  private String name;
  private BufferedReader br;

  public SNIDDb(String name, char delimiter)
  {
    this.name=name;
    this.delimiter=delimiter;
    try
    {
      FileReader fr= new FileReader(name);
      br= new BufferedReader(fr);
    }
    catch(IOException i)
    {
      System.out.println(i.getMessage());
    }
    catch(FileNotFoundException fnfe)
    {
      System.out.print(fnfe.getMessage());
    }
  }

Body:
If you look at the definition of FileNotFoundException you will see it is

public class FileNotFoundException extends IOException {

So by catching the base class IOException you are already, in effect, catching the derived exception, hence the error you are seeing.

However, if you further look at the FileReader constructor you are calling, it only throws FileNotFoundException so you actually don't need to catch IOException in and can remove that catch clause and fix your error.


问:
How does .reduce work with recursive functions in that situation?
I'm trying to understand how .reduce works with nested/recursive functions. In the example below, the console.logs show that the .reduce first compiles the functions and then runs them. What I can't understand is how that happens, does it just create a giant nested function, or does it do something else?
From what I've seen and read, people say it creates a composed function which directly substitutes: e.g. func3(acc(...args), where acc = func2(func1(...args)); but then won't the result be func3(func2(func1(...args))(...args))? The only solution I can think of is that the first (...args) disappears in the substitution of acc, so it becomes func3(func2(func1(...args))).

var numOfCallsToPipeFunction = 0;
var headerApplied = false;

// const pipe = (f, g) => (...args) => g(f(...args))
const pipe = function(f,g) {

  numOfCallsToPipeFunction++
  console.log('___________________________________________\n')
  console.log(" Call# " + numOfCallsToPipeFunction + " to pipe() function:");
  console.log('___________________________________________\n')

  console.log("  pipe() >>> 'f' input Parameter: "+f.name+"()\n")
  console.log("  pipe() >>> 'g' input Parameter: "+ g.name+"()\n")

    return function (...args) {
    if (!headerApplied) {
      console.log('=======================================================================\n')
       headerApplied = true
    }
    let retResult = g(f(...args))

    console.log("Results after running function(s): \n");
    console.log(f.name,g.name);
    console.log(" \n");
    console.log('Returned Result: ', retResult);
    console.log("\n");

    return retResult
  }
}
const startPipe  = function (...fns) {
   console.log('_______________________________________________________\n')
  console.log("StartPipe(): Input Parameters (i.e., ...fns)" )
  console.log('_______________________________________________________\n')
  console.log(fns.map(x=>x.name))
  return fns.reduce(pipe);
}
startPipe(
  func1,
  func2,
  func3,
  func4,
)(1, 1)

function func1(num1, num2) {
   console.log('________________________________________________\n')
   console.log("Executing compose function with Data (...args): ")
   console.log('________________________________________________\n')
  console.log(`func1 called, applying:  ${num1} + ${num2}`)
  return num1 + num2
}

function func2(num1) {
  console.log(`func2 called, applying:  ${num1} * 2`)
  return num1*2
}

function func3(num1) {

   console.log(`func3 called, applying:  ${num1} - 2`)
   return num1-1
}

function func4(num1) {

 console.log(`func4 called, applying:  ${num1} + 2`)
 return num1+2
}```

答:
After the reduce is finished, you get a composed function where each function, when executed, calls a reference to the last function in the iteration.  It does not execute the function(s), just returns the function as an object.

This is technically not recursion.  None of the functions are calling themselves.

The reduce functions basically like this snippet here:

// an "unwrapped" version of the reduce iteration
f1 = func1
g1 = func2
acc1 = (x,y) =>
  g1(f1(x,y))

f2 = acc1
g2 = func3
acc2 = (x,y) =>
  g2(f2(x,y))

f3 = acc2
g3 = func4
acc3 = (x,y) =>
   g3(f3(x,y))

// acc3 has the resulting function
console.log("typeof acc3:", typeof acc3)
console.log("variable acc3 is a function object:", acc3)
// nothing has been called yet, you just have a function object that has chained calls to the other ones

console.log("calling acc3:")
console.log("result of calling acc3:", acc3(1,1))
console.log("\n\nI can call acc2:")
console.log("result of calling acc2:", acc2(1,1))

// how the spread operator functions:
function spread(...args) {
  console.log(args)
  console.log(...args)
}

spread(1,2,3,4)

function func1(num1, num2) {
   console.log('________________________________________________\n')
   console.log("Executing compose function with Data (...args): ")
   console.log('________________________________________________\n')
  console.log(`func1 called, applying:  ${num1} + ${num2}`)
  return num1 + num2
}

function func2(num1) {
  console.log(`func2 called, applying:  ${num1} * 2`)
  return num1*2
}

function func3(num1) {

   console.log(`func3 called, applying:  ${num1} - 2`)
   return num1-1
}

function func4(num1) {

 console.log(`func4 called, applying:  ${num1} + 2`)
 return num1+2
}```


问:
how to use XPath with XDocument?
There is a similar question, but it seems that the solution didn't work out in my case: Weirdness with XDocument, XPath and namespaces

Here is the XML I am working with:

```<code><?xml version="1.0" encoding="utf-8"?>
<Report Id="ID1" Type="Demo Report" Created="2011-01-01T01:01:01+11:00" Culture="en" xmlns="http://demo.com/2011/demo-schema">
    <ReportInfo>
        <Name>Demo Report</Name>
        <CreatedBy>Unit Test</CreatedBy>
    </ReportInfo>
</Report>
</code>```

And below is the code that I thought it should be working but it didn't...

```<code>XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable());
xnm.AddNamespace(String.Empty, "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/Report/ReportInfo/Name", xnm) == null);
</code>```

Does anyone have any ideas?
Thanks.

答:
XPath 1.0, which is what MS implements, does not have the idea of a default namespace.  So try this:</p>

```<code>XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable());
xnm.AddNamespace("x", "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/x:Report/x:ReportInfo/x:Name", xnm) == null);
</code>```

Title: how to use XPath with XDocument?

Body:
There is a similar question, but it seems that the solution didn't work out in my case: Weirdness with XDocument, XPath and namespaces

Here is the XML I am working with:

<?xml version="1.0" encoding="utf-8"?>
<Report Id="ID1" Type="Demo Report" Created="2011-01-01T01:01:01+11:00" Culture="en" xmlns="http://demo.com/2011/demo-schema">
    <ReportInfo>
        <Name>Demo Report</Name>
        <CreatedBy>Unit Test</CreatedBy>
    </ReportInfo>
</Report>

And below is the code that I thought it should be working but it didn't...

XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable());
xnm.AddNamespace(String.Empty, "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/Report/ReportInfo/Name", xnm) == null);

Does anyone have any ideas?
Thanks.

Body:
XPath 1.0, which is what MS implements, does not have the idea of a default namespace.  So try this:

XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable());
xnm.AddNamespace("x", "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/x:Report/x:ReportInfo/x:Name", xnm) == null);


问:
How to copy InMemoryUploadedFile object to disk
I am trying to catch a file sent with form and perform some operations on it before it will be saved. So I need to create a copy of this file in temp directory, but I don't know how to reach it. Shutil's functions fail to copy this file, since there is no path to it. So is there a way to do this operation in some other way ?

My code :

```<code>    image = form.cleaned_data['image']
    temp = os.path.join(settings.PROJECT_PATH, 'tmp')
    sourceFile = image.name # without .name here it wasn't working either
    import shutil
    shutil.copy(sourceFile, temp)
</code>```

Which raises :

Exception Type: IOError at /

Exception Value: (2, 'No such file or directory')

And the debug :

```<code>#  (..)\views.py in function

  67. sourceFile = image.name
  68. import shutil
  69. shutil.copy2(sourceFile, temp) ...

# (..)\Python26\lib\shutil.py in copy2

  92. """Copy data and all stat info ("cp -p src dst").
  93.
  94. The destination may be a directory.
  95.
  96. """
  97. if os.path.isdir(dst):
  98. dst = os.path.join(dst, os.path.basename(src))
  99. copyfile(src, dst) ...
 100. copystat(src, dst)
 101.

▼ Local vars
Variable    Value
dst
u'(..)\\tmp\\myfile.JPG'
src
u'myfile.JPG'
# (..)\Python26\lib\shutil.py in copyfile

  45. """Copy data from src to dst"""
  46. if _samefile(src, dst):
  47. raise Error, "`%s` and `%s` are the same file" % (src, dst)
  48.
  49. fsrc = None
  50. fdst = None
  51. try:
  52. fsrc = open(src, 'rb') ...
  53. fdst = open(dst, 'wb')
  54. copyfileobj(fsrc, fdst)
  55. finally:
  56. if fdst:
  57. fdst.close()
  58. if fsrc:

▼ Local vars
Variable    Value
dst
u'(..)\\tmp\\myfile.JPG'
fdst
None
fsrc
None
src
u'myfile.JPG'
</code>```

答:
This is how I tried to save the file locally    </p>

```<code>    file_object = request.FILES["document_file"]
    file_name = str(file_object)
    print(f'[INFO] File Name: {file_name}')
    with open(file_name, 'wb+') as f:
        for chunk in file_object.chunks():
            f.write(chunk)
</code>```

Body:
I am trying to catch a file sent with form and perform some operations on it before it will be saved. So I need to create a copy of this file in temp directory, but I don't know how to reach it. Shutil's functions fail to copy this file, since there is no path to it. So is there a way to do this operation in some other way ?

My code :

    image = form.cleaned_data['image']
    temp = os.path.join(settings.PROJECT_PATH, 'tmp')
    sourceFile = image.name # without .name here it wasn't working either
    import shutil
    shutil.copy(sourceFile, temp)

Which raises :

Exception Type: IOError at /

Exception Value: (2, 'No such file or directory')

And the debug :

#  (..)\views.py in function

  67. sourceFile = image.name
  68. import shutil
  69. shutil.copy2(sourceFile, temp) ...

# (..)\Python26\lib\shutil.py in copy2

  92. """Copy data and all stat info ("cp -p src dst").
  93.
  94. The destination may be a directory.
  95.
  96. """
  97. if os.path.isdir(dst):
  98. dst = os.path.join(dst, os.path.basename(src))
  99. copyfile(src, dst) ...
 100. copystat(src, dst)
 101.

▼ Local vars
Variable    Value
dst
u'(..)\\tmp\\myfile.JPG'
src
u'myfile.JPG'
# (..)\Python26\lib\shutil.py in copyfile

  45. """Copy data from src to dst"""
  46. if _samefile(src, dst):
  47. raise Error, "`%s` and `%s` are the same file" % (src, dst)
  48.
  49. fsrc = None
  50. fdst = None
  51. try:
  52. fsrc = open(src, 'rb') ...
  53. fdst = open(dst, 'wb')
  54. copyfileobj(fsrc, fdst)
  55. finally:
  56. if fdst:
  57. fdst.close()
  58. if fsrc:

▼ Local vars
Variable    Value
dst
u'(..)\\tmp\\myfile.JPG'
fdst
None
fsrc
None
src
u'myfile.JPG'

Body:
This is how I tried to save the file locally

    file_object = request.FILES["document_file"]
    file_name = str(file_object)
    print(f'[INFO] File Name: {file_name}')
    with open(file_name, 'wb+') as f:
        for chunk in file_object.chunks():
            f.write(chunk)


问:
Cannot use import statement outside a module with Babel configured
I am trying to use ES6 imports with Express Node.js. I know that Node.js supports CommonJS only so I have configured Babel with Webpack 4 like such:

```<code>{
      test: /\.m?js$/,
      exclude: ['/node_modules/', /\bcore-js\b/, /\bwebpack\/buildin\b/, /@babel\/runtime-corejs3/],
      use: {
        loader: 'babel-loader',
        options: {
          babelrc : false,
          sourceType : "unambiguous",
          presets : [
            ["@babel/preset-env", {
              modules : false,
              useBuiltIns : "usage",
              corejs : {
                version : "2",
              }
            }]
          ],
        }
      }
    },
</code>```

As a test to see if it works I updated my CommonJS require statements into ES6 imports like such:

```<code>import express from "express"
import api from "api/v1/index.api.js"

const expressRouter = express.Router();

expressRouter.get('/', async function (req, res)  {
});

export default expressRouter
</code>```

I believe having read this article that the above should just work. But on build, I still get the following error:

import express from "express"

^^^^^^

SyntaxError: Cannot use import statement outside a module

Is my babel-loader not working, or is there some other issue going on? Firstly not all my files are using ES6 imports - some are still using CommonJS require statements. I thought I'd try it on one file at a time to ensure it works which sadly it does not.

Any ideas on what to look at? I am using core-js 2.6.11 because version 3 causes problems with mini-css-extract-plugin

答: @babel/plugin-transform-modules-commonjs did work for me where I needed the some commonjs lib to be used for setting up the test infrastructure. Note to add it in babel.config.js</p>

Body:
I am trying to use ES6 imports with Express Node.js. I know that Node.js supports CommonJS only so I have configured Babel with Webpack 4 like such:

{
      test: /\.m?js$/,
      exclude: ['/node_modules/', /\bcore-js\b/, /\bwebpack\/buildin\b/, /@babel\/runtime-corejs3/],
      use: {
        loader: 'babel-loader',
        options: {
          babelrc : false,
          sourceType : "unambiguous",
          presets : [
            ["@babel/preset-env", {
              modules : false,
              useBuiltIns : "usage",
              corejs : {
                version : "2",
              }
            }]
          ],
        }
      }
    },

As a test to see if it works I updated my CommonJS require statements into ES6 imports like such:

import express from "express"
import api from "api/v1/index.api.js"

const expressRouter = express.Router();

expressRouter.get('/', async function (req, res)  {
});

export default expressRouter

I believe having read this article that the above should just work. But on build, I still get the following error:

import express from "express"

^^^^^^

SyntaxError: Cannot use import statement outside a module

Is my babel-loader not working, or is there some other issue going on? Firstly not all my files are using ES6 imports - some are still using CommonJS require statements. I thought I'd try it on one file at a time to ensure it works which sadly it does not.

Any ideas on what to look at? I am using core-js 2.6.11 because version 3 causes problems with mini-css-extract-plugin