问:
Regular Expression for matching parentheses
What is the regular expression for matching '(' in a string?

Following is the scenario :

I have a string

```<code>str = "abc(efg)";
</code>```

I want to split the string at '(' using regular expression.For that i am using

```<code>Arrays.asList(Pattern.compile("/(").split(str))
</code>```

But i am getting the following exception.

```<code>java.util.regex.PatternSyntaxException: Unclosed group near index 2
/(
</code>```

Escaping '(' doesn't seems to work.

答:
You can escape any meta-character by using a backslash, so you can match ( with the pattern
\(.

Many languages come with a build-in escaping function, for example, .Net's Regex.Escape or Java's Pattern.quote

Some flavors support \Q and \E, with literal text between them.

Some flavors (VIM, for example) match ( literally, and require \( for capturing groups.

See also: Regular Expression Basic Syntax Reference

Body:
What is the regular expression for matching '(' in a string?

Following is the scenario :

I have a string

str = "abc(efg)";

I want to split the string at '(' using regular expression.For that i am using

Arrays.asList(Pattern.compile("/(").split(str))

But i am getting the following exception.

java.util.regex.PatternSyntaxException: Unclosed group near index 2
/(

Escaping '(' doesn't seems to work.


来源: stackexchange

问:
Building AOSP and adding a system app with runtime permission
I work on Android 6 AOSP. I am able to build add the application as a system app
but now I want to add runtime permission by default on this system app. Like that the app can start without asking the user to validate the permission.

Do you know how I can do that?

Thanks for you help.

答:
You can grant runtime permissions to system apps by modifying the DefaultPermissionsGrantPolicy.java class.

In the grantDefaultSystemHandlerPermissions(int userId) method, add this code:

```<code>PackageParser.Package yourPackage = getSystemPackageLPr("YOUR_APP_PACKAGE_NAME");
if (yourPackage != null
                && doesPackageSupportRuntimePermissions(yourPackage)) {
    grantRuntimePermissionsLPw(yourPackage, CONTACTS_PERMISSIONS, userId);
    grantRuntimePermissionsLPw(yourPackage, CALENDAR_PERMISSIONS, userId);
}
</code>```

Make sure you add the code above this line:

mService.mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);

ContentLicense: CC BY-SA 3.0

Body:
You can grant runtime permissions to system apps by modifying the DefaultPermissionsGrantPolicy.java class.

In the grantDefaultSystemHandlerPermissions(int userId) method, add this code:

PackageParser.Package yourPackage = getSystemPackageLPr("YOUR_APP_PACKAGE_NAME");
if (yourPackage != null
                && doesPackageSupportRuntimePermissions(yourPackage)) {
    grantRuntimePermissionsLPw(yourPackage, CONTACTS_PERMISSIONS, userId);
    grantRuntimePermissionsLPw(yourPackage, CALENDAR_PERMISSIONS, userId);
}

Make sure you add the code above this line:

mService.mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);

ContentLicense: CC BY-SA 4.0


问:
How to prevent tkinter from generating duplicating windows
I am using TKInter to create a window that display some information, something like a notice. The window should show up when the 'View Details" button of the main application is clicked.

Here is the code of the window i was talking about. The Categories() method is called when the above mentioned button is clickd.

from tkinter import *
from tkinter import ttk

def Categories():

    roots = Tk()
    roots.minsize(600, 600)
    roots.title("Category Details")

    labelFrameCategory = ttk.LabelFrame(roots,text="Financial")
    labelFrameCategory.configure()
    labelFrameCategory.grid(column=0 ,row=0, pady=10, padx = 30 , sticky = W)

    labelClass = Label(labelFrameCategory, text="Documents related to finance")
    labelClass.grid(column=0, row=1)
    labelClass.config(font=("Courier", 15))

    roots.resizable(False, False)
    roots.mainloop()

```

The problem I have is every time I press the button, it creates a new window but leaves the current window open. So If I click 10 times, it will open 10 similar windows. But I want it to open only 1 window no matter how many times the button is clicked, there should be only 1 such window. How to do that ?

答:
instead of disabling the button,

why don’t you use the property name  of the toplevel?

this will allow you to use a single instance of your toplevel.

try the code below.

```<code>import tkinter as tk
from tkinter import ttk

root = tk.Tk()

def new_window():
    #a.config(command="")
    #use instead name='something'
    roots = tk.Toplevel(name='goofy') #Use Toplevel instead if you simply want another window
    roots.minsize(600, 600)
    roots.title("Category Details")

    labelFrameCategory = ttk.LabelFrame(roots,text="Financial")
    labelFrameCategory.configure()
    labelFrameCategory.grid(column=0 ,row=0, pady=10, padx = 30 , sticky = tk.W)

    labelClass = tk.Label(labelFrameCategory, text="Documents related to finance")
    labelClass.grid(column=0, row=1)
    labelClass.config(font=("Courier", 15))

    roots.resizable(False, False)

    def quit_window():
        a.config(command=new_window)
        roots.destroy()

    roots.protocol("WM_DELETE_WINDOW",quit_window)

a = tk.Button(root,text="Click to open new win",command=new_window)
a.pack()

root.mainloop()
</code>```

Body:
I am using TKInter to create a window that display some information, something like a notice. The window should show up when the 'View Details" button of the main application is clicked.

Here is the code of the window i was talking about. The Categories() method is called when the above mentioned button is clickd.

from tkinter import *
from tkinter import ttk

def Categories():

    roots = Tk()
    roots.minsize(600, 600)
    roots.title("Category Details")

    labelFrameCategory = ttk.LabelFrame(roots,text="Financial")
    labelFrameCategory.configure()
    labelFrameCategory.grid(column=0 ,row=0, pady=10, padx = 30 , sticky = W)

    labelClass = Label(labelFrameCategory, text="Documents related to finance")
    labelClass.grid(column=0, row=1)
    labelClass.config(font=("Courier", 15))

    roots.resizable(False, False)
    roots.mainloop()

The problem I have is every time I press the button, it creates a new window but leaves the current window open. So If I click 10 times, it will open 10 similar windows. But I want it to open only 1 window no matter how many times the button is clicked, there should be only 1 such window. How to do that ?

Body:
instead of disabling the button,

why don’t you use the property name  of the toplevel?

this will allow you to use a single instance of your toplevel.

try the code below.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

def new_window():
    #a.config(command="")
    #use instead name='something'
    roots = tk.Toplevel(name='goofy') #Use Toplevel instead if you simply want another window
    roots.minsize(600, 600)
    roots.title("Category Details")

    labelFrameCategory = ttk.LabelFrame(roots,text="Financial")
    labelFrameCategory.configure()
    labelFrameCategory.grid(column=0 ,row=0, pady=10, padx = 30 , sticky = tk.W)

    labelClass = tk.Label(labelFrameCategory, text="Documents related to finance")
    labelClass.grid(column=0, row=1)
    labelClass.config(font=("Courier", 15))

    roots.resizable(False, False)

    def quit_window():
        a.config(command=new_window)
        roots.destroy()

    roots.protocol("WM_DELETE_WINDOW",quit_window)

a = tk.Button(root,text="Click to open new win",command=new_window)
a.pack()

root.mainloop()


问:
How to speed up the "ImageFolder" for ImageNet
I am in an university, and all the file system are in a remote system, wherever I log in with my account, I could aways access my home directory. even though I log into the GPU servers through SSH command. This is the condition where I employ the GPU servers to read data.

Currently, I use the PyTorch to train ResNet from scratch on ImageNet, my codes only use all the GPUs in the same computer, I found that the "torchvision.datasets.ImageFolder" will take almost two hours.

Would you please provide some experiences in how to speed up "torchvision.datasets.ImageFolder"? Thanks very much.

答:
Why it takes so long?

Setting up an ImageFolder can take a long time, especially when the images are stored on a slow remote disk. The reason for this latency is that the __init__ function for the dataset goes over all files in the image folders and check whether this file is an image file. For ImageNet that can take quite a while as there are over 1 million files to check.

What can you do?

- As Kevin Sun already pointed out, copying the dataset to a local (and possibly much faster) storage can significantly speed up things.

- Alternatively, you can create a modified dataset class that does not read all the files, but relies on a cached list of files - a cached list that you prepare only once in advance and to be used for all runs.


问:
I have a *lot* of source files to add to a git repo, how to make it fast
I am looking here for inspiration on importing bulk files into a git repo faster, but not sure it's it.

Basically the situation is, I have >100 million files I want to commit to a git repo. I have broken them down into directories roughly 5 deep. To git add path/2/3 some levels deep takes about 5 minutes. Then to commit, then to publish. It takes a long time and could take months to commit all of these files.

Please don't get caught up on wondering why I'm storing them in git and if they are source files and if there is a better solution, etc.. I specifically want to know how much git can handle and if it can handle this many files in a more optimal way.

FYI these are all config files or CSV-like data files, some very large, most of them small.

If I try to commit the whole thing, or just a large fragment, it might take an hour to commit them all. But to publish it might take several hours and I have tried it already and often times the internet cuts out and boom you have to start over. So it's not a viable solution I don't think.

What I'm wondering is if there is a way to load all this stuff directly into git in one swoop, like you would load into a database with a database dump, and bypass all the git stuff it does when doing the commit. Then it creates a commit. Then somehow publish like rsync does where it's robust and doesn't break if the internet connection breaks. Then it would be like a normal upload.

答:
There are few hard limits on the number of files—technically blob objects—that a Git database can store.1  There are a bunch of softer limits, though.

I have handy two fairly big repositories—FreeBSD and Linux—that weigh in at 5.7 and 6.7 million objects.  This is far less than 100 million files: the Linux repository is about 1/15th that size, and even then there aren't that many files, as many of the objects are commits and trees.

Note that there's a difference between putting 100 million files into one commit, and putting 100 million files into 100 million commits, each of which stores one file.  The former will require building an index that lists 100 million files, which is several gigabytes of index file and is likely to be slow, but then stores 100 million blobs, plus one tree object per directory, plus one commit.  The latter would build a small index (of 1 file), make one commit using one tree holding one blob, then repeat 100 million times: the index would never be large but the repository would store 300 million objects: 100 million commits, each with 1 tree and 1 blob.

It's not immediately obvious where all the time is going.  git add <path> requires:

compressing the contents of the file and creating a new blob object, or re-using an existing blob object if the compressed hash ID is that of an existing object; then

updating the index so that staging slot zero of the appropriate file name appears in the right position.

The index is sorted, so this update could conceivably be very fast—if the new file goes at the end of the index, a single however-many byte append would suffice—or incredibly slow: an insert at the front will be O(n2) on the number of entries already in the index, as all of them will have to move down.  In practice, Git reads the index into memory, performs the operation there, and writes the index back, so it will probably be very slow once the index passes some size threshold (which will vary depending on the OS and underlying storage medium type / speed).

You may also need a great deal of disk space between packing objects.  Modern Git will run git gc --auto after each commit, but between early Git and 2.17.0 (when it was fixed), git commit accidentally didn't.  Given your situation you probably want to disable automatic git gc anyway, and run it at controlled intervals—or, as in the documentation you linked, use git fast-import to build a pack file without going through the normal Git channels.  This will avoid the need for an index entirely (until you run git checkout to extract one of these commits, that is).

1The only real hard limit is that there are only 2160 possible hash IDs.  However, you run into noticeably high hash-collision probability, on the order of 1 in 10-18—this is also many disk manufacturers' quoted uncorrected bit error rate—by the time you're up to about 1.7 quadrillion objects.


问:
How to pass multiple arguments to a test case in CumulusCI test automation framework?
Problem statement:

Unable to pass multiple variable values to my test case using CumulusCI command:

```<code>`cci task run robot...
</code>```

I am referring this section for building my command: https://cumulusci.readthedocs.io/en/latest/tasks.html#id49

If I have to pass just one variable in the same way as above, say for eg. just LocalOrRemote, then the code works perfectly fine, so it appears that this has to do something with the way I am passing multiple variables.

My test automation tech stack is Robot Framework, CumulusCI, Selenium

Sample Code:

```<code>*** Settings ***
Resource  C:/Dev/myproject/robotframework/EnvironmentSetupFile.robot
Suite Setup  Run Keywords  Suite Setup KW1  AND  Suite Setup OS And Browser  ${LocalOrRemote}  ${Browser}

*** Test Cases ***
Verify whether I am able to set environment and browser
    [Tags]  LocalEdge
    [Documentation]  This test should run on the local edge browser
    Keyword X
    Keyword Y

*** Keywords ***
Suite Setup KW1
    do something
Suite Setup OS And Browser
    [Arguments]  ${LocalOrRemote}  ${Browser}
    Log Many  ${LocalOrRemote}  ${Browser}
    run keyword if  '${LocalOrRemote}'=='Local'  Setup Local Browser  ${Browser}
    ...  ELSE IF  '${LocalOrRemote}'=='Remote'  Setup Remote Browser  ${Browser}
    ...  ELSE  FAIL  "Incorrect environment value passed! Please refer the instructions in README for running the test suite"
</code>```

Command I am using to invoke my test:

```<code>cci task run robot -o suites mypath/MyTestFile.robot -o include LocalEdge -o vars LocalOrRemote:Local,Browser:edge
</code>```

Issue I am facing:

The value of ${Browser} is not received as edge but defaulted to chrome, which means the command is not able to pass on my desired value to the TC.

```<code>KEYWORD BuiltIn . Log Many ${LocalOrRemote}, ${Browser}
Documentation:
Logs the given messages as separate entries using the INFO level.
Start / End / Elapsed:  20190522 16:36:53.877 / 20190522 16:36:53.878 / 00:00:00.001
16:36:53.877    INFO    Local
16:36:53.877    INFO    chrome
</code>```

答:
Thanks a ton @Bryan for the direction. It was that moment when you get so awestruck by your own creation and forget to try out basic debugging in your framework.

Anyway, the issue here was the placement of resources as you rightly pointed out. Observe the before and after code pieces below. The issue (well at this point I cannot comment that its an issue or shortcoming) revolves around the placement of Salesforce.robot resource. For the Cci command to pass the right value of the 2nd variable, I had to place this resource in the test case itself. The Cci command did not pass the right value of the 2nd variable when I had this resource loaded via an environment file; weird.

```<code>*** Settings ***
Documentation  ###My setup before:
Resource  C:/Dev/myproject/robotframework/EnvironmentSetupFile.robot
Suite Setup  Run Keywords  Suite Setup KW1  AND  Suite Setup OS And Browser  ${LocalOrRemote}  ${Browser}
Documentation  ###My setup after:
Resource  C:/Dev/myproject/robotframework/EnvironmentSetupFile.robot
Resource  cumulusci/robotframework/Salesforce.robot  #had to place this resource here
Suite Setup  Run Keywords  Suite Setup KW1  AND  Suite Setup OS And Browser  ${LocalOrRemote}  ${Browser}

*** Test Cases ***
Verify whether I am able to set environment and browser
    [Tags]  LocalEdge
    [Documentation]  This test should run on the local edge browser
    Log  "TC passed"
</code>```

My setup before:

C:/Dev/myproject/robotframework/EnvironmentSetupFile.robot

```<code>*** Keywords ***
Suite Setup KW1
    Import Resource  cumulusci/robotframework/Salesforce.robot  #the resource that was causing the issue
    Import Resource  C:/Dev/myproject/robotframework/BrowserSetupKeywords.robot
    import resource  C:/Dev/myproject/robotframework/ValidationKeywords.robot
    Import Library  cumulusci.robotframework.CumulusCI  ${ORG}
    import library  SeleniumLibrary  timeout=7 seconds  implicit_wait=5 seconds
    import library  OperatingSystem
    import library  BuiltIn
</code>```

C:/Dev/myproject/robotframework/BrowserSetupKeywords.robot

```<code>*** Keywords ***
Suite Setup OS And Browser
    [Arguments]  ${LocalOrRemote}  ${Browser}
    Log Many  ${LocalOrRemote}  ${Browser}  #used to default Browser value passed to chrome
</code>```

`

My setup after:

C:/Dev/myproject/robotframework/EnvironmentSetupFile.robot

```<code>*** Keywords ***
Suite Setup KW1
    #Import Resource  cumulusci/robotframework/Salesforce.robot  # had to comment this resource here and place it before the Suite Setup
    Import Resource  C:/Dev/myproject/robotframework/BrowserSetupKeywords.robot
    import resource  C:/Dev/myproject/robotframework/ValidationKeywords.robot
    Import Library  cumulusci.robotframework.CumulusCI  ${ORG}
    import library  SeleniumLibrary  timeout=7 seconds  implicit_wait=5 seconds
    import library  OperatingSystem
    import library  BuiltIn
</code>```

C:/Dev/myproject/robotframework/BrowserSetupKeywords.robot

```<code>*** Keywords ***
Suite Setup OS And Browser
    [Arguments]  ${LocalOrRemote}  ${Browser}
    Log Many  ${LocalOrRemote}  ${Browser}  #now returns the correct Browser value
</code>```

Body:
Problem statement:

Unable to pass multiple variable values to my test case using CumulusCI command:

`cci task run robot...

I am referring this section for building my command: https://cumulusci.readthedocs.io/en/latest/tasks.html#id49

If I have to pass just one variable in the same way as above, say for eg. just LocalOrRemote, then the code works perfectly fine, so it appears that this has to do something with the way I am passing multiple variables.

My test automation tech stack is Robot Framework, CumulusCI, Selenium

Sample Code:

*** Settings ***
Resource  C:/Dev/myproject/robotframework/EnvironmentSetupFile.robot
Suite Setup  Run Keywords  Suite Setup KW1  AND  Suite Setup OS And Browser  ${LocalOrRemote}  ${Browser}

*** Test Cases ***
Verify whether I am able to set environment and browser
    [Tags]  LocalEdge
    [Documentation]  This test should run on the local edge browser
    Keyword X
    Keyword Y

*** Keywords ***
Suite Setup KW1
    do something
Suite Setup OS And Browser
    [Arguments]  ${LocalOrRemote}  ${Browser}
    Log Many  ${LocalOrRemote}  ${Browser}
    run keyword if  '${LocalOrRemote}'=='Local'  Setup Local Browser  ${Browser}
    ...  ELSE IF  '${LocalOrRemote}'=='Remote'  Setup Remote Browser  ${Browser}
    ...  ELSE  FAIL  "Incorrect environment value passed! Please refer the instructions in README for running the test suite"

Command I am using to invoke my test:

cci task run robot -o suites mypath/MyTestFile.robot -o include LocalEdge -o vars LocalOrRemote:Local,Browser:edge

Issue I am facing:

The value of ${Browser} is not received as edge but defaulted to chrome, which means the command is not able to pass on my desired value to the TC.

KEYWORD BuiltIn . Log Many ${LocalOrRemote}, ${Browser}
Documentation:
Logs the given messages as separate entries using the INFO level.
Start / End / Elapsed:  20190522 16:36:53.877 / 20190522 16:36:53.878 / 00:00:00.001
16:36:53.877    INFO    Local
16:36:53.877    INFO    chrome

Body:
Thanks a ton @Bryan for the direction. It was that moment when you get so awestruck by your own creation and forget to try out basic debugging in your framework.

Anyway, the issue here was the placement of resources as you rightly pointed out. Observe the before and after code pieces below. The issue (well at this point I cannot comment that its an issue or shortcoming) revolves around the placement of Salesforce.robot resource. For the Cci command to pass the right value of the 2nd variable, I had to place this resource in the test case itself. The Cci command did not pass the right value of the 2nd variable when I had this resource loaded via an environment file; weird.

*** Settings ***
Documentation  ###My setup before:
Resource  C:/Dev/myproject/robotframework/EnvironmentSetupFile.robot
Suite Setup  Run Keywords  Suite Setup KW1  AND  Suite Setup OS And Browser  ${LocalOrRemote}  ${Browser}
Documentation  ###My setup after:
Resource  C:/Dev/myproject/robotframework/EnvironmentSetupFile.robot
Resource  cumulusci/robotframework/Salesforce.robot  #had to place this resource here
Suite Setup  Run Keywords  Suite Setup KW1  AND  Suite Setup OS And Browser  ${LocalOrRemote}  ${Browser}

*** Test Cases ***
Verify whether I am able to set environment and browser
    [Tags]  LocalEdge
    [Documentation]  This test should run on the local edge browser
    Log  "TC passed"

My setup before:

C:/Dev/myproject/robotframework/EnvironmentSetupFile.robot

*** Keywords ***
Suite Setup KW1
    Import Resource  cumulusci/robotframework/Salesforce.robot  #the resource that was causing the issue
    Import Resource  C:/Dev/myproject/robotframework/BrowserSetupKeywords.robot
    import resource  C:/Dev/myproject/robotframework/ValidationKeywords.robot
    Import Library  cumulusci.robotframework.CumulusCI  ${ORG}
    import library  SeleniumLibrary  timeout=7 seconds  implicit_wait=5 seconds
    import library  OperatingSystem
    import library  BuiltIn

C:/Dev/myproject/robotframework/BrowserSetupKeywords.robot

*** Keywords ***
Suite Setup OS And Browser
    [Arguments]  ${LocalOrRemote}  ${Browser}
    Log Many  ${LocalOrRemote}  ${Browser}  #used to default Browser value passed to chrome

`

My setup after:

C:/Dev/myproject/robotframework/EnvironmentSetupFile.robot

*** Keywords ***
Suite Setup KW1
    #Import Resource  cumulusci/robotframework/Salesforce.robot  # had to comment this resource here and place it before the Suite Setup
    Import Resource  C:/Dev/myproject/robotframework/BrowserSetupKeywords.robot
    import resource  C:/Dev/myproject/robotframework/ValidationKeywords.robot
    Import Library  cumulusci.robotframework.CumulusCI  ${ORG}
    import library  SeleniumLibrary  timeout=7 seconds  implicit_wait=5 seconds
    import library  OperatingSystem
    import library  BuiltIn

C:/Dev/myproject/robotframework/BrowserSetupKeywords.robot

*** Keywords ***
Suite Setup OS And Browser
    [Arguments]  ${LocalOrRemote}  ${Browser}
    Log Many  ${LocalOrRemote}  ${Browser}  #now returns the correct Browser value


问:
React-select default value when no options match with the user search value
I have an array for react-select like as below

```<code>[{label:"blue",value:"blue"},{label:"green",value:"green"},{label:"other",value:"other"}]
</code>```

When an user tries to search other than blue and green,(like brown, purple) the other option should be shown in the options list, so the user can select the "other"

Is there any way to achieve this functionality in react-select

答:
I think what you're looking for is close from this post.

Basically use a filterOption props like this:

```<code> filterOption = (option, inputValue) => {
    if (option.label === "Other") {
      const { options } = this.state;
      const result = options.filter(opt => opt.label.includes(inputValue));
      this.setState({ hasExtraValue: !result.length });
      return !result.length;
    }

    return option.label.includes(inputValue);
  };
</code>```

Here's a live example matching your requirements.

Body:
I have an array for react-select like as below

[{label:"blue",value:"blue"},{label:"green",value:"green"},{label:"other",value:"other"}]

When an user tries to search other than blue and green,(like brown, purple) the other option should be shown in the options list, so the user can select the "other"

Is there any way to achieve this functionality in react-select

Body:
I think what you're looking for is close from this post.

Basically use a filterOption props like this:

 filterOption = (option, inputValue) => {
    if (option.label === "Other") {
      const { options } = this.state;
      const result = options.filter(opt => opt.label.includes(inputValue));
      this.setState({ hasExtraValue: !result.length });
      return !result.length;
    }

    return option.label.includes(inputValue);
  };

Here's a live example matching your requirements.


问:
Shortest path between raw geo coordinates and a node of a graph
I have implemented a simple Dijkstra's algorithm for finding the shortest path on an .osm map with Java.

The pathfinding in a graph which is created from an .osm file works pretty well. But in case the user's current location and/or destination is not a node of this graph (just raw coordinates) how do we 'link' those coordinates to the graph to make pathfinding work?

The simple straightforward solution "find the nearest to the current location node and draw a straight line" doesn't seem to be realistic. What if we have a situation like on the attached picture? (UPD)

The problem here is that before we start any 'smart' pathfinding algorithms (like Dijkstra's) we 'link' the current position to the graph, but it is just dumb formula (a hypotenuse from Pythagorean theorem)  of finding the nearest node in terms of geographical coordinates and this formula is not 'pathinding' - it can not take obstacles and types of nodes into account.

To paraphrase it - how do we find the shortest path between A and B if B is a node in a graph, and A is not a node?

Have you heard of any other solutions to this problem?

答:
You could treat the current location as a node, and connect that node to a few of the nearest nodes in a straight line. GPS applications would consider this straight line as being 'off road', so the cost of this line is very big compared to the other lines between nodes.

However, I didn't see your attached picture, so not sure this is a good solution for you.


问:
Use input function and while loop to transfer a path in Python
When I define a filePath and os.walk, it goes well:

```<code>filePath = 'C:/Users/User/Desktop/test/'

for subdir, dirs, files in os.walk(filePath):
    print(subdir)
</code>```

Output:

```<code>C:/Users/User/Desktop/test/
C:/Users/User/Desktop/test/a
C:/Users/User/Desktop/test/a\a1
C:/Users/User/Desktop/test/a\a2
C:/Users/User/Desktop/test/a\a3
</code>```

But when I use input function and while loop, I can not transfer filePath to os.walk(filePath), I don't know why. Someone could help me to figure it out? Thanks.

```<code>status = True
while status:
    filePath = input(r"Please write your path:")
    if filePath.strip() == "":
        status = False

for subdir, dirs, files in os.walk(filePath):
    print(subdir)
</code>```

Output:

```<code>Please write your path:C:/Users/User/Desktop/test/
Please write your path:'C:/Users/User/Desktop/test/'
Please write your path:
</code>```

EDIT:

```<code>status = True
while status:
    filePath = input(r"Please write your path:")
    if os.path.exists(filePath):
        status = False

for subdir, dirs, files in os.walk(filePath):
    print(subdir)
</code>```

Output:

```<code>Please write your path:C:/Users/User/Desktop/test/

C:/Users/User/Desktop/test/
C:/Users/User/Desktop/test/a
C:/Users/User/Desktop/test/a\a1
C:/Users/User/Desktop/test/a\a2
C:/Users/User/Desktop/test/a\a3
</code>```

Then it finish here, I want when the code rerun so I can write another path say: C:/Users/User/Desktop/test1/ at one time, until the path I write is empty, it will stop.

答:
Instead of filePath.strip() == "" use os.path.exists() to check whether the given path is valid or not.

TRY:-

```<code>import os

status = True
while status:
    filePath = input(r"Please write your path:")
    if os.path.exists(filePath):
        status = False

for subdir, dirs, files in os.walk(filePath):
    print(subdir)
</code>```

P.S.:- Your naming scheme for os.walk() is incorrect, os.walk(), in general returns in a format Dirname, SubDir_list, File_list so you should name the variables in which these are unpacked in a proper manner. You have named the variable that will be storing the path to the directory as subdir, variable storing the sub_directory list as dirs, which could be quite confusing to others. So try naming them by the convention so that it is easier for others to understand

EDIT:-

```<code>import os

status = True
while status:
    filePath = input(r"Please write your path:")
    if os.path.exists(filePath):
        for subdir, dirs, files in os.walk(filePath):
            print(subdir)

    if filePath is "":
        status = False
</code>```

This code will run until a empty string ''  is provided as a filepath. (empty string means nothing)

Body:
When I define a filePath and os.walk, it goes well:

filePath = 'C:/Users/User/Desktop/test/'

for subdir, dirs, files in os.walk(filePath):
    print(subdir)

Output:

C:/Users/User/Desktop/test/
C:/Users/User/Desktop/test/a
C:/Users/User/Desktop/test/a\a1
C:/Users/User/Desktop/test/a\a2
C:/Users/User/Desktop/test/a\a3

But when I use input function and while loop, I can not transfer filePath to os.walk(filePath), I don't know why. Someone could help me to figure it out? Thanks.

status = True
while status:
    filePath = input(r"Please write your path:")
    if filePath.strip() == "":
        status = False

for subdir, dirs, files in os.walk(filePath):
    print(subdir)

Output:

Please write your path:C:/Users/User/Desktop/test/
Please write your path:'C:/Users/User/Desktop/test/'
Please write your path:

EDIT:

status = True
while status:
    filePath = input(r"Please write your path:")
    if os.path.exists(filePath):
        status = False

for subdir, dirs, files in os.walk(filePath):
    print(subdir)

Output:

Please write your path:C:/Users/User/Desktop/test/

C:/Users/User/Desktop/test/
C:/Users/User/Desktop/test/a
C:/Users/User/Desktop/test/a\a1
C:/Users/User/Desktop/test/a\a2
C:/Users/User/Desktop/test/a\a3

Then it finish here, I want when the code rerun so I can write another path say: C:/Users/User/Desktop/test1/ at one time, until the path I write is empty, it will stop.

Body:
Instead of filePath.strip() == "" use os.path.exists() to check whether the given path is valid or not.

TRY:-

import os

status = True
while status:
    filePath = input(r"Please write your path:")
    if os.path.exists(filePath):
        status = False

for subdir, dirs, files in os.walk(filePath):
    print(subdir)

P.S.:- Your naming scheme for os.walk() is incorrect, os.walk(), in general returns in a format Dirname, SubDir_list, File_list so you should name the variables in which these are unpacked in a proper manner. You have named the variable that will be storing the path to the directory as subdir, variable storing the sub_directory list as dirs, which could be quite confusing to others. So try naming them by the convention so that it is easier for others to understand

EDIT:-

import os

status = True
while status:
    filePath = input(r"Please write your path:")
    if os.path.exists(filePath):
        for subdir, dirs, files in os.walk(filePath):
            print(subdir)

    if filePath is "":
        status = False

This code will run until a empty string ''  is provided as a filepath. (empty string means nothing)


问:
Update using Laravel: created_at is updated when updating record
The update functionality is doing fine with the below codes. Where I update the status field as 0. The default value of that field is 1. It works fine, but the created_at field also updates whenever this function is used. It should be the updated_at field that is being updated not the created_at.

In my notification_records table I have created_at and updated_at fields.

Where the created_at data type is timestamp() this field is used if there's new created notification records and the updated_at field is for modification only

```<code>public function notification(Request $request){
$company_id = auth()->user()->company_id;
DB::connection('mysql')->select("UPDATE notification_records SET status = '0' WHERE company_id = '".$company_id."' AND id = '".$request->ind."'");
}
</code>```

What I'm trying to do is whenever the function is being used the only field that will update the value of the field between created_at and updated_at is the updated_at only. Is there possible way to do it with the above codes?

答:
This is an issue in laravel 5.2
You can mitigate this by removing and readding the timestamps as follows:
Instead of $table->timestamps();

```<code>$table->timestamp('created_at')->default('0000-00-00 00:00');
$table->timestamp('updated_at')->default('0000-00-00 00:00');
</code>```

See here for the question: Laravel changes created_at on update

The solution is referenced from here

https://github.com/spatie/laravel-medialibrary/issues/150

Body:
The update functionality is doing fine with the below codes. Where I update the status field as 0. The default value of that field is 1. It works fine, but the created_at field also updates whenever this function is used. It should be the updated_at field that is being updated not the created_at.

In my notification_records table I have created_at and updated_at fields.

Where the created_at data type is timestamp() this field is used if there's new created notification records and the updated_at field is for modification only

public function notification(Request $request){
$company_id = auth()->user()->company_id;
DB::connection('mysql')->select("UPDATE notification_records SET status = '0' WHERE company_id = '".$company_id."' AND id = '".$request->ind."'");
}

What I'm trying to do is whenever the function is being used the only field that will update the value of the field between created_at and updated_at is the updated_at only. Is there possible way to do it with the above codes?

Body:
This is an issue in laravel 5.2
You can mitigate this by removing and readding the timestamps as follows:
Instead of $table->timestamps();

$table->timestamp('created_at')->default('0000-00-00 00:00');
$table->timestamp('updated_at')->default('0000-00-00 00:00');

See here for the question: Laravel changes created_at on update

The solution is referenced from here

https://github.com/spatie/laravel-medialibrary/issues/150


问:
Are actionscript bitmaps faster than vectors?
I'm working on a project which draws circles continuously at framerate and animates them around the stage and I'm running into performance issues.

I'm already converting all objects to bitmapData as soon as they become static. My question is, will converting the circles to bitmapData as soon as they are drawn increase performance? In other words, is animating say, 200 bitmaps (with transparency) faster than 200 vector circles?

Are there any drawbacks to this technique? (I'm thinking opacity problems maybe?)

If they were more complex shapes than circles would the answer be different?

Any other tips on improving performance?

Thanks a lot!

答:
There are several approaches you might consider here:

Bet on the vector renderer by drawing your lines and circles each frame. They'll get re-rendered every time, but then that's what Flash is heavily optimized for, so it's not impossible that this could be faster than the alternatives. (Note that drawing the objects at different sizes each frame might be faster than drawing them each into a Sprite and changing its size.)

Bet against the vector renderer by moving bitmaps around. A simple way to do this (assuming you're drawing the shapes with AS3) would be to draw the shapes into Bitmap objects and then move those around. You may not be happy with the jagginess of the result. Enabling bitmap smoothing will help (but cost some performance).

Note: cacheAsBitmap will probably not do what you want here, because cached bitmaps get redrawn when the object changes size (not sure about transparency).

Bet on hardware acceleration by using cacheAsBitmapMatrix. This is only available in AIR, so it may not work for you. CABM is similar to cacheAsBitmap, but it doesn't redraw the contents as they rescale. Further, in many cases the bitmap gets handed to hardware, and thus can be rescaled on the GPU. I believe there are platforms where that doesn't work though. This is generally very fast, especially on mobile devices.

Bet on AS3 bitmap handling by blitting stuff into a stage-sized BitmapData. But note even if you do this, you'll still need to decide whether to draw shapes into your big bitmap each frame (like option 1) or draw them into individual bitmaps and blit those (transformed) into the big bitmap each frame (like option 2).

I don't think there's any way to know which option is best without experimenting. I'm almost certain that option 3 will be the best if you're using AIR and if HW acceleration works on your platform, but those may not be true. My gut instinct is that option 4 will not be terribly helpful. Blitting can be very fast when you are drawing lots of of static bitmaps onto the stage untransformed, but in this case you need to be either generating or transforming the content each frame, so my guess is that the benefit of blitting will not occur where your bottleneck is. My best guess is that option 2 will be faster than 1, but you may not be happy with the visuals.


问:
Enforce field uniqueness to parent in many-to-one relation
I have a Table model which is many-to-one with a Restaurant model. Is there a way to have a field reference_label in the Table model that must be unique per restaurant, but not across different restaurants?

In short, I want to enforce reference_label uniqueness for tables with the same foreign key.

I know I can just use the Table's id, but I want each restaurant to be able to customize how they label their tables.

答:
If you are using Django 2.2 you can use UniqueConstraint instead of unique_together like this:

```<code>class Meta:
    constraints = [
        models.UniqueConstraint(fields=['restaurant', 'reference_label'], name='give_it_some_name')
    ]
</code>```

As the docs state:

Use UniqueConstraint with the constraints option instead.

UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future.

Body:
If you are using Django 2.2 you can use UniqueConstraint instead of unique_together like this:

class Meta:
    constraints = [
        models.UniqueConstraint(fields=['restaurant', 'reference_label'], name='give_it_some_name')
    ]

As the docs state:

Use UniqueConstraint with the constraints option instead.

UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future.


问:
How to execute procedure in function SQL Server
I need this function:

```<code>create function test (@InVar int)
returns nvarchar(max) as
begin
  declare @OutVar nvarchar(max);
  exec someProcedure @InVar, @OutVar out;
  return @OutVar
end
</code>```

I want :

```<code>select *, dbo.test(ID)
from SomeTable
</code>```

答:
Your code is perfect but it is not runnable because

Only functions and some extended stored procedures can be executed from within a function.

I Suggest You Instead of SP implement the logic in the function itself.

Body:
I need this function:

create function test (@InVar int)
returns nvarchar(max) as
begin
  declare @OutVar nvarchar(max);
  exec someProcedure @InVar, @OutVar out;
  return @OutVar
end

I want :

select *, dbo.test(ID)
from SomeTable


问:
Recycleview custom layout constraint are changing for each inflated view causing problems
I have a recyclerview that inflates data fetched from json.

The issue I am facing are design issues - sometimes the text is aligned correctly and the image is shown and sometimes the text is too long, causing what I think is for the image not to be shown.

here is my XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.constraint.ConstraintLayout
        android:layout_width="395dp"
        android:layout_height="170dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:background="#335634"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/heroImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:src="@mipmap/ic_launcher"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/heroTitle"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:text="Hero Title"
            android:textSize="25dp"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/heroDescription"
            android:layout_width="200dp"
            android:breakStrategy="simple"
            android:layout_height="wrap_content"
            android:layout_marginStart="36dp"
            android:layout_marginTop="24dp"
            android:layout_marginEnd="16dp"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:text="TextView"
            android:textAlignment="center"
            android:textSize="18dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/heroImage"
            app:layout_constraintTop_toBottomOf="@+id/heroTitle" />

    </android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
</code>```

and here is my adapter:

```<code>public class HeroesAdapter extends RecyclerView.Adapter<HeroesAdapter.HeroesViewHolder> {

    private List<Hero> heroList;

    public HeroesAdapter(List<Hero> heroList) {
        this.heroList = heroList;
    }

    @NonNull
    @Override
    public HeroesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.hero_cell, parent, false);
        return new HeroesViewHolder(rowView);
    }

    @Override
    public void onBindViewHolder(@NonNull HeroesViewHolder holder, int position) {

        Hero currentHero = heroList.get(position);
        String str = String.join(",", currentHero.abilities);

        holder.heroTitle.setText(currentHero.title);
        holder.heroAbilties.setText(str);
        Picasso.get().load(currentHero.image).resize(500,500).into(holder.heroesImage);

    }

    @Override
    public int getItemCount() {
        return heroList.size();
    }

    public static class HeroesViewHolder extends RecyclerView.ViewHolder {

        ImageView heroesImage;
        TextView heroTitle;
        TextView heroAbilties;

        public HeroesViewHolder(@NonNull View itemView) {
            super(itemView);
            heroesImage = itemView.findViewById(R.id.heroImage);
            heroTitle = itemView.findViewById(R.id.heroTitle);
            heroAbilties = itemView.findViewById(R.id.heroDescription);
        }
    }
}
</code>```

This is the result I am getting and this is the wanted result.

the issues I am facing are:

making each row have a clean design and act the same for all.

images are sometimes shown, sometimes not.

bottom view is "half in screen" and half out of screen.

答:
By using LinearLayout you can design your hero_cell that will give you the desirable output. as I do it for now.

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:padding="10dp"
    android:background="#335634"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/heroImage"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:src="@drawable/logo"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <LinearLayout
        android:background="#335634"
        android:layout_marginLeft="20dp"
        android:orientation="vertical"
        android:layout_gravity="center_vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/heroTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:text="Hero Title"
            android:textSize="25dp"
            android:textStyle="bold"
            />

        <TextView
            android:id="@+id/heroDescription"
            android:layout_width="match_parent"
            android:breakStrategy="simple"
            android:layout_height="wrap_content"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:text="TextView"
            android:textSize="18dp" />
    </LinearLayout>
</code>```

Body:
I have a recyclerview that inflates data fetched from json.

The issue I am facing are design issues - sometimes the text is aligned correctly and the image is shown and sometimes the text is too long, causing what I think is for the image not to be shown.

here is my XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.constraint.ConstraintLayout
        android:layout_width="395dp"
        android:layout_height="170dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:background="#335634"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/heroImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:src="@mipmap/ic_launcher"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/heroTitle"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:text="Hero Title"
            android:textSize="25dp"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/heroDescription"
            android:layout_width="200dp"
            android:breakStrategy="simple"
            android:layout_height="wrap_content"
            android:layout_marginStart="36dp"
            android:layout_marginTop="24dp"
            android:layout_marginEnd="16dp"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:text="TextView"
            android:textAlignment="center"
            android:textSize="18dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/heroImage"
            app:layout_constraintTop_toBottomOf="@+id/heroTitle" />

    </android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>

and here is my adapter:

public class HeroesAdapter extends RecyclerView.Adapter<HeroesAdapter.HeroesViewHolder> {

    private List<Hero> heroList;

    public HeroesAdapter(List<Hero> heroList) {
        this.heroList = heroList;
    }

    @NonNull
    @Override
    public HeroesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.hero_cell, parent, false);
        return new HeroesViewHolder(rowView);
    }

    @Override
    public void onBindViewHolder(@NonNull HeroesViewHolder holder, int position) {

        Hero currentHero = heroList.get(position);
        String str = String.join(",", currentHero.abilities);

        holder.heroTitle.setText(currentHero.title);
        holder.heroAbilties.setText(str);
        Picasso.get().load(currentHero.image).resize(500,500).into(holder.heroesImage);

    }

    @Override
    public int getItemCount() {
        return heroList.size();
    }

    public static class HeroesViewHolder extends RecyclerView.ViewHolder {

        ImageView heroesImage;
        TextView heroTitle;
        TextView heroAbilties;

        public HeroesViewHolder(@NonNull View itemView) {
            super(itemView);
            heroesImage = itemView.findViewById(R.id.heroImage);
            heroTitle = itemView.findViewById(R.id.heroTitle);
            heroAbilties = itemView.findViewById(R.id.heroDescription);
        }
    }
}

This is the result I am getting and this is the wanted result.

the issues I am facing are:

making each row have a clean design and act the same for all.

images are sometimes shown, sometimes not.

bottom view is "half in screen" and half out of screen.

Body:
By using LinearLayout you can design your hero_cell that will give you the desirable output. as I do it for now.

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:padding="10dp"
    android:background="#335634"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/heroImage"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:src="@drawable/logo"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <LinearLayout
        android:background="#335634"
        android:layout_marginLeft="20dp"
        android:orientation="vertical"
        android:layout_gravity="center_vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/heroTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:text="Hero Title"
            android:textSize="25dp"
            android:textStyle="bold"
            />

        <TextView
            android:id="@+id/heroDescription"
            android:layout_width="match_parent"
            android:breakStrategy="simple"
            android:layout_height="wrap_content"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:text="TextView"
            android:textSize="18dp" />
    </LinearLayout>


问:
request session not persistent - express-session
I'm trying to have a session containing user data in the node.js/express FW.
I'm using express-session. I'm not using session store yet.
I have 2 pages in the client (angular) where I iterate between - Login and Dashboard. The idea is to create the session after successful login, then routing to the dashboard page. In the dashboard page I have an anchor with routinlink to the login:

```<code><a [routerLink]="['/login']" >BackToLogin</a>
</code>```

When navigating back to the loginPage (when activating a route), I execute a service with an end-point to the express server which check if the request has a session with a request in it (I expect it to be). The problem is that I see that the session is not the same session (the id changes)

See my code:
Node.js side - server.js file:

```<code>const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');

const session = require ('express-session');
var cookieParser = require('cookie-parser');
const SESS_NAME = 'sid';

app.use(session({
    name:SESS_NAME,
    key: 'user_sid',
    resave:false,
    saveUninitialized:false,
    secure: process.env.NODE_ENV ==="production",
    secret:'<some random text>',
    cookie:{

            httpOnly: true,
            secure: process.env.NODE_ENV ==="production",
            expires: 60000
           }
}));

app.use(bodyParser.text());
app.use(bodyParser);
app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(cors()); //No limitation for test reasons

app.use(cookieParser());

//disabled on purpose
//var sessionManagement = require('./middleware/sessionManagement');
// API
app.use("/", require("./api/v1/routes.js"))//This file includes:
/*
const express = require('express');
const router = express.Router();
router.use("/login", require('./login'));
router.use("/session", require('./session'));
module.exports = router;
*/
...etc
app.listen(config.port, () => console.log(`Process ${process.pid}: Listening on port ${config.port}`));
</code>```

login.js on the server: responsible for validating user and store user data in session:

```<code>const express = require('express');
const router = express.Router();
const schema = require('./objectSchemaJson.schema.json');
const scehmaCheck = require('../../middleware/checkForSchema')(schema);//this is
a schema check (middleware) - if suceeded continue (next)

const storeSession = (req, dataResult) =>
{
    if (<dataResult return with valid use data>) //This is "where the magic happanes"
    {
        req.session.user = {
            username: <get userName from dataResult>,
            ID: <Get ID from dataResult>,
            Role: <Get Role from dataResult>
        }
    }
}
router.use("/", scehmaCheck, (req, res, next) => {
    return GetUserDataFROmDB(req.body).then((dataResult) => { //reaching the DB - not mentioned here on purpose
        storeSession(req, dataResult); // This is where the session set with user data
        res.status(200).json(dataResult);
    }).catch((err) => {
        next({
            details: err
        })
    });
});

module.exports = router;
</code>```

This is the end point on the server that responsible for getting the session - session.js - This is where the problem appears - the res.session has a session ID which is different that the one I created after the login

```<code>const express = require('express');
const router = express.Router();

 hasSession : function(req, res) //This is where the problem appears - the res.session has a session ID which is different that the one I created after the login
{
    if (req.session.user)
    {
        res.status(200).json(
            {
                recordsets: [{Roles: req.session.Roles, UserName: req.session.user.username}]
            });
    }
    else{
        res.status(200).json({});
    }
}

router.use("/", (req, res, next) => { return sessionManagement.hasSession(req, res, next)});

module.exports = router;
</code>```

Client side:

```<code>//HTML:
<div>
  <label>Username:</label>
  <input type="text" name="username" [(ngModel)]="userName" />
</div>
<div>
  <label>Password:</label>
  <input type="password" name="password" [(ngModel)]="password"/>
</div>
<div>
  <button (click)="login()">Login</button>
</div>

//COMPONENT:

login()
  {
    this.srv.login(this.userName, this.password).subscribe(result =>
      {
        if (<result is valid>)
        {
          this.router.navigate(['/dashboard']);
        }

      }
    );
  }

//This reach the node.js endpoint and routing to the session.js end point - it is executes when the router-outlet activated in the app.component:
/*
    onActivate(componentRef : any)
      {
        if (componentRef instanceof LoginComponent)
        {
          componentRef.getSession();
        }
      }
*/

getSession() : void
  {
    this.sessionService.getSession().subscribe( result =>
      {
        if (<result is valid>)
        {
          this.router.navigate(['/dashboard']);
        }
      });
  }
</code>```

I found a similar question on github - no solution yet:
https://github.com/expressjs/session/issues/515
but it might be a cookie <-> server configuration issue.

答:
Found the problem - the root cause was that the client didn't send a cookie when making an httprequest.
2 things needed to be done in order to solve the problem:

1. CORS Definition

Set the CORS definition to creadentials: true along with the origin (the host name of the client, which is probably with a different port\hostname):

```<code>app.use(cors({
    origin: config.origin,
    credentials: true
}));
</code>```

2. Set crendentials

For every http rest method (get and post, in my case) add withCredentials property with a value of true:

```<code>return this.http.get<any>(<path>, { withCredentials: true })
</code>```

or

```<code>return this.http.post<any>(<path>, <body>, { withCredentials:true })
</code>```

Body:
I'm trying to have a session containing user data in the node.js/express FW.
I'm using express-session. I'm not using session store yet.
I have 2 pages in the client (angular) where I iterate between - Login and Dashboard. The idea is to create the session after successful login, then routing to the dashboard page. In the dashboard page I have an anchor with routinlink to the login:

BackToLogin

When navigating back to the loginPage (when activating a route), I execute a service with an end-point to the express server which check if the request has a session with a request in it (I expect it to be). The problem is that I see that the session is not the same session (the id changes)

See my code:
Node.js side - server.js file:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');

const session = require ('express-session');
var cookieParser = require('cookie-parser');
const SESS_NAME = 'sid';

app.use(session({
    name:SESS_NAME,
    key: 'user_sid',
    resave:false,
    saveUninitialized:false,
    secure: process.env.NODE_ENV ==="production",
    secret:'<some random text>',
    cookie:{

            httpOnly: true,
            secure: process.env.NODE_ENV ==="production",
            expires: 60000
           }
}));

app.use(bodyParser.text());
app.use(bodyParser);
app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(cors()); //No limitation for test reasons

app.use(cookieParser());

//disabled on purpose
//var sessionManagement = require('./middleware/sessionManagement');
// API
app.use("/", require("./api/v1/routes.js"))//This file includes:
/*
const express = require('express');
const router = express.Router();
router.use("/login", require('./login'));
router.use("/session", require('./session'));
module.exports = router;
*/
...etc
app.listen(config.port, () => console.log(`Process ${process.pid}: Listening on port ${config.port}`));

login.js on the server: responsible for validating user and store user data in session:

const express = require('express');
const router = express.Router();
const schema = require('./objectSchemaJson.schema.json');
const scehmaCheck = require('../../middleware/checkForSchema')(schema);//this is
a schema check (middleware) - if suceeded continue (next)

const storeSession = (req, dataResult) =>
{
    if (<dataResult return with valid use data>) //This is "where the magic happanes"
    {
        req.session.user = {
            username: <get userName from dataResult>,
            ID: <Get ID from dataResult>,
            Role: <Get Role from dataResult>
        }
    }
}
router.use("/", scehmaCheck, (req, res, next) => {
    return GetUserDataFROmDB(req.body).then((dataResult) => { //reaching the DB - not mentioned here on purpose
        storeSession(req, dataResult); // This is where the session set with user data
        res.status(200).json(dataResult);
    }).catch((err) => {
        next({
            details: err
        })
    });
});

module.exports = router;

This is the end point on the server that responsible for getting the session - session.js - This is where the problem appears - the res.session has a session ID which is different that the one I created after the login

const express = require('express');
const router = express.Router();

 hasSession : function(req, res) //This is where the problem appears - the res.session has a session ID which is different that the one I created after the login
{
    if (req.session.user)
    {
        res.status(200).json(
            {
                recordsets: [{Roles: req.session.Roles, UserName: req.session.user.username}]
            });
    }
    else{
        res.status(200).json({});
    }
}

router.use("/", (req, res, next) => { return sessionManagement.hasSession(req, res, next)});

module.exports = router;

Client side:

//HTML:

  Username:
  <input type="text" name="username" [(ngModel)]="userName" />

  Password:
  <input type="password" name="password" [(ngModel)]="password"/>

  <button (click)="login()">Login</button>

//COMPONENT:

login()
  {
    this.srv.login(this.userName, this.password).subscribe(result =>
      {
        if (<result is valid>)
        {
          this.router.navigate(['/dashboard']);
        }

      }
    );
  }

//This reach the node.js endpoint and routing to the session.js end point - it is executes when the router-outlet activated in the app.component:
/*
    onActivate(componentRef : any)
      {
        if (componentRef instanceof LoginComponent)
        {
          componentRef.getSession();
        }
      }
*/

getSession() : void
  {
    this.sessionService.getSession().subscribe( result =>
      {
        if (<result is valid>)
        {
          this.router.navigate(['/dashboard']);
        }
      });
  }

I found a similar question on github - no solution yet:
https://github.com/expressjs/session/issues/515
but it might be a cookie <-> server configuration issue.

Body:
Found the problem - the root cause was that the client didn't send a cookie when making an httprequest.
2 things needed to be done in order to solve the problem:

1. CORS Definition

Set the CORS definition to creadentials: true along with the origin (the host name of the client, which is probably with a different port\hostname):

app.use(cors({
    origin: config.origin,
    credentials: true
}));

2. Set crendentials

For every http rest method (get and post, in my case) add withCredentials property with a value of true:

return this.http.get<any>(<path>, { withCredentials: true })

or

return this.http.post<any>(<path>, <body>, { withCredentials:true })


问:
Printing random data from list into file
I have 3 lists

```<code>x = ["1", "2", "3"]

y = ["4", "5", "6"]

z = ["7", "8", "9"]
</code>```

I need to write into a file with a random from x, y, and z on to a new line each time.

```<code>Keyword = input("Directory to list")

with open(Keyword) as f:
        content = f.readlines()

    content = [x.strip() for x in content]

    with open("test.txt") as w:
        w.write(PageFormat + )
</code>```

Output should look like this:

```<code>2 // 6 // 8

3 // 4 // 9

1 // 5 // 9

2 // 5 // 9

1 // 4 // 7
</code>```

("/" included)

Body:
I have 3 lists

x = ["1", "2", "3"]

y = ["4", "5", "6"]

z = ["7", "8", "9"]

I need to write into a file with a random from x, y, and z on to a new line each time.

Keyword = input("Directory to list")

with open(Keyword) as f:
        content = f.readlines()

    content = [x.strip() for x in content]

    with open("test.txt") as w:
        w.write(PageFormat + )

Output should look like this:

2 // 6 // 8

3 // 4 // 9

1 // 5 // 9

2 // 5 // 9

1 // 4 // 7

("/" included)

Body:
from random import choice

x = ["1", "2", "3"]

y = ["4", "5", "6"]

z = ["7", "8", "9"]

with open("test.txt", "w") as fp:
    fp.write(choice(x) + "//" + choice(y) + "//" + choice(z))


问:
Cannot compile curl and libgcc as a static library in MinGW/CLion (c++)
I am trying to compile curl and libgcc as a static library so I would not have to include dll files with my program. I am having problems with libcurl.dll not found when I run the executable through command prompt. Also, there is another error libgcc_s_dw2-1.dll not found.

It works when I put the dll files in the same folder as executable but that is not what I am really fond of. I have put -DCURL_STATICLIB in CMAKE_CXX_FLAGS as suggested here:

https://curl.haxx.se/docs/install.html

Here is my CMakeLists.txt

```<code>project(ham)

set(CMAKE_CXX_STANDARD 14)

set(CMAKE_C_FLAGS -m32 -DCURL_STATICLIB)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32 -std=c++14 -LC:/curlx86 -lcurl")

set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -static-libgcc -static-libstdc++ -lwsock32 -lws2_32 -lwinmm")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-Bstatic,--whole-archive -Wl,--no-whole-archive")

project(untitled3)
add_executable(ham Ham/ham.cpp)

target_link_libraries(ham "C:/curlx86/libcurl.dll.a")
</code>```

I want my program to run without including any extra dll files. What should I do ?

Edit
When I use
target_link_libraries(ham "C:/curlx86/libcurl.dll.a")

I get these errors.

c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(easy.o):(.text+0x8f): undefined reference to libssh2_init'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(easy.o):(.text+0x16b): undefined reference tolibssh2_exit'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0xcd): undefined reference to nghttp2_version'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x2ca): undefined reference tonghttp2_submit_rst_stream'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x2dc): undefined reference to nghttp2_session_send'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x31d): undefined reference tonghttp2_session_set_stream_user_data'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x3c0): undefined reference to nghttp2_pack_settings_payload'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x4bd): undefined reference tonghttp2_session_resume_data'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x4fe): undefined reference to nghttp2_session_mem_recv'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x51c): undefined reference tonghttp2_strerror'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x5c3): undefined reference to nghttp2_priority_spec_init'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x614): undefined reference tonghttp2_submit_priority'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x621): undefined reference to `nghttp2_session_send'

```<code>

</code>```

答:
Part 1. Setting up openssl v1.1.1b

Download the openssl v1.1.1b package (not the installer)

Download and install MSYS2

Open msys.exe (not mingw32.exe or mingw.exe)

Run this command to install perl and other packages:

```<code>pacman -S make perl msys2-devel libcrypt-devel perl-CPAN mingw-w64-i686-toolchain
</code>```

Now close msys.exe and open mingw32.exe

Change directory to wherever you extracted the openssl package, in my case it's this:

```<code>cd "C:\Users\John\Downloads\openssl-1.1.1b\openssl-1.1.1b"
</code>```

Before continuing any further you have to add #include <windows.h> to these files underneath the directory:

crypto\dso\dso_win32.c

crypto\init.c

Run (this compiles openssl as a static library):

```<code>./configure --prefix=c:/OpenSSLx86 --openssldir=c:/OpenSSLx86 no-threads no-idea no-shared mingw
</code>```

Run make clean

Run make depend

Run make

Run make install

Part 2. Building curl with openssl v1.1.1b

Download and extract the curl package

Change directory:

```<code>cd "C:\Users\John\Downloads\curl\curl-7.65.0"
</code>```

Edit lib\curl_setup.h and add the following lines to reduce the size of the compiled library by choosing only the options you will use. I will be using only the SMTP protocol, so I am disabling the others.

#define CURL_DISABLE_TFTP
#define CURL_DISABLE_FTP
#define CURL_DISABLE_LDAP
#define CURL_DISABLE_TELNET
#define CURL_DISABLE_DICT
#define CURL_DISABLE_FILE
#define CURL_DISABLE_RTSP
#define CURL_DISABLE_POP3
#define CURL_DISABLE_IMAP
//#define CURL_DISABLE_SMTP
#define CURL_DISABLE_GOPHER
#define CURL_DISABLE_SMB
```
<ol start="4">
<li>Set <code>OPENSSL_PATH = C:\OpenSSLx86</code> in these files:</li>
</ol>
<ul>
<li><code>lib\Makefile.m32</code></li>
<li><code>src\Makefile.m32</code></li>
</ul>
<ol start="5">
<li><p>Run <code>make mingw32-ssl</code></p>
</li>
<li><p>Now copy <code>libcurl.a</code> from <code>lib</code> to <code>C:\curlx86</code> and you are good to go.</p>
</li>
</ol>
<p>Here is my final <code>CMakeLists.txt</code>:</p>
<pre class="lang-cmake prettyprint-override"><code>cmake_minimum_required(VERSION 3.3)     #curl
project(ham)

set(CMAKE_CXX_STANDARD 14)

add_compile_definitions(
        CURL_STATICLIB
        WITH_SSL=STATIC
)
#CURL_DISABLE_SMTP

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m32")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32 -LC:/curlx86 -lcurl -LC:/OpenSSLx86/lib -lssl -LC:/OpenSSLx86/lib -lcrypto")

set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -static-libgcc -static-libstdc++ -lwsock32 -lws2_32 -lwinmm -lcrypt32")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-Bstatic,--whole-archive -lwinpthread -Wl,--no-whole-archive")

project(untitled3)
add_executable(ham Ham/ham.cpp)

target_link_libraries(ham "C:/curlx86/libcurl.a"  "C:/OpenSSLx86/lib/libssl.a" "C:/OpenSSLx86/lib/libcrypto.a")
</code>```

Body:
I am trying to compile curl and libgcc as a static library so I would not have to include dll files with my program. I am having problems with libcurl.dll not found when I run the executable through command prompt. Also, there is another error libgcc_s_dw2-1.dll not found.

It works when I put the dll files in the same folder as executable but that is not what I am really fond of. I have put -DCURL_STATICLIB in CMAKE_CXX_FLAGS as suggested here:

https://curl.haxx.se/docs/install.html

Here is my CMakeLists.txt

project(ham)

set(CMAKE_CXX_STANDARD 14)

set(CMAKE_C_FLAGS -m32 -DCURL_STATICLIB)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32 -std=c++14 -LC:/curlx86 -lcurl")

set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -static-libgcc -static-libstdc++ -lwsock32 -lws2_32 -lwinmm")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-Bstatic,--whole-archive -Wl,--no-whole-archive")

project(untitled3)
add_executable(ham Ham/ham.cpp)

target_link_libraries(ham "C:/curlx86/libcurl.dll.a")

I want my program to run without including any extra dll files. What should I do ?

Edit
When I use
target_link_libraries(ham "C:/curlx86/libcurl.dll.a")

I get these errors.

c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(easy.o):(.text+0x8f): undefined reference to libssh2_init'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(easy.o):(.text+0x16b): undefined reference tolibssh2_exit'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0xcd): undefined reference to nghttp2_version'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x2ca): undefined reference tonghttp2_submit_rst_stream'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x2dc): undefined reference to nghttp2_session_send'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x31d): undefined reference tonghttp2_session_set_stream_user_data'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x3c0): undefined reference to nghttp2_pack_settings_payload'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x4bd): undefined reference tonghttp2_session_resume_data'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x4fe): undefined reference to nghttp2_session_mem_recv'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x51c): undefined reference tonghttp2_strerror'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x5c3): undefined reference to nghttp2_priority_spec_init'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x614): undefined reference tonghttp2_submit_priority'
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:/curlx86/libcurl.a(http2.o):(.text+0x621): undefined reference to `nghttp2_session_send'

Body:
Part 1. Setting up openssl v1.1.1b

Download the openssl v1.1.1b package (not the installer)

Download and install MSYS2

Open msys.exe (not mingw32.exe or mingw.exe)

Run this command to install perl and other packages:

pacman -S make perl msys2-devel libcrypt-devel perl-CPAN mingw-w64-i686-toolchain

Now close msys.exe and open mingw32.exe

Change directory to wherever you extracted the openssl package, in my case it's this:

cd "C:\Users\John\Downloads\openssl-1.1.1b\openssl-1.1.1b"

Before continuing any further you have to add #include <windows.h> to these files underneath the directory:

crypto\dso\dso_win32.c

crypto\init.c

Run (this compiles openssl as a static library):

./configure --prefix=c:/OpenSSLx86 --openssldir=c:/OpenSSLx86 no-threads no-idea no-shared mingw

Run make clean

Run make depend

Run make

Run make install

Part 2. Building curl with openssl v1.1.1b

Download and extract the curl package

Change directory:

cd "C:\Users\John\Downloads\curl\curl-7.65.0"

Edit lib\curl_setup.h and add the following lines to reduce the size of the compiled library by choosing only the options you will use. I will be using only the SMTP protocol, so I am disabling the others.

#define CURL_DISABLE_TFTP
#define CURL_DISABLE_FTP
#define CURL_DISABLE_LDAP
#define CURL_DISABLE_TELNET
#define CURL_DISABLE_DICT
#define CURL_DISABLE_FILE
#define CURL_DISABLE_RTSP
#define CURL_DISABLE_POP3
#define CURL_DISABLE_IMAP
//#define CURL_DISABLE_SMTP
#define CURL_DISABLE_GOPHER
#define CURL_DISABLE_SMB

Set OPENSSL_PATH = C:\OpenSSLx86 in these files:

lib\Makefile.m32

src\Makefile.m32

Run make mingw32-ssl

Now copy libcurl.a from lib to C:\curlx86 and you are good to go.

Here is my final CMakeLists.txt:

cmake_minimum_required(VERSION 3.3)     #curl
project(ham)

set(CMAKE_CXX_STANDARD 14)

add_compile_definitions(
        CURL_STATICLIB
        WITH_SSL=STATIC
)
#CURL_DISABLE_SMTP

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m32")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32 -LC:/curlx86 -lcurl -LC:/OpenSSLx86/lib -lssl -LC:/OpenSSLx86/lib -lcrypto")

set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -static-libgcc -static-libstdc++ -lwsock32 -lws2_32 -lwinmm -lcrypt32")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-Bstatic,--whole-archive -lwinpthread -Wl,--no-whole-archive")

project(untitled3)
add_executable(ham Ham/ham.cpp)

target_link_libraries(ham "C:/curlx86/libcurl.a"  "C:/OpenSSLx86/lib/libssl.a" "C:/OpenSSLx86/lib/libcrypto.a")


问:
How to apply ngx-pipe "unique" with condition?
I have a list of object contains a property: groupID, but only some of elements held the value for this property. In the template, I want to use ngFor with unique pipe for the list. But after applied, it also did for the property's value is null.

Is there a way I could applied some kind of condition with the pipe?

Below is the simple example for my problem.

```<code>list = [
 {ID: "001", groupID: "246"},
 {ID: "002", groupID: "246"},
 {ID: "003", groupID: ""},
 {ID: "004", groupID: ""},
 {ID: "005", groupID: "135"},
 {ID: "006", groupID: "135"},
 {ID: "007", groupID: ""},
]
</code>```

HTML

```<code><div *ngFor="let l of list | unique: 'groupID'">
 <app-A [inputObject]="l['groupID']" *ngIf="l['groupID']!=''"></app-A>
 <app-B [inputObject]="l" *ngIf="l['groupID']==''"></app-B>
</div>
</code>```

Then A component received two objects, {ID: "001", groupID: "246"}, and {ID: "005", groupID: "135"}, which are correct. However, B component only received {ID: "003", groupID: ""}, because the unique pipe also caught the empty value.

答:
If you look into ngx-pipes unique pipe source code, you'll notice that you cannot pass any other argument to it in order to achieve what you want.

First idea could be to discuss that with the author and eventually you could come up with a pull request.

Second idea is simply to create your own pipe, here's my take:

```<code>@Pipe({
  name: 'unique'
})
export class UniquePipe implements PipeTransform {
  transform(arr: any[], propertyName: string): any {
    const res = arr.reduce((acc, curr) => {
      if (!acc.valuesSet.has(curr[propertyName])) {
        acc.array.push(curr)
        acc.valuesSet.add(curr[propertyName]);
      }

      return acc;
    }, { valuesSet: new Set(), array: [] })

    return res.array;
  }
}
</code>```

And a demo: https://stackblitz.com/edit/angular-3sfcw3

Body:
I have a list of object contains a property: groupID, but only some of elements held the value for this property. In the template, I want to use ngFor with unique pipe for the list. But after applied, it also did for the property's value is null.

Is there a way I could applied some kind of condition with the pipe?

Below is the simple example for my problem.

list = [
 {ID: "001", groupID: "246"},
 {ID: "002", groupID: "246"},
 {ID: "003", groupID: ""},
 {ID: "004", groupID: ""},
 {ID: "005", groupID: "135"},
 {ID: "006", groupID: "135"},
 {ID: "007", groupID: ""},
]

HTML

 <app-A [inputObject]="l['groupID']" *ngIf="l['groupID']!=''"></app-A>
 <app-B [inputObject]="l" *ngIf="l['groupID']==''"></app-B>

Then A component received two objects, {ID: "001", groupID: "246"}, and {ID: "005", groupID: "135"}, which are correct. However, B component only received {ID: "003", groupID: ""}, because the unique pipe also caught the empty value.

Body:
If you look into ngx-pipes unique pipe source code, you'll notice that you cannot pass any other argument to it in order to achieve what you want.

First idea could be to discuss that with the author and eventually you could come up with a pull request.

Second idea is simply to create your own pipe, here's my take:

@Pipe({
  name: 'unique'
})
export class UniquePipe implements PipeTransform {
  transform(arr: any[], propertyName: string): any {
    const res = arr.reduce((acc, curr) => {
      if (!acc.valuesSet.has(curr[propertyName])) {
        acc.array.push(curr)
        acc.valuesSet.add(curr[propertyName]);
      }

      return acc;
    }, { valuesSet: new Set(), array: [] })

    return res.array;
  }
}

And a demo: https://stackblitz.com/edit/angular-3sfcw3


问:
Which program will be bigger in size - RISC or CISC?
Let's say I have a hello world program, which print 'Hello World'.
Now, I have compiled this program for CISC Processor and next I have compiled for RISC processor. My question is which will have bigger code size and why?</p>

答: The programs will be the same size. As both of them consist simply of passing a string constant to a system call.</p>


问:
Multer - Stop File Uploading If Form Validation Fails
i have mixed form with file upload and normal form fields, and while sending this form to Nodejs server i am validating form but problem is that i do not know how to stop uploading the file if (for example) one of the form field is empty.
so for example:

```<code>if(name.trim().length < 1){
   //stop uploading of file
   return res.status(409).send({
     message: 'provide name'
   })
 }
</code>```

how can i do that (Multer & ExpressJS)?

答:
I was using following code in my case (node & express).

From routes.js file I am calling this insertRating method. like below

```<code>//routes.js
router.post('/common/insertrating',RatingService.insertRating);

//controller class
// storage & upload are configurations

var storage = multer.diskStorage({
destination: function (req, file, cb) {

    var dateObj = new Date();
    var month = dateObj.getUTCMonth() + 1; //months from 1-12

    var year = dateObj.getUTCFullYear();
    console.log("month and yeare are " + month + " year " + year);
    var quarterMonth = "";
    var quarterYear = "";

    var dir_path = '../../uploads/' + year + '/' + quarterMonth;

    mkdirp(dir_path, function (err) {
        if (err) {
            console.log("error is cominggg insidee");
        }
        else {
            console.log("folder is createtd ")
        }
        cb(null, '../../uploads/' + year + '/' + quarterMonth)
    })

    console.log("incomingggg to destination");

},
filename: function (req, file, cb) {

    console.log("incoming to filename")
    cb(null, Date.now() + "_" + file.originalname);
},

});

var upload = multer({
storage: storage,
limits: {
    fileSize: 1048576 * 5
},
fileFilter: function (req, file, callback) {
    var ext = path.extname(file.originalname);
    ext = ext.toLowerCase();
    console.log("ext isss " + ext);

    if (ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg' && ext !== '.pdf' && ext !== '.txt'
        && ext !== '.doc' && ext !== '.docx' && ext !== '.xlsx' && ext !== '.xls'
    ) {
        return callback(new Error('Only specific extensions are allowed'))
    }
    callback(null, true)
}

}).array('files', 5);

 // calling below insertRating method from routes js file...

exports.insertRating = async function (req, res) {
        let quarterData = req.query.quarterData;
        quarterData = JSON.parse(quarterData);

        if (quarterData != null) { // here you can check your custom condition like name.trim().length
               req.files = []; // not required
               upload(req, res, async function (err) { // calling upload
                            if (err) {

                                res.send("error is cominggg")
                                return;
                            } else {
                                res.send("file is uploaded");
                      }

                            //
               });

        }
       else {
               res.send("filed must not be empty");
       }
}
</code>```

Body:
i have mixed form with file upload and normal form fields, and while sending this form to Nodejs server i am validating form but problem is that i do not know how to stop uploading the file if (for example) one of the form field is empty.
so for example:

if(name.trim().length < 1){
   //stop uploading of file
   return res.status(409).send({
     message: 'provide name'
   })
 }

how can i do that (Multer & ExpressJS)?

Body:
I was using following code in my case (node & express).

From routes.js file I am calling this insertRating method. like below

//routes.js
router.post('/common/insertrating',RatingService.insertRating);

//controller class
// storage & upload are configurations

var storage = multer.diskStorage({
destination: function (req, file, cb) {

    var dateObj = new Date();
    var month = dateObj.getUTCMonth() + 1; //months from 1-12

    var year = dateObj.getUTCFullYear();
    console.log("month and yeare are " + month + " year " + year);
    var quarterMonth = "";
    var quarterYear = "";

    var dir_path = '../../uploads/' + year + '/' + quarterMonth;

    mkdirp(dir_path, function (err) {
        if (err) {
            console.log("error is cominggg insidee");
        }
        else {
            console.log("folder is createtd ")
        }
        cb(null, '../../uploads/' + year + '/' + quarterMonth)
    })

    console.log("incomingggg to destination");

},
filename: function (req, file, cb) {

    console.log("incoming to filename")
    cb(null, Date.now() + "_" + file.originalname);
},

});

var upload = multer({
storage: storage,
limits: {
    fileSize: 1048576 * 5
},
fileFilter: function (req, file, callback) {
    var ext = path.extname(file.originalname);
    ext = ext.toLowerCase();
    console.log("ext isss " + ext);

    if (ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg' && ext !== '.pdf' && ext !== '.txt'
        && ext !== '.doc' && ext !== '.docx' && ext !== '.xlsx' && ext !== '.xls'
    ) {
        return callback(new Error('Only specific extensions are allowed'))
    }
    callback(null, true)
}

}).array('files', 5);

 // calling below insertRating method from routes js file...

exports.insertRating = async function (req, res) {
        let quarterData = req.query.quarterData;
        quarterData = JSON.parse(quarterData);

        if (quarterData != null) { // here you can check your custom condition like name.trim().length
               req.files = []; // not required
               upload(req, res, async function (err) { // calling upload
                            if (err) {

                                res.send("error is cominggg")
                                return;
                            } else {
                                res.send("file is uploaded");
                      }

                            //
               });

        }
       else {
               res.send("filed must not be empty");
       }
}


问:
How to find the unique list entries in a python dataframe?
I have a dataset which has the movie title along with the different genres that it falls under. Each movie has more than one genre. Hence, for the entire dataset I want to find the total number of unique genres that are present.

I am not able to use df.unique() as it is a list in each column of the DataFrame itself.

```<code>movieId title   genres
0   1   Toy Story (1995)    Adventure|Animation|Children|Comedy|Fantasy
1   2   Jumanji (1995)  Adventure|Children|Fantasy
2   3   Grumpier Old Men (1995) Comedy|Romance
3   4   Waiting to Exhale (1995)    Comedy|Drama|Romance
4   5   Father of the Bride Part II (1995)  Comedy
5   6   Heat (1995) Action|Crime|Thriller
6   7   Sabrina (1995)  Comedy|Romance
7   8   Tom and Huck (1995) Adventure|Children
8   9   Sudden Death (1995) Action
9   10  GoldenEye (1995)    Action|Adventure|Thriller
10  11  American President, The (1995)  Comedy|Drama|Romance
11  12  Dracula: Dead and Loving It (1995)  Comedy|Horror
12  13  Balto (1995)    Adventure|Animation|Children
13  14  Nixon (1995)    Drama
14  15  Cutthroat Island (1995) Action|Adventure|Romance
15  16  Casino (1995)   Crime|Drama
16  17  Sense and Sensibility (1995)    Drama|Romance
17  18  Four Rooms (1995)   Comedy
18  19  Ace Ventura: When Nature Calls (1995)   Comedy
19  20  Money Train (1995)  Action|Comedy|Crime|Drama|Thriller
20  21  Get Shorty (1995)   Comedy|Crime|Thriller
21  22  Copycat (1995)  Crime|Drama|Horror|Mystery|Thriller
22  23  Assassins (1995)    Action|Crime|Thriller
23  24  Powder (1995)   Drama|Sci-Fi
24  25  Leaving Las Vegas (1995)    Drama|Romance
25  26  Othello (1995)  Drama
26  27  Now and Then (1995) Children|Drama
27  28  Persuasion (1995)   Drama|Romance
28  29  City of Lost Children, The (Cité des enfants p...
</code>```

This is the dataset for movies.

Under the genres column I want to split Action|Comedy|Crime|Drama|Thriller into Action, Comedy, Crime, Drama, Thriller.

Also for the entire dataset which is as a DataFrame now, I want to find the unique genres.

答:
Try following:</p>

```<code>df = pda.read_csv('movies.csv')
df['genres'] = df['genres'].apply(lambda x: x.strip().split('|'))
df['count'] = df['genres'].apply(lambda y: len(y))
print(df)

OUTPUT :

   movie   Id  ...                                             genres count
     0    1  ...  [Adventure, Animation, Children, Comedy, Fantasy]     5
     1    2  ...                     [Adventure, Children, Fantasy]     3
     2    3  ...                                  [Comedy, Romance]     2
     3    4  ...                           [Comedy, Drama, Romance]     3
     4    5  ...                                           [Comedy]     1
     5    6  ...                          [Action, Crime, Thriller]     3
</code>```

Body:
I have a dataset which has the movie title along with the different genres that it falls under. Each movie has more than one genre. Hence, for the entire dataset I want to find the total number of unique genres that are present.

I am not able to use df.unique() as it is a list in each column of the DataFrame itself.

movieId title   genres
0   1   Toy Story (1995)    Adventure|Animation|Children|Comedy|Fantasy
1   2   Jumanji (1995)  Adventure|Children|Fantasy
2   3   Grumpier Old Men (1995) Comedy|Romance
3   4   Waiting to Exhale (1995)    Comedy|Drama|Romance
4   5   Father of the Bride Part II (1995)  Comedy
5   6   Heat (1995) Action|Crime|Thriller
6   7   Sabrina (1995)  Comedy|Romance
7   8   Tom and Huck (1995) Adventure|Children
8   9   Sudden Death (1995) Action
9   10  GoldenEye (1995)    Action|Adventure|Thriller
10  11  American President, The (1995)  Comedy|Drama|Romance
11  12  Dracula: Dead and Loving It (1995)  Comedy|Horror
12  13  Balto (1995)    Adventure|Animation|Children
13  14  Nixon (1995)    Drama
14  15  Cutthroat Island (1995) Action|Adventure|Romance
15  16  Casino (1995)   Crime|Drama
16  17  Sense and Sensibility (1995)    Drama|Romance
17  18  Four Rooms (1995)   Comedy
18  19  Ace Ventura: When Nature Calls (1995)   Comedy
19  20  Money Train (1995)  Action|Comedy|Crime|Drama|Thriller
20  21  Get Shorty (1995)   Comedy|Crime|Thriller
21  22  Copycat (1995)  Crime|Drama|Horror|Mystery|Thriller
22  23  Assassins (1995)    Action|Crime|Thriller
23  24  Powder (1995)   Drama|Sci-Fi
24  25  Leaving Las Vegas (1995)    Drama|Romance
25  26  Othello (1995)  Drama
26  27  Now and Then (1995) Children|Drama
27  28  Persuasion (1995)   Drama|Romance
28  29  City of Lost Children, The (Cité des enfants p...

This is the dataset for movies.

Under the genres column I want to split Action|Comedy|Crime|Drama|Thriller into Action, Comedy, Crime, Drama, Thriller.

Also for the entire dataset which is as a DataFrame now, I want to find the unique genres.

Body:
Try following:

df = pda.read_csv('movies.csv')
df['genres'] = df['genres'].apply(lambda x: x.strip().split('|'))
df['count'] = df['genres'].apply(lambda y: len(y))
print(df)

OUTPUT :

   movie   Id  ...                                             genres count
     0    1  ...  [Adventure, Animation, Children, Comedy, Fantasy]     5
     1    2  ...                     [Adventure, Children, Fantasy]     3
     2    3  ...                                  [Comedy, Romance]     2
     3    4  ...                           [Comedy, Drama, Romance]     3
     4    5  ...                                           [Comedy]     1
     5    6  ...                          [Action, Crime, Thriller]     3