问:
How do I use Bash on Ubuntu on Windows (WSL) for my VS Code terminal?
While other questions deal with how to use things like git-bash, giving the new WSL a spin as the terminal for VS Code is not the same: it gives you access to bash running on an actual Ubuntu Linux subsystem, instead of the git-bash terminal running on the Windows subsystem.

So how do we get it working as the VS Code terminal, and particularly how do we get it working as a functional dev environment terminal?

Unlike git-bash, this is unfortunately not as simple, because the Ubuntu Linux configuration in WSL can provide some gotchas, such as NPM trying (and failing) to run from your Windows Program Files directory due to the interaction between WSL and Windows itself in terms of pathing, and some packages such as Compass failing for what are not necessarily immediately obvious reasons to someone who is not used to developing on Linux. What's a simple way to have a reliable WSL terminal environment for VS Code where most frequently used tools will run when installed via apt-get or npm?

答:
This answer seeks to help others avoid spending 1-2 hours troubleshooting and slowly finding disparate solutions for common problems when using WSL for the terminal in VS Code. It does not cover installing specific packages, but rather common ones that may not properly install as dependencies when installing things that do rely on their presence, and on fixing related common settings.

Summary of steps

WSL installed

VS Code (or other IDE) configured for terminal

NPM installed & path fix in .profile (may help with other tools)

build-essential installed (helps with any tools that use make/gcc/etc)

VS Code Tasks using WSL

Extras

Getting Started & Requirements

You must have WSL installed. (Which means you must be running 64 bit Windows 10, with the appropriate updates) Follow the install guide if not already installed. This will require some reboots.

VS Code Terminal Configuration

Either the CTRL+, keyboard shortcut, or File → Preferences → Settings

In the top right of the editing window, make sure you are working in the correct context for you: either User Settings or Workspace Settings.

In the settings search bar, type terminal.integrated.shell.windows (or whatever gets you far enough long)

Find the setting in the actual settings file, use Edit (mouse over the line, it will be on the left: on a touch screen without a mouse, you should be able to simply tap to the left of the line), and select Replace in Settings

In the right pane, modify the entry created in the modified json file: replace the previous setting with

```<code>"C:\\WINDOWS\\Sysnative\\bash.exe"
</code>```

Other IDEs: IntelliJ

Open Settings/Tools/Terminal and set the "Shell path" field to "C:\Users\USERNAME\AppData\Local\Microsoft\WindowsApps\ubuntu.exe"

Making your WSL Ubuntu Bash Terminal functional for dev

When you use CTRL+` to open the terminal, you should now have a bash terminal.

If this is the first time you have run bash.exe, you may be asked about installing Ubuntu. Do so. Once your installation is complete, choose your username and password to be used in WSL Ubuntu. These do not have to coincide with your current Windows account, and it's important to note that they will not change based on changes to your Windows account's password.

Once you are done, you will have a bash command prompt in your terminal.

Note that unlike git-bash on Windows, this is a separate environment. While it can be used to launch Windows software outside of itself, you will need appropriate Ubuntu packages to run them within the actual terminal.

Currently, WSL does not come loaded with everything you might expect or be used to having, and some things can conflict with software you have loaded in Windows, based on default profile settings.

Updates & git

Note: I'm going to document these as sudo for people who simply need single pieces of this, but one option at the start is to instead sudo su and simply running the following commands without sudo.

Make sure your Ubuntu packages are up to date:

```<code>sudo apt-get -y update
sudo apt-get -y upgrade
sudo apt-get -y dist-upgrade
sudo apt autoremove
</code>```

Install git:

```<code>sudo apt-get install git
</code>```

Node.js & NPM

If you already have Node or NPM loaded in Windows, running them in Ubuntu can get problematic due to path issues. So, you need to install the Ubuntu native versions and ensure that they are used instead.

First, install node.js with NPM.
(alternate: install NVM and use it to install node.js)

After installing, running npm commands will probably fail: for example, npm -v will probably give you:

```<code>: not foundram Files/nodejs/npm: 3: /mnt/c/Program Files/nodejs/npm:
: not foundram Files/nodejs/npm: 5: /mnt/c/Program Files/nodejs/npm:
/mnt/c/Program Files/nodejs/npm: 6: /mnt/c/Program Files/nodejs/npm: Syntax error: word unexpected (expecting "in")
</code>```

This is due to a pathing issue with a fairly straightforward solution. Using your favorite CLI editor (such as nano, vim, emacs, cat and sed… etc), open your ~/.profile

```<code>nano ~/.profile
</code>```

Note: do NOT attempt to edit Linux files using Windows tools. (Thanks to @david-c-rankin's comment for the official link with the bold red text explaining this) If you don't want to use a CLI editor for this in the terminal, see the bottom of this post for a link on how to get a GUI one running.

Currently, the default bash PATH variable in WSL is

```<code>PATH="$HOME/bin:$HOME/.local/bin:$PATH"
</code>```

Which is injecting the windows path after the first two binary directories. Unfortunately, this doesn't result in /usr/bin being used before the windows installed npm, so add that before the final $PATH:

```<code>PATH="$HOME/bin:$HOME/.local/bin:/usr/bin:$PATH"
</code>```

Save out, and then either reload the terminal or just source the path file

```<code>source ~/.profile
</code>```

Build-essential

If you are using anything which requires compiling or otherwise uses make, it's almost guaranteed that you will need these installed; so if you did not install them while installing node.js, do so. It's much easier to simply use the build-essential package rather than try to install everything separately.

Note that packages such as Compass which rely on Ruby FFI will fail without these. If you are having trouble properly installing and running a tool, making sure you have gcc and make installed can be a good place to start.

```<code>sudo apt-get install -y build-essential
</code>```

Running Tasks using Ubuntu

Note that if you use VS Code's tasks.json to run build tasks, by default it will still run them using the Windows subsystem instead of the Ubuntu one. Sometimes this may be what you want, but if you've just finished installing grunt-cli in Ubuntu and not Windows, it's probably not.

VS Code recently had the 2017 May update to how Tasks work that allows it to set the task runner as the terminal. This is by far the easiest way to migrate tasks over.

Simply set

```<code>"runner": "terminal",
</code>```

in your tasks.json and you're done (assuming you have all of the appropriate tools you are trying to run now installed in WSL Ubuntu).

This is very portable, ideally requiring no changes between systems which do or do not have WSL, or to other OSes, and is the method I would recommend.

As of the moment, this method spawns another TERMINAL tab instance (accessed from the drop down). You can still set up appropriate watchers, but it does mean that it's no longer sitting on the OUTPUT tab.

The old method is capable of invoking the WSL Ubunutu Bash shell and having it show up in OUTPUT, and involves either calling bash.exe with the -c argument or using a shell script. It unfortunately is not as semantic, since we are making bash our command and passing it what we want to run as an argument instead. This also means it is not as quickly portable to other systems.

You can use the same location you gave VS Code earlier for the terminal itself, C:\\WINDOWS\\Sysnative\\bash.exe as the value for command

Set the first element of the args array as -c and the second as the command you want to run (credit to the second half of this answer).

Alternatively, you can instead run a shell script as seen here.

Further helpful bits

Want to start VSCode in Windows from the WSL Bash command line?

Want to have a graphical interface for your WSL Ubuntu? (this will allow you to do things like use a Linux GUI editor for files within the Ubuntu system itself: do not edit them using Windows editing tools, see comments/note in section on npm)

Want to build (see the above portion on setting up VS Code Tasks properly for WSL) and debug entirely within WSL Ubuntu? (this shows how to do so using gdb, but the pipeTransport concept could be used with other debuggers) (credit to this answer, but the one before it also provides a method using local loopback that could prove useful)

Body:
This answer seeks to help others avoid spending 1-2 hours troubleshooting and slowly finding disparate solutions for common problems when using WSL for the terminal in VS Code. It does not cover installing specific packages, but rather common ones that may not properly install as dependencies when installing things that do rely on their presence, and on fixing related common settings.

Summary of steps

WSL installed

VS Code (or other IDE) configured for terminal

NPM installed & path fix in .profile (may help with other tools)

build-essential installed (helps with any tools that use make/gcc/etc)

VS Code Tasks using WSL

Extras

Getting Started & Requirements

You must have WSL installed. (Which means you must be running 64 bit Windows 10, with the appropriate updates) Follow the install guide if not already installed. This will require some reboots.

VS Code Terminal Configuration

Either the CTRL+, keyboard shortcut, or File → Preferences → Settings

In the top right of the editing window, make sure you are working in the correct context for you: either User Settings or Workspace Settings.

In the settings search bar, type terminal.integrated.shell.windows (or whatever gets you far enough long)

Find the setting in the actual settings file, use Edit (mouse over the line, it will be on the left: on a touch screen without a mouse, you should be able to simply tap to the left of the line), and select Replace in Settings

In the right pane, modify the entry created in the modified json file: replace the previous setting with

"C:\\WINDOWS\\Sysnative\\bash.exe"

Other IDEs: IntelliJ

Open Settings/Tools/Terminal and set the "Shell path" field to "C:\Users\USERNAME\AppData\Local\Microsoft\WindowsApps\ubuntu.exe"

Making your WSL Ubuntu Bash Terminal functional for dev

When you use CTRL+` to open the terminal, you should now have a bash terminal.

If this is the first time you have run bash.exe, you may be asked about installing Ubuntu. Do so. Once your installation is complete, choose your username and password to be used in WSL Ubuntu. These do not have to coincide with your current Windows account, and it's important to note that they will not change based on changes to your Windows account's password.

Once you are done, you will have a bash command prompt in your terminal.

Note that unlike git-bash on Windows, this is a separate environment. While it can be used to launch Windows software outside of itself, you will need appropriate Ubuntu packages to run them within the actual terminal.

Currently, WSL does not come loaded with everything you might expect or be used to having, and some things can conflict with software you have loaded in Windows, based on default profile settings.

Updates & git

Note: I'm going to document these as sudo for people who simply need single pieces of this, but one option at the start is to instead sudo su and simply running the following commands without sudo.

Make sure your Ubuntu packages are up to date:

sudo apt-get -y update
sudo apt-get -y upgrade
sudo apt-get -y dist-upgrade
sudo apt autoremove

Install git:

sudo apt-get install git

Node.js & NPM

If you already have Node or NPM loaded in Windows, running them in Ubuntu can get problematic due to path issues. So, you need to install the Ubuntu native versions and ensure that they are used instead.

First, install node.js with NPM.
(alternate: install NVM and use it to install node.js)

After installing, running npm commands will probably fail: for example, npm -v will probably give you:

: not foundram Files/nodejs/npm: 3: /mnt/c/Program Files/nodejs/npm:
: not foundram Files/nodejs/npm: 5: /mnt/c/Program Files/nodejs/npm:
/mnt/c/Program Files/nodejs/npm: 6: /mnt/c/Program Files/nodejs/npm: Syntax error: word unexpected (expecting "in")

This is due to a pathing issue with a fairly straightforward solution. Using your favorite CLI editor (such as nano, vim, emacs, cat and sed… etc), open your ~/.profile

nano ~/.profile

Note: do NOT attempt to edit Linux files using Windows tools. (Thanks to @david-c-rankin's comment for the official link with the bold red text explaining this) If you don't want to use a CLI editor for this in the terminal, see the bottom of this post for a link on how to get a GUI one running.

Currently, the default bash PATH variable in WSL is

PATH="$HOME/bin:$HOME/.local/bin:$PATH"

Which is injecting the windows path after the first two binary directories. Unfortunately, this doesn't result in /usr/bin being used before the windows installed npm, so add that before the final $PATH:

PATH="$HOME/bin:$HOME/.local/bin:/usr/bin:$PATH"

Save out, and then either reload the terminal or just source the path file

source ~/.profile

Build-essential

If you are using anything which requires compiling or otherwise uses make, it's almost guaranteed that you will need these installed; so if you did not install them while installing node.js, do so. It's much easier to simply use the build-essential package rather than try to install everything separately.

Note that packages such as Compass which rely on Ruby FFI will fail without these. If you are having trouble properly installing and running a tool, making sure you have gcc and make installed can be a good place to start.

sudo apt-get install -y build-essential

Running Tasks using Ubuntu

Note that if you use VS Code's tasks.json to run build tasks, by default it will still run them using the Windows subsystem instead of the Ubuntu one. Sometimes this may be what you want, but if you've just finished installing grunt-cli in Ubuntu and not Windows, it's probably not.

VS Code recently had the 2017 May update to how Tasks work that allows it to set the task runner as the terminal. This is by far the easiest way to migrate tasks over.

Simply set

"runner": "terminal",

in your tasks.json and you're done (assuming you have all of the appropriate tools you are trying to run now installed in WSL Ubuntu).

This is very portable, ideally requiring no changes between systems which do or do not have WSL, or to other OSes, and is the method I would recommend.

As of the moment, this method spawns another TERMINAL tab instance (accessed from the drop down). You can still set up appropriate watchers, but it does mean that it's no longer sitting on the OUTPUT tab.

The old method is capable of invoking the WSL Ubunutu Bash shell and having it show up in OUTPUT, and involves either calling bash.exe with the -c argument or using a shell script. It unfortunately is not as semantic, since we are making bash our command and passing it what we want to run as an argument instead. This also means it is not as quickly portable to other systems.

You can use the same location you gave VS Code earlier for the terminal itself, C:\\WINDOWS\\Sysnative\\bash.exe as the value for command

Set the first element of the args array as -c and the second as the command you want to run (credit to the second half of this answer).

Alternatively, you can instead run a shell script as seen here.

Further helpful bits

Want to start VSCode in Windows from the WSL Bash command line?

Want to have a graphical interface for your WSL Ubuntu? (this will allow you to do things like use a Linux GUI editor for files within the Ubuntu system itself: do not edit them using Windows editing tools, see comments/note in section on npm)

Want to build (see the above portion on setting up VS Code Tasks properly for WSL) and debug entirely within WSL Ubuntu? (this shows how to do so using gdb, but the pipeTransport concept could be used with other debuggers) (credit to this answer, but the one before it also provides a method using local loopback that could prove useful)


来源: stackexchange

问:
Is there a Mercurial extension like svn propset?
I need to attach custom metadata to my source files that at tracked via Mercurial.  The svn properties commands are exactly what I need.

Is there a mercurial extension that provides commands similar to propset, propget, propdel, etc?

If there isn't an extension, why not?

Is there an alternative/better approach for custom metadata when using Mercurial?

Is custom metadata not useful to anyone else?

Is the extension dearly desired but just not written yet?

extra info: If it helps.  The metadata I'm tracking is whether each file has been codereviewed, unittested, qa'd, etc.  This data needs to be traceable and merges between branches/clones aren't fine grained enough.

答:
The Mercurial convention is to put files name .hg* into the root of the repository, and use them as dictionaries (of some kind) to map file names to property values. For example, instead of svn:eol-style the hgeol extension uses a .hgeol file.

In case of tracking code review, I'd recommend to write another extension that allows manipulation of this metadata, and have that extension store its state in a merge-friendly format.

ContentLicense: CC BY-SA 2.5


问:
Optional Default Parameter in Swift
I have a function with default parameters in swift.

```<code>func test(string: String = "", middleString: String = "", endString: String = "") -> Void {
  // do stuff
}
</code>```

I want to pass in variables that will be optional strings.

```<code>let string: String?
let middleString: String?
let endString: String?
</code>```

How do I make it so that if the parameters are nil, use the default parameters.
If not, then use the values within the optionals.

test(string, middleString: middleString, endString: endString)

答:
Note: Don't interpret this optional parameters as ?, this is different approach.

Totally optional parameters, i.e Don't even use while calling method.

```<code>func doAddition(value1Name value1:Int = 0, value2Name value2:Int = 0, value3Name value3:Int = 0){
    print(value1+value2+value3)
}
</code>```

Now all parameters are optional to add. call how you like,

```<code>doAddition(value1Name: 1)
doAddition(value1Name: 1, value2Name: 2)
doAddition(value3Name: 3)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Optional Default Parameter in Swift

Body:
I have a function with default parameters in swift.

func test(string: String = "", middleString: String = "", endString: String = "") -> Void {
  // do stuff
}

I want to pass in variables that will be optional strings.

let string: String?
let middleString: String?
let endString: String?

How do I make it so that if the parameters are nil, use the default parameters.
If not, then use the values within the optionals.

test(string, middleString: middleString, endString: endString)

Body:
Note: Don't interpret this optional parameters as ?, this is different approach.

Totally optional parameters, i.e Don't even use while calling method.

func doAddition(value1Name value1:Int = 0, value2Name value2:Int = 0, value3Name value3:Int = 0){
    print(value1+value2+value3)
}

Now all parameters are optional to add. call how you like,

doAddition(value1Name: 1)
doAddition(value1Name: 1, value2Name: 2)
doAddition(value3Name: 3)

ContentLicense: CC BY-SA 3.0


问:
Issue with Merging in Pandas
I am having issues in merging 2 pandas dataframes.

```<code>a = [{'City':'CCC','ID':'BBB'},{'City':'AAA','ID':'DDD'},{'City':'CCC','ID':'HHH'}]
b = [{'City':'AAA','Name':'FFF'},{'City':'CCC','Name':'GGG'}]
df1 = pd.DataFrame(a)
df2 = pd.DataFrame(b)
df3 = pd.merge(df1,df2,how='left',on='City')
</code>```

df1:

```<code>   City ID
0   CCC BBB
1   AAA DDD
2   CCC HHH
</code>```

df2:

```<code>    City Name
0   AAA  FFF
1   CCC  GGG
</code>```

df3:

```<code>    City ID     Name
0   CCC  BBB    GGG
1   AAA  DDD    FFF
2   CCC  HHH    GGG
</code>```

In the above mock code, df3['Name'] has no NaN values. But, in my real dataframes (which I can't share here), the equivalent of df3['Name'] has NaN values although it shouldn't because all elements in df1['City'] and df2['City'] match in my real dataframes (not these mock dataframes). So, I try to troubleshoot and find the followings.

If I try the following code,

```<code>'AAA' in df1['City']
</code>```

I get False although it should be True since 'AAA' is in that column.

But, if I try the following code,

```<code>'AAA' in sorted(df1['City'])
</code>```

I get True, which is what I expect.

Also, to confirm, I try this:

```<code>len([x for x in df1['City'] if x not in df2['City']])
</code>```

And got output of 3, which should be 0.

So, I wonder what's the causes of the above issues and any guess on why the merging of the real dataframe is not working? The elements of the column used for merging are string.

答:
You didn't get any NaN in this example because every element of the 'City' column in df1 was in the 'City' column of df2.

Try this example instead

```<code>a = [
    {'City':'CCC','ID':'BBB'},
    {'City':'AAA','ID':'DDD'},
    {'City':'CCC','ID':'HHH'},
    {'City':'DDD','ID':'XXX'}
]

b = [
    {'City':'AAA','Name':'FFF'},
    {'City':'CCC','Name':'GGG'}
]

df1 = pd.DataFrame(a)
df2 = pd.DataFrame(b)
df3 = pd.merge(df1,df2,how='left',on='City')
df3

  City   ID Name
0  CCC  BBB  GGG
1  AAA  DDD  FFF
2  CCC  HHH  GGG
3  DDD  XXX  NaN
</code>```

You can check if 'AAA' is in df3.City

```<code>(df3.City == 'AAA').any()

True
</code>```

Or

```<code>'AAA' in df3.City.tolist()

True
</code>```

Title: Issue with Merging in Pandas

Body:
I am having issues in merging 2 pandas dataframes.

a = [{'City':'CCC','ID':'BBB'},{'City':'AAA','ID':'DDD'},{'City':'CCC','ID':'HHH'}]
b = [{'City':'AAA','Name':'FFF'},{'City':'CCC','Name':'GGG'}]
df1 = pd.DataFrame(a)
df2 = pd.DataFrame(b)
df3 = pd.merge(df1,df2,how='left',on='City')

df1:

   City ID
0   CCC BBB
1   AAA DDD
2   CCC HHH

df2:

    City Name
0   AAA  FFF
1   CCC  GGG

df3:

    City ID     Name
0   CCC  BBB    GGG
1   AAA  DDD    FFF
2   CCC  HHH    GGG

In the above mock code, df3['Name'] has no NaN values. But, in my real dataframes (which I can't share here), the equivalent of df3['Name'] has NaN values although it shouldn't because all elements in df1['City'] and df2['City'] match in my real dataframes (not these mock dataframes). So, I try to troubleshoot and find the followings.

If I try the following code,

'AAA' in df1['City']

I get False although it should be True since 'AAA' is in that column.

But, if I try the following code,

'AAA' in sorted(df1['City'])

I get True, which is what I expect.

Also, to confirm, I try this:

len([x for x in df1['City'] if x not in df2['City']])

And got output of 3, which should be 0.

So, I wonder what's the causes of the above issues and any guess on why the merging of the real dataframe is not working? The elements of the column used for merging are string.

Body:
You didn't get any NaN in this example because every element of the 'City' column in df1 was in the 'City' column of df2.

Try this example instead

a = [
    {'City':'CCC','ID':'BBB'},
    {'City':'AAA','ID':'DDD'},
    {'City':'CCC','ID':'HHH'},
    {'City':'DDD','ID':'XXX'}
]

b = [
    {'City':'AAA','Name':'FFF'},
    {'City':'CCC','Name':'GGG'}
]

df1 = pd.DataFrame(a)
df2 = pd.DataFrame(b)
df3 = pd.merge(df1,df2,how='left',on='City')
df3

  City   ID Name
0  CCC  BBB  GGG
1  AAA  DDD  FFF
2  CCC  HHH  GGG
3  DDD  XXX  NaN

You can check if 'AAA' is in df3.City

(df3.City == 'AAA').any()

True

Or

'AAA' in df3.City.tolist()

True


答:
First you badly check AAA - need isin for check multiple values or compare with Series and if need scalar output add any for check at least one True.

See also using the in operator.

```<code>#this check in index, not in values
print ('AAA' in df1['City'])
False

print (0 in df1['City'])
True
</code>```

```<code>#this check in list from column
print (sorted(df1['City']))
['AAA', 'CCC', 'CCC', 'DDD']

print ('AAA' in sorted(df1['City']))
True

#pandas function for checking multiple values is isin
print (df1['City'].isin(['AAA', 'EEE']))
0    False
1     True
2    False
Name: City, dtype: bool

print (df1['City'].isin(['AAA', 'EEE']).any())
True
</code>```

```<code>print (df3['City'] == 'AAA')
0    False
1     True
2    False
Name: City, dtype: bool

print ((df3['City'] == 'AAA').any())
True
</code>```

And you get NaNs in column City in output, because no match - it show another answer.

You can get difference values by :

```<code>#borrowed sample from piRSquared's answer
a = [
    {'City':'CCC','ID':'BBB'},
    {'City':'AAA','ID':'DDD'},
    {'City':'CCC','ID':'HHH'},
    {'City':'DDD','ID':'XXX'}
]

b = [
    {'City':'AAA','Name':'FFF'},
    {'City':'CCC','Name':'GGG'}
]

df1 = pd.DataFrame(a)
df2 = pd.DataFrame(b)

print (np.setdiff1d(df1['City'], df2['City']))
['DDD']
</code>```

Or isin for check multiple values, ~ is for invert boolean mask.

Then is possible use boolean indexing.

```<code>print (~df1['City'].isin(df2['City']))
0    False
1    False
2    False
3     True
Name: City, dtype: bool

print (df1[~df1['City'].isin(df2['City'])])
  City   ID
3  DDD  XXX

print (df1.loc[~df1['City'].isin(df2['City']), 'City'])
3    DDD
Name: City, dtype: object
</code>```

Title: Issue with Merging in Pandas

Body:
First you badly check AAA - need isin for check multiple values or compare with Series and if need scalar output add any for check at least one True.

See also using the in operator.

#this check in index, not in values
print ('AAA' in df1['City'])
False

print (0 in df1['City'])
True

#this check in list from column
print (sorted(df1['City']))
['AAA', 'CCC', 'CCC', 'DDD']

print ('AAA' in sorted(df1['City']))
True

#pandas function for checking multiple values is isin
print (df1['City'].isin(['AAA', 'EEE']))
0    False
1     True
2    False
Name: City, dtype: bool

print (df1['City'].isin(['AAA', 'EEE']).any())
True

print (df3['City'] == 'AAA')
0    False
1     True
2    False
Name: City, dtype: bool

print ((df3['City'] == 'AAA').any())
True

And you get NaNs in column City in output, because no match - it show another answer.

You can get difference values by :

#borrowed sample from piRSquared's answer
a = [
    {'City':'CCC','ID':'BBB'},
    {'City':'AAA','ID':'DDD'},
    {'City':'CCC','ID':'HHH'},
    {'City':'DDD','ID':'XXX'}
]

b = [
    {'City':'AAA','Name':'FFF'},
    {'City':'CCC','Name':'GGG'}
]

df1 = pd.DataFrame(a)
df2 = pd.DataFrame(b)

print (np.setdiff1d(df1['City'], df2['City']))
['DDD']

Or isin for check multiple values, ~ is for invert boolean mask.

Then is possible use boolean indexing.

print (~df1['City'].isin(df2['City']))
0    False
1    False
2    False
3     True
Name: City, dtype: bool

print (df1[~df1['City'].isin(df2['City'])])
  City   ID
3  DDD  XXX

print (df1.loc[~df1['City'].isin(df2['City']), 'City'])
3    DDD
Name: City, dtype: object


问:
How to parse xs:date with NodaTime?
I have to process XML documents sent by various external systems that also contain some dates. xs:date allows adding a "time zone", i.e. an offset, to a date. E.g. "2017-06-02+03:00" is a valid value. Also, offsets are not used consistently in a single XML document. Some dates have an offset, most do not.

LocalDatePattern.IsoPattern does not handle values with an offset and my attempts at a custom pattern were also fruitless.

What would be the best way to parse these values into a LocalDate?

I debated to 2 possible options:

Simply strip the offset part from the textual value and continue using LocalDatePattern.IsoPattern.

Use OffsetDateTimePattern with a custom pattern that does not contain the time part and then construct the LocalDate manually from the parsed value.

I ended up going with option 1, because I do not need the offset for any conversions.

答:
I would parse the value as OffsetDateTimePattern as that most closely represents the information you actually have in the text. My experience is that it's best to parse in a form that retains all the information you need, then use the Noda Time APIs to change to a format that you actually want... rather than do the transformation on the string and then parse.

Benefits of that:

It validates all the text, not just the text you're interested in. The value "2017-06-09-badger-badger" clearly suggests there's something very wrong, but if you're using a substring approach you'd miss that.

It's more robust - you're less likely to end up with magic numbers in your code, and it's much easier to handle things like variable-width formats (not a problem in this specific case, of course)

It makes it easier to change your mind about what you want, because the decision remains entirely in the "date and time" domain, not the "text parsing" domain.

The only exception I normally make to this is if the string is unparseable at the moment - e.g. it includes some unsupported aspect like ordinals ("June 3rd 2017").

We could consider adding this as a text format for LocalDate - I don't anticipate creating an OffsetDate type, unless there's significant demand.

Title: How to parse xs:date with NodaTime?


问:
Finding new line character in a String in "Swift 3"
In my app I am receiving some incoming data from a web service. In that data some wrong values can also be received like new line characters. I want to find in response string that if it contains a new line character or not.

Before Swift 3 I was able to do it like this

```<code>string.rangeOfString("\n")) == nil)
</code>```

But in Swift 3 this methods is no longer available. However substring method is available which does with the help of Range.

I want to detect if my string contains "\n" how this would be accomplished using this method in Swift 3.

答:
Swift 3

```<code>string.range(of: "\n")
</code>```

To check:

```<code>if string.range(of: "\n") == nil{

}
</code>```

Or if you simply want to check the string contains \n or not, Then,

```<code>if !str.characters.contains("\n") {

}
</code>```

Body:
In my app I am receiving some incoming data from a web service. In that data some wrong values can also be received like new line characters. I want to find in response string that if it contains a new line character or not.

Before Swift 3 I was able to do it like this

string.rangeOfString("\n")) == nil)

But in Swift 3 this methods is no longer available. However substring method is available which does with the help of Range.

I want to detect if my string contains "\n" how this would be accomplished using this method in Swift 3.

Body:
Swift 3

string.range(of: "\n")

To check:

if string.range(of: "\n") == nil{

}

Or if you simply want to check the string contains \n or not, Then,

if !str.characters.contains("\n") {

}


问:
Merge and align center cell using apache poi
I want to export data to excel using Apache poi.
 Now the problem that I am facing is that I am unable to merge rows and align them in the center.

Code for export data is:

```<code>List<LinkedHashMap<String,Object>> lstReportHeader = null;
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();

//Set Header Font
HSSFFont headerFont = wb.createFont();
headerFont.setBoldweight(headerFont.BOLDWEIGHT_BOLD);
headerFont.setFontHeightInPoints((short) 12);

//Set Header Style
CellStyle headerStyle = wb.createCellStyle();
headerStyle.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
headerStyle.setAlignment(headerStyle.ALIGN_CENTER);
headerStyle.setFont(headerFont);
headerStyle.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
int rowCount= 0;
Row header;
header = sheet.createRow(0);//its for header
Cell cell ;//= header.createCell(0);
for(int j = 0;j < 4; j++) {
    cell = header.createCell(j);
    if(j == 0) {
        cell.setCellValue("ItemWise List");
    }
    cell.setCellStyle(headerStyle);
}
sheet.addMergedRegion(new CellRangeAddress(rowCount, rowCount, 0, lstReportFormHeader.size()-1));
header = sheet.createRow(0);
        cell = header.createCell(0);
cell.setCellValue("Sr. No");
        cell = header.createCell(1);
cell.setCellValue("Item Name");
        cell = header.createCell(2);
cell.setCellValue("Qty");
        cell = header.createCell(3);
cell.setCellValue("Rate");
</code>```

Now I want to ItemWise List merge and make it align center.

答:
Use </p>

```<code>style.setVerticalAlignment()
</code>```

<p>to set the vertical alignments instead of </p>

```<code>style.setAlignment().
</code>```

Body:
I want to export data to excel using Apache poi.
 Now the problem that I am facing is that I am unable to merge rows and align them in the center.

Code for export data is:

List<LinkedHashMap<String,Object>> lstReportHeader = null;
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();

//Set Header Font
HSSFFont headerFont = wb.createFont();
headerFont.setBoldweight(headerFont.BOLDWEIGHT_BOLD);
headerFont.setFontHeightInPoints((short) 12);

//Set Header Style
CellStyle headerStyle = wb.createCellStyle();
headerStyle.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
headerStyle.setAlignment(headerStyle.ALIGN_CENTER);
headerStyle.setFont(headerFont);
headerStyle.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
int rowCount= 0;
Row header;
header = sheet.createRow(0);//its for header
Cell cell ;//= header.createCell(0);
for(int j = 0;j < 4; j++) {
    cell = header.createCell(j);
    if(j == 0) {
        cell.setCellValue("ItemWise List");
    }
    cell.setCellStyle(headerStyle);
}
sheet.addMergedRegion(new CellRangeAddress(rowCount, rowCount, 0, lstReportFormHeader.size()-1));
header = sheet.createRow(0);
        cell = header.createCell(0);
cell.setCellValue("Sr. No");
        cell = header.createCell(1);
cell.setCellValue("Item Name");
        cell = header.createCell(2);
cell.setCellValue("Qty");
        cell = header.createCell(3);
cell.setCellValue("Rate");

Now I want to ItemWise List merge and make it align center.

Body:
Use

style.setVerticalAlignment()

to set the vertical alignments instead of

style.setAlignment().


问:
postgresql postgis If point inside circle
I'm using postgresql as db , i have the table named car_wash  with field "point geometry"(use postgis) so in application I'm getting lon lat from user using GOOGLE API, next step I need to create circle around user and check if car_wash inside this circle I use

```<code>  select *
 from car_wash cw
where
ST_DWithin (
   cw.lon_lat,
   ST_GeomFromText('POINT(54.21 22.54)')
)=false
AND
not cw.was_deleted
</code>```

Is it corect way? IF you need my srid is 0 according to this query

```<code> Select Find_SRID('public',  'car_wash',  'lon_lat')
</code>```

答:
SRID of the ST_GeomFromText('POINT(54.21 22.54)') must be same as the SRID of cw.lon_lat. Suppose SRID of cw.lon_lat is 4326 you can set the other attribute srib by using  ST_GeomFromText('POINT(54.21 22.54)',4326).
Secondly, ST_DWithin needs buffer distance as 3rd parameter. So suppose if you want to check if point is within 100 meter buffer it should be like

```<code>ST_DWithin (
   cw.lon_lat,
   ST_GeomFromText('POINT(54.21 22.54)', 3857), 100
)
</code>```

Buffer value is according to the srid unit. in case of 3857 its meter. You need to convert cw.lon_lat and POINT(54.21 22.54) to the same SRID in order to make this work, using st_setSRID e.g.

Body:
I'm using postgresql as db , i have the table named car_wash  with field "point geometry"(use postgis) so in application I'm getting lon lat from user using GOOGLE API, next step I need to create circle around user and check if car_wash inside this circle I use

  select *
 from car_wash cw
where
ST_DWithin (
   cw.lon_lat,
   ST_GeomFromText('POINT(54.21 22.54)')
)=false
AND
not cw.was_deleted

Is it corect way? IF you need my srid is 0 according to this query

 Select Find_SRID('public',  'car_wash',  'lon_lat')

Body:
SRID of the ST_GeomFromText('POINT(54.21 22.54)') must be same as the SRID of cw.lon_lat. Suppose SRID of cw.lon_lat is 4326 you can set the other attribute srib by using  ST_GeomFromText('POINT(54.21 22.54)',4326).
Secondly, ST_DWithin needs buffer distance as 3rd parameter. So suppose if you want to check if point is within 100 meter buffer it should be like

ST_DWithin (
   cw.lon_lat,
   ST_GeomFromText('POINT(54.21 22.54)', 3857), 100
)

Buffer value is according to the srid unit. in case of 3857 its meter. You need to convert cw.lon_lat and POINT(54.21 22.54) to the same SRID in order to make this work, using st_setSRID e.g.


问:
Is there any way to adjust the sequence of LegendEntries (Series) in Excel chart by VBA?
I'm working on an Excel chart automation. When I try to move up a LegendEntry(Series) object, I cannot find any related API method from MS site. The manual way is like this: Select the chart > Right click > Select Data... > Choose one of the LegendEntry > Click button Move Up. How could I do this by VBA? Thank you in advance.

答:
The legend entry order is the same as the series order. I'm not sure if this is even exposed in the object model. You can change the number of the last parameter of the series formula to re-order the series and the legend entries alike.

```<code>ActiveSheet.ChartObjects("Chart 1").Activate
Debug.Print ActiveChart.FullSeriesCollection(1).Formula
</code>```

This will get you something like

```<code>=SERIES(Sheet1!$B$6,,Sheet1!$C$6,1)
</code>```

The 1 as the last parameter means that it is the first series in the chart and hence the legend. Change that parameter to move the legend entry to a different position.

Body:
The legend entry order is the same as the series order. I'm not sure if this is even exposed in the object model. You can change the number of the last parameter of the series formula to re-order the series and the legend entries alike.

ActiveSheet.ChartObjects("Chart 1").Activate
Debug.Print ActiveChart.FullSeriesCollection(1).Formula

This will get you something like

=SERIES(Sheet1!$B$6,,Sheet1!$C$6,1)

The 1 as the last parameter means that it is the first series in the chart and hence the legend. Change that parameter to move the legend entry to a different position.


问:
Running Bottle + Python + Google App engine for the first time
As the first step in creating a cloud based mobile app I chose to try out the Google Cloud trial period. So as per the instructions in https://console.developers.google.com/start/appengine?_ga=1.92011098.1535487967.1418404546, I installed the Google cloud SDK and Google App engine and tried out the following code snippet as mentioned in the instructions.

```<code>from bottle import Bottle

bottle = Bottle()

# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.

@bottle.route('/')
def hello():
    """Return a friendly HTTP greeting."""
    return 'Hello World!'

# Define an handler for 404 errors.
@bottle.error(404)
def error_404(error):
    """Return a custom 404 error."""
    return 'Sorry, nothing at this URL.'
</code>```

As per instructions, I

Sign in to Google Cloud Platform using this command: gcloud auth login

Install the App Engine package for Python using this command: gcloud components update gae-python

Start a local server using this command: dev_appserver.py appengine-try-python-bottle

However, it generated the following logs (which I am not allowed to share here apparently because I haven't earned some points here) and localhost:8080 was blank. Can you please help me understand what am I missing here ?

答:
Look here for an answer: https://github.com/GoogleCloudPlatform/appengine-bottle-skeleton

Those instructions worked perfectly for me.

Body:
As the first step in creating a cloud based mobile app I chose to try out the Google Cloud trial period. So as per the instructions in https://console.developers.google.com/start/appengine?_ga=1.92011098.1535487967.1418404546, I installed the Google cloud SDK and Google App engine and tried out the following code snippet as mentioned in the instructions.

from bottle import Bottle

bottle = Bottle()

# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.

@bottle.route('/')
def hello():
    """Return a friendly HTTP greeting."""
    return 'Hello World!'

# Define an handler for 404 errors.
@bottle.error(404)
def error_404(error):
    """Return a custom 404 error."""
    return 'Sorry, nothing at this URL.'

As per instructions, I

Sign in to Google Cloud Platform using this command: gcloud auth login

Install the App Engine package for Python using this command: gcloud components update gae-python

Start a local server using this command: dev_appserver.py appengine-try-python-bottle

However, it generated the following logs (which I am not allowed to share here apparently because I haven't earned some points here) and localhost:8080 was blank. Can you please help me understand what am I missing here ?


问:
How do I get the real reason why promise is rejected
I have this code

```<code>var loadFilePromise = new Promise(function(loadFilePromiseResolve, loadFilePromiseReject) {

    $.ajax({
        type: 'post',
        url: "http://localhost:12343/MyTestPage.aspx",
        data: {
            DocumentFileID: documentFileId
        },
        dataType: 'json'
    }).then(function(resp) {
        // Do something here
        loadFilePromiseResolve();
    }, function(xhr) {
        // This is reject response from ajax. And it hits here.
        var msg = "Error occurred: " + xhr.statusText + " (" + xhr.status + ")\n" + Util.parseAspxExceptionMessage(xhr.responseText);
        loadFilePromiseReject(msg);
    });

});
</code>```

I would like to know as to know why the promise has been rejected. I looked inside the xhr object and there is none. The weird thing about this is that the status is 200 and the statusText = OK.

Need help on this because I don't have much knowledge yet in ES6.

答:
See the jQuery documentation on ajax:

```<code>jqXHR.then(
    function( data, textStatus, jqXHR ) {},
    function( jqXHR, textStatus, errorThrown ) {}
);
</code>```

Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

The signature of the error callback is function(jqXHR, textStatus, errorThrown) so you can get more information about the exact problem using textStatus and errorThrown.

Body:
I have this code

var loadFilePromise = new Promise(function(loadFilePromiseResolve, loadFilePromiseReject) {

    $.ajax({
        type: 'post',
        url: "http://localhost:12343/MyTestPage.aspx",
        data: {
            DocumentFileID: documentFileId
        },
        dataType: 'json'
    }).then(function(resp) {
        // Do something here
        loadFilePromiseResolve();
    }, function(xhr) {
        // This is reject response from ajax. And it hits here.
        var msg = "Error occurred: " + xhr.statusText + " (" + xhr.status + ")\n" + Util.parseAspxExceptionMessage(xhr.responseText);
        loadFilePromiseReject(msg);
    });

});

I would like to know as to know why the promise has been rejected. I looked inside the xhr object and there is none. The weird thing about this is that the status is 200 and the statusText = OK.

Need help on this because I don't have much knowledge yet in ES6.

Body:
See the jQuery documentation on ajax:

jqXHR.then(
    function( data, textStatus, jqXHR ) {},
    function( jqXHR, textStatus, errorThrown ) {}
);

Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

The signature of the error callback is function(jqXHR, textStatus, errorThrown) so you can get more information about the exact problem using textStatus and errorThrown.


问:
Java List MVC Pattern
I'm having some trouble implementing a JList in Java using the MVC Pattern because I can't figure out how am I suppose to write the controller and the view(each one in a separte class) so that I can call the methods from the model.Example : In the model I have a method called ( getBooks() ) and in the GUI a frame with a JList so that when I click an item in the list some textboxes will get filled with the appropriate information(title, author etc). The problem is I'm not sure how to write the listeners in the controller and/or in the view.By the way the items from the list should also be loaded from the model.

Thank you.

答:
The listener you want to register with your JList is a ListSelectionListener, which will alert you when the selection changes.  If I were doing this I would do something similar to the following:

```<code>public class BookListModel {
    public List<Book> getBooks() {
        // Replace with however you get your books
        return Arrays.asList(new Book("It", "Stephen King"),
            new Book("The Lion, The Witch, and the Wardrobe", "C.S. Lewis"));
    }
}

public class Book {
    private String title;
    private String author;

    public String getTitle() { return title; }
    public String getAuthor() { return author; }

    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }
}

public class BookListView extends JPanel {

    private JList books;
    private BookInfoView bookInfo;
    private BookListModel model;
    public BookListView(BookListModel model) {
        books = new JList(model.toArray());

        bookInfo = new BookInfoView();

        books.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                // get the book that was clicked
                // call setBook on the BookInfoView
            }
        });

        // Add the JList and the info view
    }

}

public class BookInfoView extends JPanel {

    private JLabel titleLabel;
    private JLabel authorLabel;

    private JTextField titleTextField;
    private JTextField authorTextField;

    public void setBook(Book b) {
        // adjust the text fields appropriately
    }

}
</code>```

The above assumes that the list of books is static.  If that's not the case, you should make your BookListModel extend DefaultListModel and fill in the appropriate methods.

Title: Java List MVC Pattern

Body:
The listener you want to register with your JList is a ListSelectionListener, which will alert you when the selection changes.  If I were doing this I would do something similar to the following:

public class BookListModel {
    public List<Book> getBooks() {
        // Replace with however you get your books
        return Arrays.asList(new Book("It", "Stephen King"),
            new Book("The Lion, The Witch, and the Wardrobe", "C.S. Lewis"));
    }
}

public class Book {
    private String title;
    private String author;

    public String getTitle() { return title; }
    public String getAuthor() { return author; }

    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }
}

public class BookListView extends JPanel {

    private JList books;
    private BookInfoView bookInfo;
    private BookListModel model;
    public BookListView(BookListModel model) {
        books = new JList(model.toArray());

        bookInfo = new BookInfoView();

        books.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                // get the book that was clicked
                // call setBook on the BookInfoView
            }
        });

        // Add the JList and the info view
    }

}

public class BookInfoView extends JPanel {

    private JLabel titleLabel;
    private JLabel authorLabel;

    private JTextField titleTextField;
    private JTextField authorTextField;

    public void setBook(Book b) {
        // adjust the text fields appropriately
    }

}

The above assumes that the list of books is static.  If that's not the case, you should make your BookListModel extend DefaultListModel and fill in the appropriate methods.


答:
Here is another way

```<code>Sub Sample()
    Dim ws As Worksheet
    Dim objChrt As ChartObject
    Dim chrt As Chart

    Set ws = ActiveSheet
    Set objchart = ws.ChartObjects(1)
    Set chrt = objchart.Chart

    chrt.FullSeriesCollection(2).PlotOrder = 1
End Sub
</code>```

Screenshot

Title: Is there any way to adjust the sequence of LegendEntries (Series) in Excel chart by VBA?

Body: I'm working on an Excel chart automation. When I try to move up a LegendEntry(Series) object, I cannot find any related API method from MS site. The manual way is like this: Select the chart > Right click > Select Data... > Choose one of the LegendEntry > Click button Move Up. How could I do this by VBA? Thank you in advance.

Body:
Here is another way

Sub Sample()
    Dim ws As Worksheet
    Dim objChrt As ChartObject
    Dim chrt As Chart

    Set ws = ActiveSheet
    Set objchart = ws.ChartObjects(1)
    Set chrt = objchart.Chart

    chrt.FullSeriesCollection(2).PlotOrder = 1
End Sub

Screenshot


问:
Create Azure Storage Account using C# Throw exception "The request was aborted: Could not create SSL/TLS secure channel."
I have a method in my asp.net mvc 5 application that uses Microsoft Azure client classes (CloudContext.Clients) to create StorageManagementClient. Needs certificate to authenticate, so I created a selfsigned certificate.

On development machine everything works ok.

On azure virtual machine(windows server 2008 r2) I have imported the certificate which is found by the code as expected, but when code that creates StorageManagementClient executes an exception is thrown

Inner Exception Type: System.Net.WebException
  Inner Exception: The request was aborted: Could not create SSL/TLS secure channel.
  Inner Source: System
  Inner Stack Trace:
     at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
     at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
  Exception Type: System.Net.Http.HttpRequestException
  Exception: An error occurred while sending the request.
  Source: test
  Stack Trace:
     at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task)
     at Microsoft.WindowsAzure.StorageAccountOperationsExtensions.Create(IStorageAccountOperations operations, StorageAccountCreateParameters parameters)
     at ApplicationPortal.Code.DeployAzureResources.CreateStorageAccount(SubscriptionCloudCredentials credentials, String storageName) in C:\Users\DEVSYS1\Documents\Visual Studio 2017\Projects\PaSeaPortal\ApplicationPortal\Code\DeployAzureResources.cs:line 106
     at ApplicationPortal.Controllers.AccountController.d__21.MoveNext() in C:\Users\DEVSYS1\Documents\Visual Studio 2017\Projects\PaSeaPortal\ApplicationPortal\Controllers\AccountController.cs:line 355

And on Event Viewer I am seeing this Error "The following fatal alert was generated: 80. The internal error state is 301."

答:
I have imported the certificate which is found by the code as expected

Do you mean that you have installed the selfsigned  .cer certification on the Azure virtual machine?
If it is not that case, please have a try to export the cert from your develop machine and install it on the azure virtual  machine. And try to use following code test it again.

```<code>public static X509Certificate2 GetCert(string thumbprint)
        {

            X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            certStore.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
            if (certCollection.Count <= 0) return null;
            X509Certificate2 cert = certCollection[0];
            return cert;
        }

 var thumbprint= "cert thumbprint";
 SubscriptionCloudCredentials credentials = new CertificateCloudCredentials("subscription Id", cert);
 StorageManagementClient storageManagementClient = new StorageManagementClient(credentials);
 storageManagementClient.StorageAccounts.Get("storage name"); //only classical storage can be got.
</code>```

packages.config

```<code><?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Hyak.Common" version="1.0.2" targetFramework="net462" />
  <package id="Microsoft.Azure.Common" version="2.0.4" targetFramework="net462" />
  <package id="Microsoft.Azure.Common.Dependencies" version="1.0.0" targetFramework="net462" />
  <package id="Microsoft.Bcl" version="1.1.9" targetFramework="net462" />
  <package id="Microsoft.Bcl.Async" version="1.0.168" targetFramework="net462" />
  <package id="Microsoft.Bcl.Build" version="1.0.14" targetFramework="net462" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net462" />
  <package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net462" developmentDependency="true" />
  <package id="Microsoft.Net.Http" version="2.2.22" targetFramework="net462" />
  <package id="Microsoft.WindowsAzure.Common" version="1.4.1" targetFramework="net462" />
  <package id="Microsoft.WindowsAzure.Common.Dependencies" version="1.1.1" targetFramework="net462" />
  <package id="Microsoft.WindowsAzure.Management.Storage" version="6.0.1" targetFramework="net462" />
  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net462" />
</packages>
</code>```

If you try to creat Resource management storage account, please have try use  Microsoft.Azure.Management.Fluent SDK. We also could get more demo code from github

Body:
I have imported the certificate which is found by the code as expected

Do you mean that you have installed the selfsigned  .cer certification on the Azure virtual machine?
If it is not that case, please have a try to export the cert from your develop machine and install it on the azure virtual  machine. And try to use following code test it again.

public static X509Certificate2 GetCert(string thumbprint)
        {

            X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            certStore.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
            if (certCollection.Count <= 0) return null;
            X509Certificate2 cert = certCollection[0];
            return cert;
        }

 var thumbprint= "cert thumbprint";
 SubscriptionCloudCredentials credentials = new CertificateCloudCredentials("subscription Id", cert);
 StorageManagementClient storageManagementClient = new StorageManagementClient(credentials);
 storageManagementClient.StorageAccounts.Get("storage name"); //only classical storage can be got.

packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Hyak.Common" version="1.0.2" targetFramework="net462" />
  <package id="Microsoft.Azure.Common" version="2.0.4" targetFramework="net462" />
  <package id="Microsoft.Azure.Common.Dependencies" version="1.0.0" targetFramework="net462" />
  <package id="Microsoft.Bcl" version="1.1.9" targetFramework="net462" />
  <package id="Microsoft.Bcl.Async" version="1.0.168" targetFramework="net462" />
  <package id="Microsoft.Bcl.Build" version="1.0.14" targetFramework="net462" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net462" />
  <package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net462" developmentDependency="true" />
  <package id="Microsoft.Net.Http" version="2.2.22" targetFramework="net462" />
  <package id="Microsoft.WindowsAzure.Common" version="1.4.1" targetFramework="net462" />
  <package id="Microsoft.WindowsAzure.Common.Dependencies" version="1.1.1" targetFramework="net462" />
  <package id="Microsoft.WindowsAzure.Management.Storage" version="6.0.1" targetFramework="net462" />
  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net462" />
</packages>

If you try to creat Resource management storage account, please have try use  Microsoft.Azure.Management.Fluent SDK. We also could get more demo code from github


答:
You should change the signature of your fail function to be

function( jqXHR, textStatus, errorThrown )

Then check the values of those last 2 arguments.

Title: How do I get the real reason why promise is rejected


问:
Logic error when using Newton-Raphson method in Python
I'm trying to calculate the approximated square root of a number in python using the Newton-Raphson method(The formula)

However the code does not work as it is stuck in the while loop(at least I think so). My plan is to calculate approximations until approximations differ by 1e–10.
This is the code I have right now:

```<code>k = input("Enter a number")
try:
    k = int(k)
    xi = 1
    xi2 = xi - (xi**2 - k)/(xi*2)
    diff = xi2 - xi
    while (diff > 0.0000000001):
        xi = xi2
        xi2 = xi - (xi**2 - k)/(xi*2)
        print(xi2)
    print(xi2)
except:
    print("bye")
</code>```

I'm new to python so any help will be much appreciated! thanks a lot! :)

Update:
I tried using the code below as some answer suggested, however when giving the input 2 it only gives me one loop before giving the answer(1.4166666666666667). The correct answer should be (1.4142135623730951).

```<code>while (diff > 0.0000000001):
    xi = xi2
    xi2 = xi - (xi**2 - k)/(xi*2)
    diff = xi2 - xi
</code>```

答:
The problem is that you are not changing the diff within the loop. The diff is always the initial value you assigned, so it never becomes less than 1e-10

```<code>while (diff > 0.0000000001):
        xi = xi2
        xi2 = xi - (xi**2 - k)/(xi*2)
        diff=xi2-xi
</code>```

EDIT:

Your problem is not a programming one.
After running some iterations with a print(diff) added to the while block I noticed there were negative values involved.

Consider a value of - 1e-2. It does satisfy the loop break condition because it's less than 1e-10, but it's actually a big distance away from desired result.

If you are dealing with differences, use absolutes:

```<code>k = input("Enter a number ")
k = int(k)
xi = 1
xi2 = xi - (xi**2 - k)/(xi*2)
diff = abs(xi2 - xi)
#0.0000000001
while (diff > 0.0000000001):
    xi = xi2
    xi2 = xi - (xi**2 - k)/(xi*2)
    diff = abs(xi2 - xi)
    print(diff)
print(xi2)
</code>```

Output:

```<code>$ python newton-raphson.py
Enter a number 2
0.08333333333333326
0.002450980392156854
2.123899820016817e-06
1.5947243525715749e-12
1.4142135623730951
</code>```

Body:
I'm trying to calculate the approximated square root of a number in python using the Newton-Raphson method(The formula)

However the code does not work as it is stuck in the while loop(at least I think so). My plan is to calculate approximations until approximations differ by 1e–10.
This is the code I have right now:

k = input("Enter a number")
try:
    k = int(k)
    xi = 1
    xi2 = xi - (xi**2 - k)/(xi*2)
    diff = xi2 - xi
    while (diff > 0.0000000001):
        xi = xi2
        xi2 = xi - (xi**2 - k)/(xi*2)
        print(xi2)
    print(xi2)
except:
    print("bye")

I'm new to python so any help will be much appreciated! thanks a lot! :)

Update:
I tried using the code below as some answer suggested, however when giving the input 2 it only gives me one loop before giving the answer(1.4166666666666667). The correct answer should be (1.4142135623730951).

while (diff > 0.0000000001):
    xi = xi2
    xi2 = xi - (xi**2 - k)/(xi*2)
    diff = xi2 - xi

Body:
The problem is that you are not changing the diff within the loop. The diff is always the initial value you assigned, so it never becomes less than 1e-10

while (diff > 0.0000000001):
        xi = xi2
        xi2 = xi - (xi**2 - k)/(xi*2)
        diff=xi2-xi

EDIT:

Your problem is not a programming one.
After running some iterations with a print(diff) added to the while block I noticed there were negative values involved.

Consider a value of - 1e-2. It does satisfy the loop break condition because it's less than 1e-10, but it's actually a big distance away from desired result.

If you are dealing with differences, use absolutes:

k = input("Enter a number ")
k = int(k)
xi = 1
xi2 = xi - (xi**2 - k)/(xi*2)
diff = abs(xi2 - xi)
#0.0000000001
while (diff > 0.0000000001):
    xi = xi2
    xi2 = xi - (xi**2 - k)/(xi*2)
    diff = abs(xi2 - xi)
    print(diff)
print(xi2)

Output:

$ python newton-raphson.py
Enter a number 2
0.08333333333333326
0.002450980392156854
2.123899820016817e-06
1.5947243525715749e-12
1.4142135623730951


问:
Add a new column with the list of values from all rows meeting a criterion
I have some list of data in the form of:

```<code>        date           value
'2017-01-01 01:01:01'   99
'2017-01-02 01:01:01'   98
'2017-01-03 01:01:01'   97
....
'2017-01-30 01:01:01'   95
'2017-01-31 01:01:01'   94
</code>```

I would like to add a column such that it is like:

```<code>        date          value     list
 ...
 ...
 ...
'2017-01-30 01:01:01'   95  [99,98,97,95]
'2017-01-31 01:01:01'   94  [99,98,97,95,94]
</code>```

Where the third column is a list of the values in the second column if the date falls within a certain time frame (say 5 days) prior to the date in the corresponding row.

Body:
I have some list of data in the form of:

        date           value
'2017-01-01 01:01:01'   99
'2017-01-02 01:01:01'   98
'2017-01-03 01:01:01'   97
....
'2017-01-30 01:01:01'   95
'2017-01-31 01:01:01'   94

I would like to add a column such that it is like:

        date          value     list
 ...
 ...
 ...
'2017-01-30 01:01:01'   95  [99,98,97,95]
'2017-01-31 01:01:01'   94  [99,98,97,95,94]

Where the third column is a list of the values in the second column if the date falls within a certain time frame (say 5 days) prior to the date in the corresponding row.

Body:
Something like this should work...

df = pd.DataFrame({'date': ['2017-01-01 01:01:01', '2017-01-02 01:01:01', '2017-01-03 01:01:01', '2017-01-30 01:01:01', '2017-01-31 01:01:01'],
                   'value': [99,98,97,95,94]})

df['date'] = pd.to_datetime(df['date'])

def get_list(row):

   subset = df[(row['date'] - df['date'] <= pd.to_timedelta('5 days')) & (row['date'] - df['date'] >= pd.to_timedelta('0 days'))]
   return str(subset['value'].tolist())

df['list'] = df.apply(get_list, axis=1)

Output:

              date  value          list
0 2017-01-01 01:01:01     99          [99]
1 2017-01-02 01:01:01     98      [99, 98]
2 2017-01-03 01:01:01     97  [99, 98, 97]
3 2017-01-30 01:01:01     95          [95]
4 2017-01-31 01:01:01     94      [95, 94]


问:
How do I make bottle work with google app engine?
This is the code,

```<code>import webapp2
from framework import bottle
from framework.bottle import route, template, request, error, debug

@route('/')
def root():
         return 'hello world'
class MainHandler(webapp2.RequestHandler):
   def get(self):
        root()

app = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=True)
</code>```

All the dependencies are there (framework, bottle, etc), however, when I deploy it using GAE, I just get an empty page!

Also I tried these and none of them worked, perhaps GAE changed its settings:

http://blog.rutwick.com/use-bottle-python-framework-with-google-app-engine

problems deploying bottle application with google app engine

答: Another solution that worked perfectly for me: https://github.com/GoogleCloudPlatform/appengine-bottle-skeleton</p>

Body:
This is the code,

import webapp2
from framework import bottle
from framework.bottle import route, template, request, error, debug

@route('/')
def root():
         return 'hello world'
class MainHandler(webapp2.RequestHandler):
   def get(self):
        root()

app = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=True)

All the dependencies are there (framework, bottle, etc), however, when I deploy it using GAE, I just get an empty page!

Also I tried these and none of them worked, perhaps GAE changed its settings:

http://blog.rutwick.com/use-bottle-python-framework-with-google-app-engine

problems deploying bottle application with google app engine


问:
Is there an iOS library to help me detect higher-level accelerometer gestures?
For example, let's say I want to detect if the user made a circle gesture so I can trigger something in my game. Is there a library that would allow me to just listen for some sort of "circleDectected" event?

If there isn't, would anyone find value in something like this if I developed it? Thanks!

答: It doesn't exist (as far as I know).  You would have to do it manually, which shouldn't be too hard, but it could potentially be time consuming.  I think it'll be fantastic if somebody made a library to do it.</p>


问:
how to install tensorflow for windows 7 32bit system?i installed python 3.5(32 bit) into my system and also installed anaconda 3.4.4(32 bit)
i have only 32bit system so i installed python 3.5 (64 bit ) error occurs .so i installed python 32bit successfully after that i followed by that document(http://tensorflow.org/install/…) i tried this into command prompt

```<code>C:\Users\mydoc>pip3 install --upgrade tensorflow
</code>```

but error occurs like this.

```<code>C:\Users\mydoc>pip install tensorflow

Collecting tensorflow
  Could not find a version that satisfies the requirement tensorflow (from versions: )
No matching distribution found for tensorflow

C:\Users\mydoc>
</code>```

please help me how to install tensorflow for my windows (32-bit)system.

答:
This question is already answered:

We have only tested the TensorFlow distribution on 64-bit Linux and
  Mac OS X, and distribute binary packages for those platforms only. Try
  following the source installation instructions to build a version
  for your platform.

  EDIT: One user has published instructions for running TensorFlow on a 32-bit ARM processor , which is promising for other 32-bit
  architectures. These instructions may have useful pointers for getting
  TensorFlow and Bazel to work in a 32-bit environment.

Body:
i have only 32bit system so i installed python 3.5 (64 bit ) error occurs .so i installed python 32bit successfully after that i followed by that document(http://tensorflow.org/install/…) i tried this into command prompt

C:\Users\mydoc>pip3 install --upgrade tensorflow

but error occurs like this.

C:\Users\mydoc>pip install tensorflow

Collecting tensorflow
  Could not find a version that satisfies the requirement tensorflow (from versions: )
No matching distribution found for tensorflow

C:\Users\mydoc>

please help me how to install tensorflow for my windows (32-bit)system.


问:
How can i make a custom list of files in django?
I have an app in Django where users upload some files(xlsx), the information gets extracted and the files are stored in /media.
I want a page/view where the users should be able to browse through the files by folder structure or alphabetically and they should be able to download them from the server.

What i have now is as basic as it gets:
this is the .html

```<code>{% block Content%}
{% if documents %}
    <ul id="files_ul">
        {% for document in documents %}
        <li>
            <a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a>
        </li>
        {% endfor %}
    </ul>
{% else %}
    <p> No documents. </p>
{% endif %}
{% endblock %}
</code>```

I have a model named Document and i've added this:

```<code>+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
</code>```

to urls.py which i know it's not secure.

I don't need something like Filer because i already have that but i didn't yet figure out how to configure.

I only know python and that not extensively and i'm new to Django so any help would be really appreciated.

It would be of great help if you could show me at least how to change the name of the files that appear now in this view,

```<code>document.docfile.name
</code>```

Results in folder1/folder2/filename and i would want only the filename to appear.

Model

```<code>class Document(models.Model):

    def filename(self):
        return os.path.basename(self.file.name)

    upload_user=models.ForeignKey(User, related_name='documents')
    upload_time=models.DateTimeField(auto_now_add=True)
    docfile=models.FileField(upload_to='documents/%Y/%m')
</code>```

答:
in your model where you have defined filefield put this function

```<code>def filename(self):
        return os.path.basename(self.docfile.name)
</code>```

and in template

```<code> <a href="{{ document.docfile.url }}">{{ document.filename }}</a>
</code>```

Body:
I have an app in Django where users upload some files(xlsx), the information gets extracted and the files are stored in /media.
I want a page/view where the users should be able to browse through the files by folder structure or alphabetically and they should be able to download them from the server.

What i have now is as basic as it gets:
this is the .html

{% block Content%}
{% if documents %}

        {% for document in documents %}

            {{ document.docfile.name }}

        {% endfor %}

{% else %}

 No documents.

{% endif %}
{% endblock %}

I have a model named Document and i've added this:

+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

to urls.py which i know it's not secure.

I don't need something like Filer because i already have that but i didn't yet figure out how to configure.

I only know python and that not extensively and i'm new to Django so any help would be really appreciated.

It would be of great help if you could show me at least how to change the name of the files that appear now in this view,

document.docfile.name

Results in folder1/folder2/filename and i would want only the filename to appear.

Model

class Document(models.Model):

    def filename(self):
        return os.path.basename(self.file.name)

    upload_user=models.ForeignKey(User, related_name='documents')
    upload_time=models.DateTimeField(auto_now_add=True)
    docfile=models.FileField(upload_to='documents/%Y/%m')

Body:
in your model where you have defined filefield put this function

def filename(self):
        return os.path.basename(self.docfile.name)

and in template

 <a href="{{ document.docfile.url }}">{{ document.filename }}</a>


问:
Oracle: Sql to update row of the same table based on value from another row of the same table
I need a sql to update the price column to 999 for the item records which meet the following condition:

The location of the ITEM should not be null for both the records.

Update the price to 999 for which one of the 2 records has location as null.

```
ID   LOCATION   ITEM   PRICE
1    NULL       101    0
2    123        101    0
3    NULL       102    0
4    NULL       102    0
5    124        103    0
6    NULL       103    0
```

OUTPUT TABLE SAMPLE

```
ID   LOCATION   ITEM   PRICE
1    NULL       101    999
2    123        101    0
3    NULL       102    0
4    NULL       102    0
5    124        103    0
6    NULL       103    999
```

答:
Use IN (or EXISTS) to check for the existence of a record with the item number where location is not null.

```<code>update items
set price = 999
where location is null
and item_id in (select item_id from items where location is not null);
</code>```

Body:
I need a sql to update the price column to 999 for the item records which meet the following condition:

The location of the ITEM should not be null for both the records.

Update the price to 999 for which one of the 2 records has location as null.

ID   LOCATION   ITEM   PRICE
1    NULL       101    0
2    123        101    0
3    NULL       102    0
4    NULL       102    0
5    124        103    0
6    NULL       103    0

OUTPUT TABLE SAMPLE

ID   LOCATION   ITEM   PRICE
1    NULL       101    999
2    123        101    0
3    NULL       102    0
4    NULL       102    0
5    124        103    0
6    NULL       103    999

Body:
Use IN (or EXISTS) to check for the existence of a record with the item number where location is not null.

update items
set price = 999
where location is null
and item_id in (select item_id from items where location is not null);


问:
django many to many field does not save
I have the following models:

```<code>class Offering(models.Model):
    entity = models.OneToOneField('companies.entity')
    company_type = models.ManyToManyField(CompanyTypeChoice, blank=True)

@python_2_unicode_compatible
class Tag(models.Model):
    word = models.CharField(max_length=64)

@python_2_unicode_compatible
class Entity(models.Model):
    tags = models.ManyToManyField(Tag,related_name='companies', blank=True, null=True)

class CompanyTypeChoice(models.Model):
title = models.CharField(max_length=64)
</code>```

I have the following loop that I want to create a M2M tag relation:

```<code>offerings = Offering.objects.all()
    for o in offerings:
        for ct in o.company_type.all():
            tag = Tag.objects.get(word=ct.title)
            e = Entity.objects.get(pk=o.entity.id)
            e.tags.add(tag)
</code>```

This does not save the M2M relationship. What am I doing wrong?

答:
You have specified related_name = "companies" for tags in your Entity model. So, thats why your many to many value not getting saved. To solve this, replace your line,

```<code>e.tags.add(tag)
</code>```

with,

```<code>e.companies.add(tag)
</code>```

I hope this helps.

Title: django many to many field does not save

Body:
I have the following models:

class Offering(models.Model):
    entity = models.OneToOneField('companies.entity')
    company_type = models.ManyToManyField(CompanyTypeChoice, blank=True)

@python_2_unicode_compatible
class Tag(models.Model):
    word = models.CharField(max_length=64)

@python_2_unicode_compatible
class Entity(models.Model):
    tags = models.ManyToManyField(Tag,related_name='companies', blank=True, null=True)

class CompanyTypeChoice(models.Model):
title = models.CharField(max_length=64)

I have the following loop that I want to create a M2M tag relation:

offerings = Offering.objects.all()
    for o in offerings:
        for ct in o.company_type.all():
            tag = Tag.objects.get(word=ct.title)
            e = Entity.objects.get(pk=o.entity.id)
            e.tags.add(tag)

This does not save the M2M relationship. What am I doing wrong?

Body:
You have specified related_name = "companies" for tags in your Entity model. So, thats why your many to many value not getting saved. To solve this, replace your line,

e.tags.add(tag)

with,

e.companies.add(tag)

I hope this helps.


问:
Why does the movement of my canvas box increase on click?

The Js Fiddle attached draw a box where ever the mouse is clicked. It works as expected for the most part. Except every time a new box is drawn on the canvas it speeds up more and more every time to the point where it's way too fast.

I've console.loged the dx/dy values and they are not increasing in value so it's not that, I don't think.

The dx value is what the position of the box is moving by.

Can any one shed some light?

var canvas = document.getElementById('myCanvas');
    var logger = document.getElementById('logger');
    var ctx = canvas.getContext('2d');
    var x = 0;
    var y = 0;
    var dx = -2;
    var dy = -2;
    var boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
    var boxSize = 20;
    var mousex,
        mousey;

    canvas.addEventListener('click',function(e){
      mousex = e.clientX;
      mousey = e.clientY;
      x = mousex - canvas.offsetLeft-(boxSize/2);
      y = mousey - canvas.offsetTop-(boxSize/2);
      draw();
    });

    function draw(){
      logger.innerHTML = "x: " + x + "y: " + y;
      ctx.clearRect(0,0,canvas.width,canvas.height);
      collistionDetection();
      ctx.beginPath();
      ctx.rect(x,y,boxSize,boxSize);
      ctx.fillStyle=boxColour;
      ctx.fill();
      ctx.closePath();
      x+=dx;
      y+=dy;
      requestAnimationFrame(draw);
    };

    function collistionDetection(){
      if(x<0 || x>canvas.width-boxSize){
        dx = -dx;
        boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
      };
      if(y<canvas.offsetTop-(boxSize/2) || y>canvas.height-boxSize){
        boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
        dy = -dy;
      };
    };```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* { padding: 0; margin: 0; }
    canvas { background: #eee; display: block;
      margin: 0 auto; margin-top:10px;
      }</code>```

<canvas id="myCanvas" width='480' height='320'></canvas>

```

Your help is always much appreciated.

Thanks

moe

答:
I think your requestAnimationFrames are not being cleared so your animation function is just being called more and more frequently every time you click. I made a small change to your code below which seems to help.

    var canvas = document.getElementById('myCanvas');
    var logger = document.getElementById('logger');
    var ctx = canvas.getContext('2d');
    var x = 0;
    var y = 0;
    var dx = -2;
    var dy = -2;
    var boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
    var boxSize = 20;
    var mousex,
        mousey;
    var lastAnimationFrame;
    canvas.addEventListener('click',function(e){
      mousex = e.clientX;
      mousey = e.clientY;
      x = mousex - canvas.offsetLeft-(boxSize/2);
      y = mousey - canvas.offsetTop-(boxSize/2);
      cancelAnimationFrame(lastAnimationFrame)
      draw();
    });

    function draw(){
      logger.innerHTML = "x: " + x + "y: " + y;
      ctx.clearRect(0,0,canvas.width,canvas.height);
      collistionDetection();
      ctx.beginPath();
      ctx.rect(x,y,boxSize,boxSize);
      ctx.fillStyle=boxColour;
      ctx.fill();
      ctx.closePath();
      x+=dx;
      y+=dy;
      lastAnimationFrame = requestAnimationFrame(draw);
    };

    function collistionDetection(){
      if(x<0 || x>canvas.width-boxSize){
        dx = -dx;
        boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
      };
      if(y<canvas.offsetTop-(boxSize/2) || y>canvas.height-boxSize){
        boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
        dy = -dy;
      };
    };```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    * { padding: 0; margin: 0; }
    canvas { background: #eee; display: block;
      margin: 0 auto; margin-top:10px;</code>```

<canvas id="myCanvas" width='480' height='320'></canvas>

```

Body:
The Js Fiddle attached draw a box where ever the mouse is clicked. It works as expected for the most part. Except every time a new box is drawn on the canvas it speeds up more and more every time to the point where it's way too fast.

I've console.loged the dx/dy values and they are not increasing in value so it's not that, I don't think.

The dx value is what the position of the box is moving by.

Can any one shed some light?

var canvas = document.getElementById('myCanvas');
    var logger = document.getElementById('logger');
    var ctx = canvas.getContext('2d');
    var x = 0;
    var y = 0;
    var dx = -2;
    var dy = -2;
    var boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
    var boxSize = 20;
    var mousex,
        mousey;

    canvas.addEventListener('click',function(e){
      mousex = e.clientX;
      mousey = e.clientY;
      x = mousex - canvas.offsetLeft-(boxSize/2);
      y = mousey - canvas.offsetTop-(boxSize/2);
      draw();
    });

    function draw(){
      logger.innerHTML = "x: " + x + "y: " + y;
      ctx.clearRect(0,0,canvas.width,canvas.height);
      collistionDetection();
      ctx.beginPath();
      ctx.rect(x,y,boxSize,boxSize);
      ctx.fillStyle=boxColour;
      ctx.fill();
      ctx.closePath();
      x+=dx;
      y+=dy;
      requestAnimationFrame(draw);
    };

    function collistionDetection(){
      if(x<0 || x>canvas.width-boxSize){
        dx = -dx;
        boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
      };
      if(y<canvas.offsetTop-(boxSize/2) || y>canvas.height-boxSize){
        boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
        dy = -dy;
      };
    };

* { padding: 0; margin: 0; }
    canvas { background: #eee; display: block;
      margin: 0 auto; margin-top:10px;
      }

<canvas id="myCanvas" width='480' height='320'></canvas>

Your help is always much appreciated.

Thanks

moe

Body:
I think your requestAnimationFrames are not being cleared so your animation function is just being called more and more frequently every time you click. I made a small change to your code below which seems to help.

    var canvas = document.getElementById('myCanvas');
    var logger = document.getElementById('logger');
    var ctx = canvas.getContext('2d');
    var x = 0;
    var y = 0;
    var dx = -2;
    var dy = -2;
    var boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
    var boxSize = 20;
    var mousex,
        mousey;
    var lastAnimationFrame;
    canvas.addEventListener('click',function(e){
      mousex = e.clientX;
      mousey = e.clientY;
      x = mousex - canvas.offsetLeft-(boxSize/2);
      y = mousey - canvas.offsetTop-(boxSize/2);
      cancelAnimationFrame(lastAnimationFrame)
      draw();
    });

    function draw(){
      logger.innerHTML = "x: " + x + "y: " + y;
      ctx.clearRect(0,0,canvas.width,canvas.height);
      collistionDetection();
      ctx.beginPath();
      ctx.rect(x,y,boxSize,boxSize);
      ctx.fillStyle=boxColour;
      ctx.fill();
      ctx.closePath();
      x+=dx;
      y+=dy;
      lastAnimationFrame = requestAnimationFrame(draw);
    };

    function collistionDetection(){
      if(x<0 || x>canvas.width-boxSize){
        dx = -dx;
        boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
      };
      if(y<canvas.offsetTop-(boxSize/2) || y>canvas.height-boxSize){
        boxColour = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
        dy = -dy;
      };
    };

    * { padding: 0; margin: 0; }
    canvas { background: #eee; display: block;
      margin: 0 auto; margin-top:10px;

<canvas id="myCanvas" width='480' height='320'></canvas>
<div id="logger"></div>


问:
How can I fix 'android.os.NetworkOnMainThreadException'?
I got an error while running my Android project for RssReader.

Code:

```<code>URL url = new URL(urlToRssFeed);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RssHandler theRSSHandler = new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();
</code>```

And it shows the below error:

```<code>android.os.NetworkOnMainThreadException
</code>```

How can I fix this issue?

答:
RxAndroid is another better alternative to this problem and it saves us from hassles of creating threads and then posting results on Android UI thread.

We just need to specify threads on which tasks need to be executed and everything is handled internally.

```<code>Observable<List<String>> musicShowsObservable = Observable.fromCallable(new Callable<List<String>>() {

  @Override
  public List<String> call() {
    return mRestClient.getFavoriteMusicShows();
  }

});

mMusicShowSubscription = musicShowsObservable
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(new Observer<List<String>>() {

    @Override
    public void onCompleted() { }

    @Override
    public void onError(Throwable e) { }

    @Override
    public void onNext(List<String> musicShows) {
        listMusicShows(musicShows);
    }
});
</code>```

By specifiying (Schedulers.io()), RxAndroid will run getFavoriteMusicShows() on a different thread.

By using AndroidSchedulers.mainThread() we want to observe this Observable on the UI thread, i.e., we want our onNext() callback to be called on the UI thread.

Body:
I got an error while running my Android project for RssReader.

Code:

URL url = new URL(urlToRssFeed);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RssHandler theRSSHandler = new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();

And it shows the below error:

android.os.NetworkOnMainThreadException

How can I fix this issue?

Body:
RxAndroid is another better alternative to this problem and it saves us from hassles of creating threads and then posting results on Android UI thread.

We just need to specify threads on which tasks need to be executed and everything is handled internally.

Observable<List<String>> musicShowsObservable = Observable.fromCallable(new Callable<List<String>>() {

  @Override
  public List<String> call() {
    return mRestClient.getFavoriteMusicShows();
  }

});

mMusicShowSubscription = musicShowsObservable
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(new Observer<List<String>>() {

    @Override
    public void onCompleted() { }

    @Override
    public void onError(Throwable e) { }

    @Override
    public void onNext(List<String> musicShows) {
        listMusicShows(musicShows);
    }
});

By specifiying (Schedulers.io()), RxAndroid will run getFavoriteMusicShows() on a different thread.

By using AndroidSchedulers.mainThread() we want to observe this Observable on the UI thread, i.e., we want our onNext() callback to be called on the UI thread.


问:
How to set session in two different browser in same method with codeigniter?
I have same method to save session with codeigniter. It's work in chrome but in firefox can't save session.</p>

答:
You can go through below solutions and use depends on your needs.

if you are using filebase.

```<code>$config['sess_save_path'] = FCPATH . 'application/ci_sessions/';
</code>```

If you store in database Then

```<code>$config['sess_driver'] = 'database'; // Change files to database
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions'; // This will be your database table for sessions
$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
</code>```

ci_session Table defination

```<code>CREATE TABLE IF NOT EXISTS `ci_sessions` (
    `id` varchar(40) NOT NULL,
    `ip_address` varchar(45) NOT NULL,
    `timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
    `data` blob NOT NULL,
    KEY `ci_sessions_timestamp` (`timestamp`)
);
</code>```

Please note: If you are sharing same session with multiple domain than better to go with database storage.

Body:
You can go through below solutions and use depends on your needs.

if you are using filebase.

$config['sess_save_path'] = FCPATH . 'application/ci_sessions/';

If you store in database Then

$config['sess_driver'] = 'database'; // Change files to database
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions'; // This will be your database table for sessions
$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

ci_session Table defination

CREATE TABLE IF NOT EXISTS `ci_sessions` (
    `id` varchar(40) NOT NULL,
    `ip_address` varchar(45) NOT NULL,
    `timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
    `data` blob NOT NULL,
    KEY `ci_sessions_timestamp` (`timestamp`)
);

Please note: If you are sharing same session with multiple domain than better to go with database storage.


问:
std::map crappy chars only in release mode
I have an std::map as parameter for an function and in Debug Mode (VS2008) the map have the correct keys and values, but when I start the program in Release there are crappy chars in to the map!

Code dump:

```<code>    std::map<CString, CString> libVersions;
    ... // fill values
    utilFunctions->Function(&libVersions))

    bool UtilityFunctions::Function(std::map<CString,CString> *dllMapData)
    {
       ...
       map<CString,CString>::iterator it;

       for(it=dllMapData->begin(); it!=dllMapData->end(); it++)
       {
          ...
       }
       ...
    }
</code>```

Any ideas why this code is not functional in Release mode???

Thanks and greets

答: My guess is that in release you are still compiling against the debug CRT and don't have _DEBUG defined (or vice versa).</p>

Body:
I have an std::map as parameter for an function and in Debug Mode (VS2008) the map have the correct keys and values, but when I start the program in Release there are crappy chars in to the map!

Code dump:

    std::map<CString, CString> libVersions;
    ... // fill values
    utilFunctions->Function(&libVersions))

    bool UtilityFunctions::Function(std::map<CString,CString> *dllMapData)
    {
       ...
       map<CString,CString>::iterator it;

       for(it=dllMapData->begin(); it!=dllMapData->end(); it++)
       {
          ...
       }
       ...
    }

Any ideas why this code is not functional in Release mode???

Thanks and greets


问:
Finding new line character in a String in "Swift 3"
In my app I am receiving some incoming data from a web service. In that data some wrong values can also be received like new line characters. I want to find in response string that if it contains a new line character or not.

Before Swift 3 I was able to do it like this

```<code>string.rangeOfString("\n")) == nil)
</code>```

But in Swift 3 this methods is no longer available. However substring method is available which does with the help of Range.

I want to detect if my string contains "\n" how this would be accomplished using this method in Swift 3.

答: If you just want to know if it is there and don't care where it is, string.contains("\n") will return true if it is there and false if not.

Body:
In my app I am receiving some incoming data from a web service. In that data some wrong values can also be received like new line characters. I want to find in response string that if it contains a new line character or not.

Before Swift 3 I was able to do it like this

string.rangeOfString("\n")) == nil)

But in Swift 3 this methods is no longer available. However substring method is available which does with the help of Range.

I want to detect if my string contains "\n" how this would be accomplished using this method in Swift 3.


问:
Get median of array
I have an array that looks like this:

```<code>let arr = [1,2,3,4,5,6,7,8,9]
</code>```

I know you can get min and max by:

```<code>let min = arr.min()
let max = arr.max()
</code>```

But how do you get the median?

答:
To get the median you can use the following:

```<code>let median = arr.sorted(by: <)[arr.count / 2]
</code>```

In your case it will return 5.

As @Nirav pointed out [1,2,3,4,5,6,7,8] will return 5 but should return 4.5.

Use this instead:

```<code>func calculateMedian(array: [Int]) -> Float {
    let sorted = array.sorted()
    if sorted.count % 2 == 0 {
        return Float((sorted[(sorted.count / 2)] + sorted[(sorted.count / 2) - 1])) / 2
    } else {
        return Float(sorted[(sorted.count - 1) / 2])
    }
}
</code>```

Usage:

```<code>let array = [1,2,3,4,5,6,7,8]
let m2 = calculateMedian(array: array) // 4.5
</code>```

Title: Get median of array

Body:
I have an array that looks like this:

let arr = [1,2,3,4,5,6,7,8,9]

I know you can get min and max by:

let min = arr.min()
let max = arr.max()

But how do you get the median?

Body:
To get the median you can use the following:

let median = arr.sorted(by: <)[arr.count / 2]

In your case it will return 5.

As @Nirav pointed out [1,2,3,4,5,6,7,8] will return 5 but should return 4.5.

Use this instead:

func calculateMedian(array: [Int]) -> Float {
    let sorted = array.sorted()
    if sorted.count % 2 == 0 {
        return Float((sorted[(sorted.count / 2)] + sorted[(sorted.count / 2) - 1])) / 2
    } else {
        return Float(sorted[(sorted.count - 1) / 2])
    }
}

Usage:

let array = [1,2,3,4,5,6,7,8]
let m2 = calculateMedian(array: array) // 4.5


问:
Getting first day of a week with NSDateComponents : changing year
Hello
I have a problem with setting a firstWeekDay, here is what I do:

```<code>NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
comp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit) fromDate:targetDate];
[comp setWeekday:2];

NSDate *firstWeekDay = [gregorian dateFromComponents:comp];
</code>```

If Saturday 2011-01-01 is targetDate, the firstWeekDay in my calendar appears to be Monday 2011-12-26, but in fact it should be Monday 2010-12-26.  How can I make it right?

答:
```<code>// Make these two methods as categories to NSDate
// Use This to get First date of the week (Monday)

- (NSDate *) getFirstDayOfWeek {

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSDateComponents *compOfDate = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday) fromDate:self];

    NSInteger numOfDaysToAdd = compOfDate.weekday == 1 ? -6 : (2 - compOfDate.weekday);

    NSDateComponents *compToAdd = [[NSDateComponents alloc] init];

    compToAdd.day = numOfDaysToAdd;

    return [calendar dateByAddingComponents:compToAdd toDate:self options:0];
}

// Use This to get last date of the week (Sunday)

- (NSDate *)getLastDayOfWeek {

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSDateComponents *compOfDate = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday) fromDate:self];

    NSInteger numOfDaysToAdd = compOfDate.weekday == 1 ? 0 : (8 - compOfDate.weekday);

    NSDateComponents *compToAdd = [[NSDateComponents alloc] init];

    compToAdd.day = numOfDaysToAdd;

    return [calendar dateByAddingComponents:compToAdd toDate:self options:0];
}
</code>```

Body:
Hello
I have a problem with setting a firstWeekDay, here is what I do:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
comp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit) fromDate:targetDate];
[comp setWeekday:2];

NSDate *firstWeekDay = [gregorian dateFromComponents:comp];

If Saturday 2011-01-01 is targetDate, the firstWeekDay in my calendar appears to be Monday 2011-12-26, but in fact it should be Monday 2010-12-26.  How can I make it right?


问:
New pull request without unmerged commits
I have a pull request on a repository. The commits are still unmerged. Now, I want to make another pull request, totally independent from the previous one. When I create a new branch and make the new commits, all of the unmerged commits are also alongside with the new ones!

I want to create a new pull request without the unmerged commits. Please help me on how should I do that as I'm new to git :)

答:
Create Satsh which will temporary store you commits in some storage

```<code>git stash
</code>```

Then create a new brnach

```<code>git checkout -b "new branch name".
</code>```

Then get all that commits in the new branch by poping the stash

```<code>git stash pop
</code>```

all commit which is in old branch will be saved here.

or else
If you want to commit and all changes are also committed to new branch so simply just commit all changes in that branch and make a new branch.

```<code>git checkout -b "new branch"
</code>```

as you created new branch from previous branch all changes are taken in new branch

Body:
Create Satsh which will temporary store you commits in some storage

git stash

Then create a new brnach

git checkout -b "new branch name".

Then get all that commits in the new branch by poping the stash

git stash pop

all commit which is in old branch will be saved here.

or else
If you want to commit and all changes are also committed to new branch so simply just commit all changes in that branch and make a new branch.

git checkout -b "new branch"

as you created new branch from previous branch all changes are taken in new branch


问:
Parse this string of a JSONObject that contains a JSONArray of JSONObjects
I want to parse this string of a JSONObject that contains a JSONArray of JSONObjects

```<code>Array
(
[Assignments] => Array
    (
        [0] => Array
            (
                [ass_name] => Test123
                [class_id] => 2
                [date_assigned] => 2017-08-23
                [done] => false
                [due] => 2017-08-23 13:34:54
                [id] => 10
                [weight] => 65
            )

    )

)
</code>```

I tried using

```<code>$json = json_decode($testing,true);
echo $json;
</code>```

where $testing is my entire string but $json echos nothing.

答:
Check this example,

echo => Outputs one or more strings separated by commas

print_r => Accepts not just strings but other types including arrays and objects, formatting them to be readable

```<code>$testing = array("Assignments"=>array("ass_name"=>"Test123","class_id"=>"2","date_assigned"=>"2017-08-23","done"=>"false","due"=>"2017-08-23 13:34:54","id"=>"10","weight"=>"65"));

$json = json_encode($testing); //convert array to json
echo $json;

$json1 = json_decode($json,true); //convert json to array
print_r($json1);
</code>```

Body:
I want to parse this string of a JSONObject that contains a JSONArray of JSONObjects

Array
(
[Assignments] => Array
    (
        [0] => Array
            (
                [ass_name] => Test123
                [class_id] => 2
                [date_assigned] => 2017-08-23
                [done] => false
                [due] => 2017-08-23 13:34:54
                [id] => 10
                [weight] => 65
            )

    )

)

I tried using

$json = json_decode($testing,true);
echo $json;

where $testing is my entire string but $json echos nothing.

Body:
Check this example,

echo => Outputs one or more strings separated by commas

print_r => Accepts not just strings but other types including arrays and objects, formatting them to be readable

$testing = array("Assignments"=>array("ass_name"=>"Test123","class_id"=>"2","date_assigned"=>"2017-08-23","done"=>"false","due"=>"2017-08-23 13:34:54","id"=>"10","weight"=>"65"));

$json = json_encode($testing); //convert array to json
echo $json;

$json1 = json_decode($json,true); //convert json to array
print_r($json1);