问:
Anaconda install on Windows is stuck on executing install.py
Update: Two months after posting this question, I switched to a fresh install of Windows 10 and was able to install the correct version of Anaconda Python. Unfortunately the answers came too late for me to test them.

I want to switch from the 32-bit version of Anaconda Python 3.5 to the 64-bit version. First I uninstalled Anaconda through the 'Programs and Features' window, then I downloaded the Anaconda3-4.2.0-Windows-x86_64.exe installer and attempted to run it. For reference, I am using the 64-bit version of Windows 7. After some initial processing the installer is stuck on Execute: "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pythonw.exe" -E -s "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pkgs\.install.py" --root-prefix "C:\Users\user.name\AppData\Local\Continuum\Anaconda3" --post root

It does not throw any errors, it just hangs. I let it run throughout the night to see if it would progress any further, but unfortunately it was still stuck in the same place in the morning. Afterwards I tried looking for hidden Continuum files from the previous installation and removed those - also removed Anaconda from my PATH variable. I even tried installing miniconda instead of anaconda, but both installers get stuck in the exact same place. Am I missing a hidden file somewhere which is causing the Anaconda installer to hang?

Below is part of the installation log up until the execution command where it gets stuck.

```<code>Installing: dill-0.2.5-py35_0 (into root)
untgz::extract -d 'C:\Users\user.name\AppData\Local\Continuum\Anaconda3' -zbz2 'C:\Users\use.name\AppData\Local\Continuum\Anaconda3\pkgs\dill-0.2.5-py35_0.tar.bz2'
Writing Lib/site-packages/dill-0.2.5-py3.5.egg-info
Writing Lib/site-packages/dill/__diff.py
Writing Lib/site-packages/dill/__init__.py
Writing Lib/site-packages/dill/__pycache__/__diff.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/__init__.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/_objects.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/detect.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/dill.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/info.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/objtypes.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/pointers.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/settings.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/source.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/temp.cpython-35.pyc
Writing Lib/site-packages/dill/_objects.py
Writing Lib/site-packages/dill/detect.py
Writing Lib/site-packages/dill/dill.py
Writing Lib/site-packages/dill/info.py
Writing Lib/site-packages/dill/objtypes.py
Writing Lib/site-packages/dill/pointers.py
Writing Lib/site-packages/dill/settings.py
Writing Lib/site-packages/dill/source.py
Writing Lib/site-packages/dill/temp.py
Writing Scripts/get_objgraph.py
Writing Scripts/unpickle.py
Writing info/LICENSE.txt
Writing info/files
Writing info/has_prefix
Writing info/index.json
Writing info/platform
Writing info/recipe/bld.bat
Writing info/recipe/build.sh
Writing info/recipe/meta.yaml
extraction complete.
Execute: "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pythonw.exe" -E -s "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pkgs\.install.py" --root-prefix "C:\Users\user.name\AppData\Local\Continuum\Anaconda3" --post root
</code>```

答:
As mentioned by ClaraJacintho in https://github.com/ContinuumIO/anaconda-issues/issues/6258#issuecomment-565063685:

I found that the "security module" called Warsaw (or GAS antifraud), used by many banks in Brazil for internet banking security, was interfering with the installation. I uninstalled it and was able to install Anaconda3.2019.10 64 bits on my Windows 10 machine.

It worked for me.

Body:
Update: Two months after posting this question, I switched to a fresh install of Windows 10 and was able to install the correct version of Anaconda Python. Unfortunately the answers came too late for me to test them.

I want to switch from the 32-bit version of Anaconda Python 3.5 to the 64-bit version. First I uninstalled Anaconda through the 'Programs and Features' window, then I downloaded the Anaconda3-4.2.0-Windows-x86_64.exe installer and attempted to run it. For reference, I am using the 64-bit version of Windows 7. After some initial processing the installer is stuck on Execute: "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pythonw.exe" -E -s "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pkgs\.install.py" --root-prefix "C:\Users\user.name\AppData\Local\Continuum\Anaconda3" --post root

It does not throw any errors, it just hangs. I let it run throughout the night to see if it would progress any further, but unfortunately it was still stuck in the same place in the morning. Afterwards I tried looking for hidden Continuum files from the previous installation and removed those - also removed Anaconda from my PATH variable. I even tried installing miniconda instead of anaconda, but both installers get stuck in the exact same place. Am I missing a hidden file somewhere which is causing the Anaconda installer to hang?

Below is part of the installation log up until the execution command where it gets stuck.

Installing: dill-0.2.5-py35_0 (into root)
untgz::extract -d 'C:\Users\user.name\AppData\Local\Continuum\Anaconda3' -zbz2 'C:\Users\use.name\AppData\Local\Continuum\Anaconda3\pkgs\dill-0.2.5-py35_0.tar.bz2'
Writing Lib/site-packages/dill-0.2.5-py3.5.egg-info
Writing Lib/site-packages/dill/__diff.py
Writing Lib/site-packages/dill/__init__.py
Writing Lib/site-packages/dill/__pycache__/__diff.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/__init__.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/_objects.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/detect.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/dill.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/info.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/objtypes.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/pointers.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/settings.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/source.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/temp.cpython-35.pyc
Writing Lib/site-packages/dill/_objects.py
Writing Lib/site-packages/dill/detect.py
Writing Lib/site-packages/dill/dill.py
Writing Lib/site-packages/dill/info.py
Writing Lib/site-packages/dill/objtypes.py
Writing Lib/site-packages/dill/pointers.py
Writing Lib/site-packages/dill/settings.py
Writing Lib/site-packages/dill/source.py
Writing Lib/site-packages/dill/temp.py
Writing Scripts/get_objgraph.py
Writing Scripts/unpickle.py
Writing info/LICENSE.txt
Writing info/files
Writing info/has_prefix
Writing info/index.json
Writing info/platform
Writing info/recipe/bld.bat
Writing info/recipe/build.sh
Writing info/recipe/meta.yaml
extraction complete.
Execute: "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pythonw.exe" -E -s "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pkgs\.install.py" --root-prefix "C:\Users\user.name\AppData\Local\Continuum\Anaconda3" --post root


来源: stackexchange

问:
Rise up circle using negative margin only and not using position?
How can I rise up the circle by using negative margin only? I don't want to use position.

```<code>.task6 {
  margin-top: 5px;
  border: 1px solid red;
}

.task6_row {
  margin: 20px 0;
  width: 100%;
  background-color: lightgray;
  padding: 10px 0;
  border: 1px solid green;
}

.feature_item {
  width: 32%;
  background-color: white;
  padding: 0;
  margin: 5px;
  border-bottom: 1px solid blue;
  text-align: center;
  position: relative;
}

.feature_number {
  width: 50px;
  height: 50px;
  line-height: 50px;
  display: inline-block;
  /* position: absolute; */
  border-radius: 50%;
  background-color: blue;
  color: white;
  text-align: center;
  margin-top: -12px;
  font-family: Arial, Tahoma;
}

.feature_name {}

.feature_desc {
  color: lightgray;
}

.example {
  display: inline-block;
  margin: 10px 0;
  padding: 10px;
  background-color: blue;
  color: white;
  border-radius: 8px;
}
</code>```

1

        cheap price

        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Placeat, ratione?

      see example

```

答:
As an alternative, transform() will also move the element using negative values. Replace the margin-top property with the one below, declaring the amount you wish it to translate in the Y-axis and X-axis values. Example:</p>

```<code>transform: translate(0, -50%);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I rise up the circle by using negative margin only? I don't want to use position.

.task6 {
  margin-top: 5px;
  border: 1px solid red;
}

.task6_row {
  margin: 20px 0;
  width: 100%;
  background-color: lightgray;
  padding: 10px 0;
  border: 1px solid green;
}

.feature_item {
  width: 32%;
  background-color: white;
  padding: 0;
  margin: 5px;
  border-bottom: 1px solid blue;
  text-align: center;
  position: relative;
}

.feature_number {
  width: 50px;
  height: 50px;
  line-height: 50px;
  display: inline-block;
  /* position: absolute; */
  border-radius: 50%;
  background-color: blue;
  color: white;
  text-align: center;
  margin-top: -12px;
  font-family: Arial, Tahoma;
}

.feature_name {}

.feature_desc {
  color: lightgray;
}

.example {
  display: inline-block;
  margin: 10px 0;
  padding: 10px;
  background-color: blue;
  color: white;
  border-radius: 8px;
}

1

        cheap price

        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Placeat, ratione?

      see example

Body:
As an alternative, transform() will also move the element using negative values. Replace the margin-top property with the one below, declaring the amount you wish it to translate in the Y-axis and X-axis values. Example:

transform: translate(0, -50%);


问:
Upload artifact using Nexus API with PowerShell
Does anybody know what the request body looks like if I want to use Nexus API to upload artifact to a repo?

```<code>$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("admin123:password123"))
$header = @{authorization = "Basic $token" }

$body = @{
    'raw.dictionary' = '/TestArtifact/Prod/'
    'raw.asset1' = 'c:\temp\lenovo.zip'
    'raw.asset1.filename' = 'lenovo.zip'

} | Convertto-Json

Invoke-RestMethod -Method POST -Uri 'http://xx.xx.xxx.xxx:8081/service/rest/v1/components?repository=TestRepo' -ContentType 'application/json'-Body $body -Headers $header
</code>```

I'm getting 'Invoke-RestMethod: Response status code does not indicate success: 415 (Unsupported Media Type)'

答:
Lets try and figure this out.

The command looks like you are trying to do is

```<code>curl -v -u admin:admin123 -X POST 'http://localhost:8081/service/rest/v1/components?repository=maven-releases' -F maven2.groupId=com.google.guava -F maven2.artifactId=guava -F maven2.version=24.0-jre -F maven2.asset1=@guava-24.0-jre.jar -F maven2.asset1.extension=jar -F maven2.asset2=@guava-24.0-jre-sources.jar -F maven2.asset2.classifier=sources -F maven2.asset2.extension=jar
</code>```

It looks like the main issue we have is that you didnt convert the file to bytes.

-F @[FileName] is a Binary File

The only change really needing to be done was changing

```<code>'raw.asset1' = 'c:\temp\lenovo.zip'
</code>```

to

```<code>'raw.asset1' = [System.IO.File]::ReadAllBytes("c:\temp\lenovo.zip")
</code>```

Body:
Does anybody know what the request body looks like if I want to use Nexus API to upload artifact to a repo?

$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("admin123:password123"))
$header = @{authorization = "Basic $token" }

$body = @{
    'raw.dictionary' = '/TestArtifact/Prod/'
    'raw.asset1' = 'c:\temp\lenovo.zip'
    'raw.asset1.filename' = 'lenovo.zip'

} | Convertto-Json

Invoke-RestMethod -Method POST -Uri 'http://xx.xx.xxx.xxx:8081/service/rest/v1/components?repository=TestRepo' -ContentType 'application/json'-Body $body -Headers $header

I'm getting 'Invoke-RestMethod: Response status code does not indicate success: 415 (Unsupported Media Type)'

Body:
Lets try and figure this out.

The command looks like you are trying to do is

curl -v -u admin:admin123 -X POST 'http://localhost:8081/service/rest/v1/components?repository=maven-releases' -F maven2.groupId=com.google.guava -F maven2.artifactId=guava -F maven2.version=24.0-jre -F maven2.asset1=@guava-24.0-jre.jar -F maven2.asset1.extension=jar -F maven2.asset2=@guava-24.0-jre-sources.jar -F maven2.asset2.classifier=sources -F maven2.asset2.extension=jar

It looks like the main issue we have is that you didnt convert the file to bytes.

-F @[FileName] is a Binary File

The only change really needing to be done was changing

'raw.asset1' = 'c:\temp\lenovo.zip'

to

'raw.asset1' = [System.IO.File]::ReadAllBytes("c:\temp\lenovo.zip")


问:
Convert hex to ascii characters
Is it possible to represent a sequence of hex characters (0-9A-F) with a sequence of 0-9a-zA-Z characters, so the the result sequence is smaller and can be decoded?

For example:

```<code>$hex = '5d41402abc4b2a76b9719d911017c592';
echo $string = encode($hex); // someASCIIletters123
echo decode(string) == $hex; //true
</code>```

答:
The built-in php functions may help some landing here on a search:

// https://www.php.net/manual/en/function.hex2bin
$hex = '6578616d706c65206865782064617461';
echo hex2bin($hex); // example hex data
```

ContentLicense: CC BY-SA 3.0

Title: Convert hex to ascii characters

Body:
Is it possible to represent a sequence of hex characters (0-9A-F) with a sequence of 0-9a-zA-Z characters, so the the result sequence is smaller and can be decoded?

For example:

$hex = '5d41402abc4b2a76b9719d911017c592';
echo $string = encode($hex); // someASCIIletters123
echo decode(string) == $hex; //true


问:
Question about Java synchronized
The Java documentation says that "it is not possible for two invocations of synchronized methods on the same object to interleave".  What I need to know is whether synchronized will also prevent a synchronized method in two different instances of the same class from interleaving.

E.g. class Worker has method called process().  We have several instances of Worker running in their own threads.  We want to prevent more than one instance running the process() method simultaneously.  Will synchronized do this?

Thanks.

答:
Not unless the method is static. A synchronized non-static method takes a lock on the object (instance) on which it is invoked, not on the class.

A synchronized static method takes a lock on the class, so that could help - but it's often not very practical.

What you could do is have a static member object in your class, and do a synchronized block on that (class-global) object in your process method.

Title: Question about Java synchronized


问:
Searchfield to search for specific planets
I tried adding a search field to search for planets.
Can someone help me to fix this please?

The error I get is this:
    TypeError: Cannot read property 'state' of undefined
    handleChange
    C:/Users/charl/Desktop/IRONHACK/Paperbox/paperbox/src/pages/Home.js:29
      26 |    }
      27 |
      28 |    handleChange(e){ // eslint-disable-next-line

29 |        const planetssearchlist = this.state.planets.filter(planet => {
           | ^  30 |             if(planet.name){
        31 |                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
        32 |                    return true

```<code>import React, { PureComponent } from 'react'
import axios from "axios";

class Home extends PureComponent {
    constructor(props) {
        super(props)

        this.state = {
            planets: []
        }
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: "https://swapi.dev/api/planets/"
        })
        .then(response => {
            console.log(response)
            let planetslist = response.data.results;
            this.setState({planets: planetslist})
        })
        .catch(error => {
            console.log("You've made an error with the planets load charles: ",error)
        })
    }

    handleChange(e){ // eslint-disable-next-line
        const planetssearchlist = this.state.planets.filter(planet => {
             if(planet.name){
                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
                    return true
                }
            }
            this.setState({
                planets:planetssearchlist
            })
        })
    }

    render() {
        return (

        <div>
            <h1>Star Wars Planets</h1>

            <form>
                <input placeholder="searchbar" type="text" onChange={this.handleChange}></input>
            </form>

            {
                this.state.planets.map((planet,i) => (
                        <p key={i}>{planet.name}</p>
                ))
            }

        </div>

        )
    }
}

export default Home
</code>```

答:
You must bind the function to component, you can use lambda function syntax to define your method:

```<code>handleChange = (e) => {}
</code>```

or in constructor:

```<code>this.handleChange = this.handleChange.bind(this)
</code>```

Also your handleChange function is not working properly. You need to setState outside of the filter function. You can find working sample here: https://codesandbox.io/s/jovial-stallman-fs012?file=/src/index.js

Further things to do:

You are directly editing planet array in handleChange function. When user searches string you are removing items from state.planets. So when user removes search string, old planets will not be showing because of the removal.

You need to store planets in a immutable array.

After you did the search filter immutable array to create presentation array.

Display presentation array in render function.

Also i highly recommend to checkout the documentation for Passing Functions to Components:https://reactjs.org/docs/faq-functions.html

Body:
I tried adding a search field to search for planets.
Can someone help me to fix this please?

The error I get is this:
    TypeError: Cannot read property 'state' of undefined
    handleChange
    C:/Users/charl/Desktop/IRONHACK/Paperbox/paperbox/src/pages/Home.js:29
      26 |    }
      27 |
      28 |    handleChange(e){ // eslint-disable-next-line

29 |        const planetssearchlist = this.state.planets.filter(planet => {
           | ^  30 |             if(planet.name){
        31 |                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
        32 |                    return true

import React, { PureComponent } from 'react'
import axios from "axios";

class Home extends PureComponent {
    constructor(props) {
        super(props)

        this.state = {
            planets: []
        }
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: "https://swapi.dev/api/planets/"
        })
        .then(response => {
            console.log(response)
            let planetslist = response.data.results;
            this.setState({planets: planetslist})
        })
        .catch(error => {
            console.log("You've made an error with the planets load charles: ",error)
        })
    }

    handleChange(e){ // eslint-disable-next-line
        const planetssearchlist = this.state.planets.filter(planet => {
             if(planet.name){
                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
                    return true
                }
            }
            this.setState({
                planets:planetssearchlist
            })
        })
    }

    render() {
        return (

Star Wars Planets

            <form>
                <input placeholder="searchbar" type="text" onChange={this.handleChange}></input>
            </form>

            {
                this.state.planets.map((planet,i) => (

{planet.name}

                ))
            }

        )
    }
}

export default Home

Body:
You must bind the function to component, you can use lambda function syntax to define your method:

handleChange = (e) => {}

or in constructor:

this.handleChange = this.handleChange.bind(this)

Also your handleChange function is not working properly. You need to setState outside of the filter function. You can find working sample here: https://codesandbox.io/s/jovial-stallman-fs012?file=/src/index.js

Further things to do:

You are directly editing planet array in handleChange function. When user searches string you are removing items from state.planets. So when user removes search string, old planets will not be showing because of the removal.

You need to store planets in a immutable array.

After you did the search filter immutable array to create presentation array.

Display presentation array in render function.

Also i highly recommend to checkout the documentation for Passing Functions to Components:https://reactjs.org/docs/faq-functions.html


问:
snsdev-dev already exists in stack
Issue:
New amplify project created throws this error:

Error:
Resource Name: SNSRole (AWS::IAM::Role)
Event Type: create
Reason: snsdev-dev already exists in stack arn:aws:cloudformation:eu-west-1:

✖ An error occurred when pushing the resources to the cloud

Resource is not in the state stackUpdateComplete
An error occured during the push operation: Resource is not in the state stackUpdateComplete

Amplify project created as follows:

```<code># mkdir react-rds
# cd react-rds

# amplify init
? Enter a name for the project react-rds
? Enter a name for the environment dev
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using react

⠙ Initializing project in the cloud...
Your project has been successfully initialized and connected to the cloud!

# amplify add auth
 Do you want to use the default authentication and security configuration? Default configuration
 Warning: you will not be able to edit these selections.
 How do you want users to be able to sign in? Username
 Do you want to configure advanced settings? No, I am done.

Successfully added resource reactrds0xxxbxde locally

# amplify push
? Are you sure you want to continue? Yes
⠼ Updating resources in the cloud. This may take a few minutes...

CREATE_FAILED      SNSRole                                                         AWS::IAM::Role             Sun May 31 2020 16:35:24 GMT+1000 (Australian Eastern Standard Time) snsdev-dev already exists in stack arn:aws:cloudformation:eu-west-1:4711111:stack/amplify-react-amplified-dev-12110-authreactamplifiedc7111f-1TOaaaaBPI1/e9xxxxx0-9fxx-11ex-97xx6-0acxxxxxee0
CREATE_FAILED      amplify-react-rds-dev-163108-authreactrds011de-1PHaaaaaWIJ AWS::CloudFormation::Stack Sun May 31 2020 16:35:24 GMT+1000 (Australian Eastern Standard Time) The following resource(s) failed to create: [SNSRole].

✖ An error occurred when pushing the resources to the cloud

Resource is not in the state stackUpdateComplete
An error occured during the push operation: Resource is not in the state stackUpdateComplete
</code>```

Then the above error comes on the first push.

答:
The issue was with the hyphen in the project name.

Look at these two Github issues that deal with this issue:

https://github.com/aws-amplify/amplify-cli/issues/3879

https://github.com/aws-amplify/amplify-cli/issues/3687

I created another project without the hyphen to fix the issue.

Title: snsdev-dev already exists in stack

Body:
Issue:
New amplify project created throws this error:

Error:
Resource Name: SNSRole (AWS::IAM::Role)
Event Type: create
Reason: snsdev-dev already exists in stack arn:aws:cloudformation:eu-west-1:

✖ An error occurred when pushing the resources to the cloud

Resource is not in the state stackUpdateComplete
An error occured during the push operation: Resource is not in the state stackUpdateComplete

Amplify project created as follows:

# mkdir react-rds
# cd react-rds

# amplify init
? Enter a name for the project react-rds
? Enter a name for the environment dev
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using react

⠙ Initializing project in the cloud...
Your project has been successfully initialized and connected to the cloud!

# amplify add auth
 Do you want to use the default authentication and security configuration? Default configuration
 Warning: you will not be able to edit these selections.
 How do you want users to be able to sign in? Username
 Do you want to configure advanced settings? No, I am done.

Successfully added resource reactrds0xxxbxde locally

# amplify push
? Are you sure you want to continue? Yes
⠼ Updating resources in the cloud. This may take a few minutes...

CREATE_FAILED      SNSRole                                                         AWS::IAM::Role             Sun May 31 2020 16:35:24 GMT+1000 (Australian Eastern Standard Time) snsdev-dev already exists in stack arn:aws:cloudformation:eu-west-1:4711111:stack/amplify-react-amplified-dev-12110-authreactamplifiedc7111f-1TOaaaaBPI1/e9xxxxx0-9fxx-11ex-97xx6-0acxxxxxee0
CREATE_FAILED      amplify-react-rds-dev-163108-authreactrds011de-1PHaaaaaWIJ AWS::CloudFormation::Stack Sun May 31 2020 16:35:24 GMT+1000 (Australian Eastern Standard Time) The following resource(s) failed to create: [SNSRole].

✖ An error occurred when pushing the resources to the cloud

Resource is not in the state stackUpdateComplete
An error occured during the push operation: Resource is not in the state stackUpdateComplete

Then the above error comes on the first push.


问:
Mac OS replace multiline with one character using sed
I hope this is not duplicate, I read some questions, but I am still struggling to achieve this.

Let say i have this text:

```<code>{
  "root": {
    "2020-05": []
  }
}
{
  "root2": {
    "result": "error",
    "message": "You can't access this resource as it requires 'view' access for the website id = 206."
  }
}
</code>```

How would I get the following result:

```<code>{
  "root": {
    "2020-05": []
  },
  "root2": {
    "result": "error",
    "message": "You can't access this resource as it requires 'view' access for the website id = 206."
  }
}
</code>```

I need to replace

```<code>{
}
</code>```

with just this

```<code>,
</code>```

Or better I need to replace this

```<code>  }
}
{
</code>```

with just this:

```<code>  },
</code>```

What is the best way to achieve this using sed?

I am not sure about the regex part, I tried this /^{}$/ and this $}^${^.

Thanks

答:
jq can work but if you have the perl command you can also try:

perl -0777 -pe 's/}\n{/,/g' file.txt
```

See argument docs

-0777 to read the whole file

pe to evaluate what's in the quotes rather than a file, and loop it

Body:
I hope this is not duplicate, I read some questions, but I am still struggling to achieve this.

Let say i have this text:

{
  "root": {
    "2020-05": []
  }
}
{
  "root2": {
    "result": "error",
    "message": "You can't access this resource as it requires 'view' access for the website id = 206."
  }
}

How would I get the following result:

{
  "root": {
    "2020-05": []
  },
  "root2": {
    "result": "error",
    "message": "You can't access this resource as it requires 'view' access for the website id = 206."
  }
}

I need to replace

{
}

with just this

,

Or better I need to replace this

  }
}
{

with just this:

  },

What is the best way to achieve this using sed?

I am not sure about the regex part, I tried this /^{}$/ and this $}^${^.

Thanks

Body:
jq can work but if you have the perl command you can also try:

perl -0777 -pe 's/}\n{/,/g' file.txt

See argument docs

-0777 to read the whole file

pe to evaluate what's in the quotes rather than a file, and loop it


答:
Nevermind. I just needed to add scale_x_date(), like this:

```<code>ggplotly(plot + scale_x_date(date_labels = "%m-%Y"))
</code>```

Title: time series behaved weirdly with plot_ly

Body:
Data:

library(tidyverse)
library(lubridate)
library(plotly)

test <- tribble(
  ~Name, ~Date, ~Score, ~comp,
  "Ken" , "3-2-2020" , 5, "PC1",
    "Ken" , "3-2-2020" , 3, "PC1",
    "Ken" , "3-2-2020" , 4, "PC1",
    "Ken" , "3-2-2020" , 5, "PC1",
    "Ken" , "3-3-2020" , 5, "PC1",
    "Ken" , "3-3-2020" , 2, "PC1",
    "Ken" , "3-4-2020" , 5, "PC1",
    "Ken" , "3-5-2020" , 5, "PC1",
    "Ken" , "3-6-2020" , 4, "PC1",
    "Ken" , "3-2-2020" , 5, "PC2",
    "Ken" , "3-2-2020" , 3, "PC2",
    "Ken" , "3-2-2020" , 4, "PC2",
    "Ken" , "3-2-2020" , 5, "PC2",
    "Ken" , "3-3-2020" , 5, "PC2",
    "Ken" , "3-3-2020" , 2, "PC2",
    "Ken" , "3-4-2020" , 5, "PC2",
    "Ken" , "3-5-2020" , 5, "PC2",
    "Ken" , "3-6-2020" , 4, "PC2",
    "Ken" , "7-6-2020", 4, "PC3"
) %>%
  mutate(Date = lubridate::mdy(Date))

I would like to transform this to a faceted time series plot, like this:

plot <- test %>%
  ggplot(., aes(x=Date, y=Score)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  ylim(1,5.3) +
  theme_bw() +
  facet_wrap(. ~ comp)

plot

But when I use plotly, it looks like this.

ggplotly(plot)

What is the problem? The x-axis looks weird

Body:
Nevermind. I just needed to add scale_x_date(), like this:

ggplotly(plot + scale_x_date(date_labels = "%m-%Y"))


问:
Why this function acts like loop when it executed couple times
Why is this function acts like loop when it executed couple times did this counter stored in the add function or not

let counter = 0;

function add() {
  return counter++;
}

console.log(add());
console.log(add());
console.log(add());
console.log(add());
```
<p>if it increments I don't understand its difference from this while loop</p>
```let i = 0;
while(i <= 3){
  console.log(i)
  i++;
}
```

答:
The  counter, defined by let initially is in the global scope which is changed by your function.
Check out https://www.w3schools.com/js/js_let.asp for mor details!

Body:
Why is this function acts like loop when it executed couple times did this counter stored in the add function or not

let counter = 0;

function add() {
  return counter++;
}

console.log(add());
console.log(add());
console.log(add());
console.log(add());

if it increments I don't understand its difference from this while loop

let i = 0;
while(i <= 3){
  console.log(i)
  i++;
}


问:
Discord.js bot commands not working. How to solve?
I'm trying to create a bot with discord.js. It shows there are no errors, and goes online and runs perfectly. However, when I try to run a command, the bot doesn't say anything, not even an error message. My code is here:

const discord = require('discord.js');
var cheerio = require('cheerio');
var request = require('request');
const bot = new discord.Client();
const PREFIX = "//";

bot.on('ready', () => {
  console.log('CherryBot is online!');

})

bot.on("message", (message) => {
  if (message.author.equals(bot.user)) return;

  if (!message.content.startsWith(PREFIX)) return;

  var args = message.content.substring(PREFIX.length).split("");

  switch (args[0].toLowerCase()) {
    case "ping":

      message.channel.sendMessage("Pong!")
      break;

    case "cherry":
      image(message);

      break;
  }
});

function image(message) {

  var options = {
    url: "http://results.dogpile.com/serp?qc=images&q=" + "cherry fruit"
    , method: "GET",
    headers: {
      "Accept": "text/html",
      "User-Agent": "Chrome"
    }
  };

  request(options, function (error, response, responseBody) {
    if (error) {
      return;
    }

    $ = cheerio.load(responseBody);

    var links = $(".image a.link");

    var urls = new Array(links.length).fill(0).map((v, i) => links.eq(i).attr("href"));

    console.log(urls);

    if (!urls.length) {

      return;
    }

    // Send result
    message.channel.send(urls[Math.floor(Math.random() * urls.length)]);
  });
}
```

答:
you error is simple, in var args = ... you used split to split every character. To work you need to split just spaces. Just add a space in split function.

var args = message.content.substring(PREFIX.length).split(" ");
```

Also, message.channel.sendMessage doesn't work anymore, you need to use message.channel.send instead.

I did that changes and your bot works perfectly.

Body:
you error is simple, in var args = ... you used split to split every character. To work you need to split just spaces. Just add a space in split function.

var args = message.content.substring(PREFIX.length).split(" ");

Also, message.channel.sendMessage doesn't work anymore, you need to use message.channel.send instead.

I did that changes and your bot works perfectly.


问:
Understanding Frame Classes in Tkinter
I'm new to Python and trying to understand the code below.  This code should create 3 frame objects that can be rotated to the front to swap pages.

The APP class should create these 3 new objects.  I'm not sure that it is.

What I am trying to be is modify a label on the Dashboard class through a function in that class.
i.e. Dashboard.update()
Can someone please explain how the APP class is creating frame objects for the 3 windows.  I'm now sure that it is and I think I am trying to update text in the class and not a object of that class.

```<code>### Import libaries
import requests
import pyodbc
import tkinter as tk
from tkinter import *
from tkinter import messagebox, ttk

### Set global fonts
TITLE_FONT = ("Verdana", 12)

### Define the applicaiton class
class APP (Frame):

    ### Build the init function to create the container and windows
    def __init__ (self, master=None ):

        Frame.__init__(self, master)
        self.grid()

        # Set the application window title
        self.master.title("Playing Around with Classes")

        # set the size of the row height for the application
        self.master.rowconfigure(0, weight=1)
        self.master.rowconfigure(1, weight=35)
        self.master.rowconfigure(2, weight=1)
        self.master.rowconfigure(3, weight=1)

        #Row 0 - Title area
        label = tk.Label(master, text="Playing Around with Classes", font=TITLE_FONT)
        label.grid(row=0, columnspan=3, sticky="nsew")

        # Main presentation are
        Frame2 = Frame(master, bg="#263D42")
        Frame2.grid(row = 1, column = 0, rowspan = 1, columnspan = 3,  sticky = "nsew")

        # List of pages
        self.frames = {}

        # i think this loop defines the class objects
        for F in (NetworkMap,AuthorPage,Dashboard):

            frame = F(Frame2, self)
            self.frames[F] = frame
            frame.grid(row=0, column=1, sticky="nsew")

        self.show_frame(Dashboard)

    ### Define the show_frame function that will bring the selected fram to the front so it can be viewed
    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()

### Create a class for the Dashboard page.  This will also be the start page when the application starts
class Dashboard (tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self,parent, bg="#263D42")
        label = tk.Label(self, text="Text to change", font=TITLE_FONT, bg="#263D42", fg="white", pady = 20)
        label.grid(row=0, column=0, sticky="nsew")

    def update(self):
        self.allPapersLabel.config(text="Changed Text")

### Create a page to get the Author detasil
class AuthorPage (tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text="Get Author", font=TITLE_FONT)
        label.grid(row=0, column=0, sticky="nsew")

class NetworkMap (tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text="Network Map", font=TITLE_FONT)
        label.grid(row=0, column=0, sticky="nsew")

def changeText():
    Dashboard.update()

changeText()

root = tk.Tk()
root.geometry("600x800+100+100")
app = APP(master=root)
app.mainloop()
</code>```

答:
Can someone please explain how the APP class is creating frame objects for the 3 windows

The crux is here:

```<code>for F in (NetworkMap,AuthorPage,Dashboard):
    frame = F(Frame2, self)
    self.frames[F] = frame
    frame.grid(row=0, column=1, sticky="nsew")
</code>```

Keep in mind that NetworkMap, AuthorPage and Dashboard are classes. Classes are callables that function as a factory for new instances of the particular type.

So basically the for-loop makes F an alias (or label) for each of those classes and calls them in turn to instantiate an object.

Keep in mind that what we call "variables" in most languages are refered to as names in Python. From the language manual:

Names refer to objects. Names are introduced by name binding operations.

So F is nothing more than a handy label to refer to the three classes. The for-loop header binds the name to the classes.

BTW: This looks like a re-implementation of a ttk.Notebook. I would suggest to use that instead.

Edit

The frames are saved into the frames dictionary the App object. So in all of the methods of App instances you can access self.frames to get the individual frames.

The somewhat weird (to me at least) thing is that the class object of the frame is used as the key for selecting from the dictionary.

So using self.frames[AuthorPage] in methods of App should return the AuthorPage frame.

Title: Understanding Frame Classes in Tkinter

Body:
I'm new to Python and trying to understand the code below.  This code should create 3 frame objects that can be rotated to the front to swap pages.

The APP class should create these 3 new objects.  I'm not sure that it is.

What I am trying to be is modify a label on the Dashboard class through a function in that class.
i.e. Dashboard.update()
Can someone please explain how the APP class is creating frame objects for the 3 windows.  I'm now sure that it is and I think I am trying to update text in the class and not a object of that class.

### Import libaries
import requests
import pyodbc
import tkinter as tk
from tkinter import *
from tkinter import messagebox, ttk

### Set global fonts
TITLE_FONT = ("Verdana", 12)

### Define the applicaiton class
class APP (Frame):

    ### Build the init function to create the container and windows
    def __init__ (self, master=None ):

        Frame.__init__(self, master)
        self.grid()

        # Set the application window title
        self.master.title("Playing Around with Classes")

        # set the size of the row height for the application
        self.master.rowconfigure(0, weight=1)
        self.master.rowconfigure(1, weight=35)
        self.master.rowconfigure(2, weight=1)
        self.master.rowconfigure(3, weight=1)

        #Row 0 - Title area
        label = tk.Label(master, text="Playing Around with Classes", font=TITLE_FONT)
        label.grid(row=0, columnspan=3, sticky="nsew")

        # Main presentation are
        Frame2 = Frame(master, bg="#263D42")
        Frame2.grid(row = 1, column = 0, rowspan = 1, columnspan = 3,  sticky = "nsew")

        # List of pages
        self.frames = {}

        # i think this loop defines the class objects
        for F in (NetworkMap,AuthorPage,Dashboard):

            frame = F(Frame2, self)
            self.frames[F] = frame
            frame.grid(row=0, column=1, sticky="nsew")

        self.show_frame(Dashboard)

    ### Define the show_frame function that will bring the selected fram to the front so it can be viewed
    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()

### Create a class for the Dashboard page.  This will also be the start page when the application starts
class Dashboard (tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self,parent, bg="#263D42")
        label = tk.Label(self, text="Text to change", font=TITLE_FONT, bg="#263D42", fg="white", pady = 20)
        label.grid(row=0, column=0, sticky="nsew")

    def update(self):
        self.allPapersLabel.config(text="Changed Text")

### Create a page to get the Author detasil
class AuthorPage (tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text="Get Author", font=TITLE_FONT)
        label.grid(row=0, column=0, sticky="nsew")

class NetworkMap (tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text="Network Map", font=TITLE_FONT)
        label.grid(row=0, column=0, sticky="nsew")

def changeText():
    Dashboard.update()

changeText()

root = tk.Tk()
root.geometry("600x800+100+100")
app = APP(master=root)
app.mainloop()

Body:
Can someone please explain how the APP class is creating frame objects for the 3 windows

The crux is here:

for F in (NetworkMap,AuthorPage,Dashboard):
    frame = F(Frame2, self)
    self.frames[F] = frame
    frame.grid(row=0, column=1, sticky="nsew")

Keep in mind that NetworkMap, AuthorPage and Dashboard are classes. Classes are callables that function as a factory for new instances of the particular type.

So basically the for-loop makes F an alias (or label) for each of those classes and calls them in turn to instantiate an object.

Keep in mind that what we call "variables" in most languages are refered to as names in Python. From the language manual:

Names refer to objects. Names are introduced by name binding operations.

So F is nothing more than a handy label to refer to the three classes. The for-loop header binds the name to the classes.

BTW: This looks like a re-implementation of a ttk.Notebook. I would suggest to use that instead.

Edit

The frames are saved into the frames dictionary the App object. So in all of the methods of App instances you can access self.frames to get the individual frames.

The somewhat weird (to me at least) thing is that the class object of the frame is used as the key for selecting from the dictionary.

So using self.frames[AuthorPage] in methods of App should return the AuthorPage frame.


答:
You should bind handleChange method in constructor like :

this.handleChnage = this.handleChange.bind(this)

```<code>        or
</code>```

you should use arrow function

handleChange = (e) => {
}

Title: Searchfield to search for specific planets

Body:
You should bind handleChange method in constructor like :

this.handleChnage = this.handleChange.bind(this)

        or

you should use arrow function

handleChange = (e) => {
}


问:
How do I create a code that prints randomly picked letters until it can spell the word I want
What I want to with this code is to be able to randomly pick a letter from the list i've created until it spells out the word coffee. Here is what I have so far.

```<code>import random
def repeat():
    items = ["c", "o", "f", "e"]
    coffee_choice = random.choice(items)

items = ["c", "o", "f", "e"]

coffee_choice = random.choice (items)

print(coffee_choice)
</code>```

UPDATE: I've just realized how the things i said didn't make sense at all so i'll explain it better this time, thanks to those who provided working code unfortunately not what im after. If possible could you provide some explanation in each part of the code on how it works. (trying to learn it!)

Step 1: I need to be able to choose a random letter (done this)

Step 2: Choose letters util the word COFFEE can be spelled out.

Step 3: Display the letters that have been chosen and then state the amount of times/attempts were needed to get all of the letters.

答:
To build a six-letter string from letters randomly chosen from "c", "o", "f", "e", you'll want to make six random.choices, and then join them together to make a single string:

```<code>>>> "".join(random.choice("cofe") for _ in range(6))
'focooc'
</code>```

So now if you want to do that until it makes "coffee":

```<code>>>> attempts = 1
>>> while "coffee" != "".join(random.choice("cofe") for _ in range(6)):
...     attempts += 1
... else:
...     print(f"it took {attempts} attempts to make coffee!")
...
it took 9873 attempts to make coffee!
</code>```

Note that you can increase the odds of getting a particular letter (and decrease the number of tries) if you add more of them to the iterable you pass to random.choice:

```<code>>>>
>>> attempts = 1
>>> while "coffee" != "".join(random.choice("coffee") for _ in range(6)):
...     attempts += 1
... else:
...     print(f"it took {attempts} attempts to make coffee!")
...
it took 1282 attempts to make coffee!
</code>```

and greatly decrease the odds by adding more letters that you don't need:

```<code>>>> attempts = 1
>>> while "coffee" != "".join(random.choice("abcdefghijklmno") for _ in range(6)):
...     attempts += 1
... else:
...     print(f"it took {attempts} attempts to make coffee!")
...
it took 4683223 attempts to make coffee!
</code>```

Body:
What I want to with this code is to be able to randomly pick a letter from the list i've created until it spells out the word coffee. Here is what I have so far.

import random
def repeat():
    items = ["c", "o", "f", "e"]
    coffee_choice = random.choice(items)

items = ["c", "o", "f", "e"]

coffee_choice = random.choice (items)

print(coffee_choice)

UPDATE: I've just realized how the things i said didn't make sense at all so i'll explain it better this time, thanks to those who provided working code unfortunately not what im after. If possible could you provide some explanation in each part of the code on how it works. (trying to learn it!)

Step 1: I need to be able to choose a random letter (done this)

Step 2: Choose letters util the word COFFEE can be spelled out.

Step 3: Display the letters that have been chosen and then state the amount of times/attempts were needed to get all of the letters.

Body:
To build a six-letter string from letters randomly chosen from "c", "o", "f", "e", you'll want to make six random.choices, and then join them together to make a single string:

>>> "".join(random.choice("cofe") for _ in range(6))
'focooc'

So now if you want to do that until it makes "coffee":

>>> attempts = 1
>>> while "coffee" != "".join(random.choice("cofe") for _ in range(6)):
...     attempts += 1
... else:
...     print(f"it took {attempts} attempts to make coffee!")
...
it took 9873 attempts to make coffee!

Note that you can increase the odds of getting a particular letter (and decrease the number of tries) if you add more of them to the iterable you pass to random.choice:

>>>
>>> attempts = 1
>>> while "coffee" != "".join(random.choice("coffee") for _ in range(6)):
...     attempts += 1
... else:
...     print(f"it took {attempts} attempts to make coffee!")
...
it took 1282 attempts to make coffee!

and greatly decrease the odds by adding more letters that you don't need:

>>> attempts = 1
>>> while "coffee" != "".join(random.choice("abcdefghijklmno") for _ in range(6)):
...     attempts += 1
... else:
...     print(f"it took {attempts} attempts to make coffee!")
...
it took 4683223 attempts to make coffee!


问:
list of regular expressions
I'm looking for a concise list of all the regular expression syntax (sort of like a cheatsheet) and I found this tool: http://erik.eae.net/playground/regexp/regexp.html

in which if you click on the question mark on the top right corner it will display some sort of dictionary of regular expressions...

my question is....is this list comprehensive or is it missing something?

if anyone knows a better list, please let me know as well

答: How could it be comprehensive? There are many, many, more or less obscure regular expression engines out there, each with its own syntax. The ? isn't even the entire Java Pattern syntax, to name one.</p>

Title: list of regular expressions


答:
If I understand your question correctly, this is what you want (this can be shortened a bit but I've written it out explicitly for easy understanding):

```<code>import random

def spell_word(word, items):
  numOfLetters = len(word)
  attempt = ""

  for i in range(0, numOfLetters):
    attempt += random.choice(items)

  if attempt != word:
    print("Failed to spell {word}, spelled {attempt} instead".format(word=word, attempt=attempt))
    return False
  else:
    print("Spelled correctly!")
    return True

limit = 100000
items = ["c", "o", "f", "e"]
for i in range(0, limit):
  if spell_word("coffee", items):
    print("Took {} tries.".format(i))
    break
  else:
    pass # do something to the items list
</code>```

Edit: different code after further explanation from OP:

```<code>import random

def spell_word(word, items, attempts):
  """
  Tries to spell the given word using randomly picked letters from items
  """
  attempts = ""
  wordLen = len(word)

  for i in range(0, limit):
    attempts += random.choice(items)
    if len(attempts) >= wordLen and attempts[-wordLen:] == word:
      print("Spelled correctly after {} tries!".format(i+1))
      break

  print("All attempted letters ({} letters picked):".format(len(attempts)))
  print(attempts)

limit = 50000
items = ["c", "o", "f", "e"]
spell_word("coffee", items, limit)
</code>```

Title: How do I create a code that prints randomly picked letters until it can spell the word I want

Body:
If I understand your question correctly, this is what you want (this can be shortened a bit but I've written it out explicitly for easy understanding):

import random

def spell_word(word, items):
  numOfLetters = len(word)
  attempt = ""

  for i in range(0, numOfLetters):
    attempt += random.choice(items)

  if attempt != word:
    print("Failed to spell {word}, spelled {attempt} instead".format(word=word, attempt=attempt))
    return False
  else:
    print("Spelled correctly!")
    return True

limit = 100000
items = ["c", "o", "f", "e"]
for i in range(0, limit):
  if spell_word("coffee", items):
    print("Took {} tries.".format(i))
    break
  else:
    pass # do something to the items list

Edit: different code after further explanation from OP:

import random

def spell_word(word, items, attempts):
  """
  Tries to spell the given word using randomly picked letters from items
  """
  attempts = ""
  wordLen = len(word)

  for i in range(0, limit):
    attempts += random.choice(items)
    if len(attempts) >= wordLen and attempts[-wordLen:] == word:
      print("Spelled correctly after {} tries!".format(i+1))
      break

  print("All attempted letters ({} letters picked):".format(len(attempts)))
  print(attempts)

limit = 50000
items = ["c", "o", "f", "e"]
spell_word("coffee", items, limit)


答:
No, synchronized will not do this. More specifically synchronized on the instance level will not do this. Instead you will have to synchronize on the class level.

For example instead of having:

```<code>public synchronized method()
{
    //do stuff
}
</code>```

You will have to code as:

```<code>public void method()
{
    synchronized(this.getClass())
    {
        //do stuff
    }
}
</code>```

Title: Question about Java synchronized

Body:
The Java documentation says that "it is not possible for two invocations of synchronized methods on the same object to interleave".  What I need to know is whether synchronized will also prevent a synchronized method in two different instances of the same class from interleaving.

E.g. class Worker has method called process().  We have several instances of Worker running in their own threads.  We want to prevent more than one instance running the process() method simultaneously.  Will synchronized do this?

Thanks.

Body:
No, synchronized will not do this. More specifically synchronized on the instance level will not do this. Instead you will have to synchronize on the class level.

For example instead of having:

public synchronized method()
{
    //do stuff
}

You will have to code as:

public void method()
{
    synchronized(this.getClass())
    {
        //do stuff
    }
}


问:
boto3: file content length is right but the body is empty
I have a file of size 4.4MB in an S3 bucket and when I try to download it through boto3, the content length I see in the object description is right but the body of the object is empty. Any ideas why that is happening?</p>

```<code>s3 = session.client('s3')
obj = s3.get_object(Bucket=bucket, Key=key)
obj['ResponseMetadata']['HTTPHeaders']['content-length'] ## this returns 4598667
obj['ContentLength'] ## this returns 4598667 as well
obj['Body'].read().decode('utf-8') ## this returns ''
</code>```

答:
So as mentioned in comments, The key is to use csv.reader() and obj['Body'].read().decode('utf-8').splitlines() ( The full code can be found here.)

Why does not streaming handle this already?

About csv.reader (From the docs):

Return a reader object which will iterate over lines in the given
  csvfile. csvfile can be any object which supports the iterator
  protocol and returns a string each time its next() method is
  called — file objects and list objects are both suitable. If csvfile
  is a file object, it should be opened with newline=''.

Each row read from the csv file is returned as a list of strings. No
  automatic data type conversion is performed unless the
  QUOTE_NONNUMERIC format option is specified

With that been said, we must iterate over the return data from csv.reader in order to see the actual lines.

Code snippet example:

import csv
with open('eggs.csv', newline='') as csvfile:
     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
     for row in spamreader:
         print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
```

Body:
I have a file of size 4.4MB in an S3 bucket and when I try to download it through boto3, the content length I see in the object description is right but the body of the object is empty. Any ideas why that is happening?

s3 = session.client('s3')
obj = s3.get_object(Bucket=bucket, Key=key)
obj['ResponseMetadata']['HTTPHeaders']['content-length'] ## this returns 4598667
obj['ContentLength'] ## this returns 4598667 as well
obj['Body'].read().decode('utf-8') ## this returns ''


问:
Python Select first word in a string without using methods
I have a homework assignment where I have to select the first word in a string. Normally I would do this:

```<code>s = "Hello World"
words = s.split()
first_word = words[0]
print(first_word)
</code>```

For this assignment I cannot use methods or loops to answer the question. Any ideas?

答:
This recursion is very similar to MacieK's:

(edited to allow non space word delimiters)

```<code>def hello(s):

    delims = ' ,-'

    if s == '' or s[:1] in delims: return

    print(s[:1], end='')

    hello(s[1:])

hello('Hello, World')
</code>```

Body:
I have a homework assignment where I have to select the first word in a string. Normally I would do this:

s = "Hello World"
words = s.split()
first_word = words[0]
print(first_word)

For this assignment I cannot use methods or loops to answer the question. Any ideas?

Body:
This recursion is very similar to MacieK's:

(edited to allow non space word delimiters)

def hello(s):

    delims = ' ,-'

    if s == '' or s[:1] in delims: return

    print(s[:1], end='')

    hello(s[1:])

hello('Hello, World')


问:
Exclude values equal to zero in regression line and R^2 on ggplot
Imagine I had this data frame:

```<code>exampleDF <- data.frame(
   'Site' = c('s1', 's1', 's2', 's2', 's3', 's4', 's5', 's5', 's6', 's7'),
   'xCol' = c(0, 48.75, 43.78, 48.37, 46.58, 41.22, 34.48, 39.84, 46.37, 0),
   'yCol' = c(43.52, 0, 42.16, 40.85, 43.48, 0, 35.12, 39.14, 47.65, 41.18)
    )
</code>```

Resulting table (or data frame)

And I have the following code for making a plot with the r-squared and the regression line on top of the dots:

```<code>library(ggplot2)
library(ggpmisc)

plot <- ggplot(exampleDF, aes(x = xCol, y = yCol)) +
  geom_smooth(method = lm, se=FALSE, color="black", formula = y ~ x) +
  stat_poly_eq(formula = y ~ x, aes(label = paste(..rr.label..)), parse = TRUE) +
  ggtitle("Dem Plots") +
  xlab("X-Axis label") + ylab("Y-Axis label") +
  geom_point()

plot
</code>```

Resulting Plot

But if you can see the image, I include in the plot values that are equal to zero, which is what I want in the plot. However, I only want the regression line and the r-squared calculations to exclude when their values are equal to zero (or say, include only when values are greater than zero)

I tried manipulating the formula on both of these lines but I get many errors. Is there a particular syntaxis I should care when touching y ~ x ?

Thanks

答:
The easiest approach, I think, would be to split the data and plot as separate layers.

```<code>library(ggplot2)
library(ggpmisc)
library(dplyr)

exampleDF <- exampleDF %>%
  group_split(zeroes = xCol == 0 | yCol == 0)

ggplot(exampleDF[[1]], aes(x = xCol, y = yCol)) +
  geom_smooth(method = lm, se=FALSE, color="black", formula = y ~ x, fullrange = TRUE) +
  stat_poly_eq(formula = y ~ x, aes(label = ..rr.label..), parse = TRUE) +
  geom_point() +
  geom_point(data = exampleDF[[2]], aes(x = xCol, y = yCol), color = "red") +
  ggtitle("Dem Plots") +
  xlab("X-Axis label") +
  ylab("Y-Axis label")
</code>```

Body:
Imagine I had this data frame:

exampleDF <- data.frame(
   'Site' = c('s1', 's1', 's2', 's2', 's3', 's4', 's5', 's5', 's6', 's7'),
   'xCol' = c(0, 48.75, 43.78, 48.37, 46.58, 41.22, 34.48, 39.84, 46.37, 0),
   'yCol' = c(43.52, 0, 42.16, 40.85, 43.48, 0, 35.12, 39.14, 47.65, 41.18)
    )

Resulting table (or data frame)

And I have the following code for making a plot with the r-squared and the regression line on top of the dots:

library(ggplot2)
library(ggpmisc)

plot <- ggplot(exampleDF, aes(x = xCol, y = yCol)) +
  geom_smooth(method = lm, se=FALSE, color="black", formula = y ~ x) +
  stat_poly_eq(formula = y ~ x, aes(label = paste(..rr.label..)), parse = TRUE) +
  ggtitle("Dem Plots") +
  xlab("X-Axis label") + ylab("Y-Axis label") +
  geom_point()

plot

Resulting Plot

But if you can see the image, I include in the plot values that are equal to zero, which is what I want in the plot. However, I only want the regression line and the r-squared calculations to exclude when their values are equal to zero (or say, include only when values are greater than zero)

I tried manipulating the formula on both of these lines but I get many errors. Is there a particular syntaxis I should care when touching y ~ x ?

Thanks

Body:
The easiest approach, I think, would be to split the data and plot as separate layers.

library(ggplot2)
library(ggpmisc)
library(dplyr)

exampleDF <- exampleDF %>%
  group_split(zeroes = xCol == 0 | yCol == 0)

ggplot(exampleDF[[1]], aes(x = xCol, y = yCol)) +
  geom_smooth(method = lm, se=FALSE, color="black", formula = y ~ x, fullrange = TRUE) +
  stat_poly_eq(formula = y ~ x, aes(label = ..rr.label..), parse = TRUE) +
  geom_point() +
  geom_point(data = exampleDF[[2]], aes(x = xCol, y = yCol), color = "red") +
  ggtitle("Dem Plots") +
  xlab("X-Axis label") +
  ylab("Y-Axis label")


问:
(React) Selecing different dropdown values does not change anything
I have a dropdown menu, and selecting different values does not change anything. Previously, it did change just fine. Here is my code:

context.js:

```<code>import React, { useState, useEffect } from 'react'
import items from './data'

const RoomContext = React.createContext()

const RoomProvider = ({ children }) => {
    const [state, setState] = useState({
        rooms: [],
        sortedRooms: [],
        featuredRooms: [],
        loading: true,
        type: 'all',
        capacity: 1,
        price: 0,
        minPrice: 0,
        maxPrice: 0,
        minSize: 0,
        maxSize: 0,
        breakfast: false,
        pets: false
    })

    const formatData = items => {
        let tempItems = items.map(item => {
            let id = item.sys.id
            let images = item.fields.images.map(image => image.fields.file.url)
            let room = { ...item.fields, images, id }
            return room
        })
        return tempItems
    }

    const getRoom = slug => {
        let tempRooms = [...state.rooms]
        const room = tempRooms.find(room => room.slug === slug)
        return room
    }

    useEffect(() => {
        let rooms = formatData(items)
        let featuredRoomsTemp = state.rooms.filter(room => room.featured)
        let maxPrice = Math.max(...state.rooms.map(item => item.price))
        let maxSize = Math.max(...state.rooms.map(item => item.size))

        setState({
            ...state,
            rooms,
            featuredRooms: featuredRoomsTemp,
            sortedRooms: rooms,
            loading: false,
            price: maxPrice,
            maxPrice,
            maxSize
        })
    }, [])

      const handleChange = e => {
        const target = e.target
        const value = e.type === 'checkbox' ? target.checked : target.value
        const name = e.target.name

        setState({
            ...state,
            [name]: value
        })
        filterRooms()
    }

    const filterRooms = () => {
        console.log('reached')
        let { rooms, type, capacity, price, minSize, maxSize, breakfast, pets } = state

        let tempRooms = [...rooms]
        if (type !== 'all') {
            // console.log('NOT ALL')
            tempRooms = tempRooms.filter(room => room.type === type)
        }
        console.log('temprooms:' ,tempRooms)

        //ONLY AFTER ADDING THE BELOW SETSTATE,  AM I UNABLE TO CHANGE THE DROPDOWN VALUES. IF I REMOVE THE BELOW, I CAN CHANGE IT JUST FINE. Why would a setState make me unable to change the values?
        setState({
            ...state,
            sortedRooms: tempRooms
        })
    }

    return (
        <RoomContext.Provider value={{
            ...state,
            getRoom,
            handleChange
        }}>
            {children}
        </RoomContext.Provider>
    )
}

const RoomConsumer = RoomContext.Consumer

export function withRoomConsumer(Component) {
    return function ConsumerWrapper(props) {
        return <RoomConsumer>
            {value => <Component {...props} context={value} />}
        </RoomConsumer>
    }
}

export { RoomProvider, RoomConsumer, RoomContext }

</code>```

RoomsFilter.js

```<code>import React, { useContext } from 'react'
import { RoomContext } from '../context'
import Title from './Title'

const getUnique = (items, value) => {
    return [...new Set(items.map(item => item[value]))]
}

const RoomsFilter = ({ rooms }) => {
    const context = useContext(RoomContext)

    const { handleChange, type, capacity, price, minPrice, maxPrice, minSize, maxSize, breakfast, pets } = context

    let types = getUnique(rooms, 'type')
    types = ['all', ...types]

    types = types.map((item, i) => {
        return (
            <option value={item} key={i}>{item}</option>
        )
    })

    return (
        <section className='filter-container'>
            <Title title='Search rooms' />
            <form className='filter-form'>
                {/* select type */}
                <div className='form-group'>
                    <label htmlFor='type'>Room type</label>
                    <select name='type' id='type' value={type} className='form-control' onChange={handleChange}>
                        {types}
                    </select>
                </div>
                {/* end select type */}
            </form>
        </section>
    )
}

export default RoomsFilter
</code>```

==================================================================

As you can see, it is only when I added

```<code>setState({
            ...state,
            sortedRooms: tempRooms
        })
</code>```

in filterRooms (in context.js) that I am no longer able to change the dropdown value. Why would adding setState do this?

Please help, and thank you for reading!

===============UPDATE=====================

RoomsContainer is the one that contains the Dropdown menu(RoomsFilter) and the list of rooms below that dropdown menu(RoomsList).

RoomsFilter is the dropdown menu component

RoomsList is the component whose job is to render the rooms

Rooms Container:

```<code>import React from 'react'
import RoomsFilter from './RoomsFilter'
import RoomsList from './RoomsList'
import { withRoomConsumer } from '../context'
import Loading from './Loading'

function RoomContainer({ context }) {
const { loading, sortedRooms, rooms } = context
console.log(context)
if (loading) {
return <Loading />
}

return (
<div>
<RoomsFilter rooms={rooms} />
<RoomsList rooms={sortedRooms} />
</div>
)
}

export default withRoomConsumer(RoomContainer)
</code>```

RoomsFilter:

```<code>import React, { useContext } from 'react'
import { RoomContext } from '../context'
import Title from './Title'

const getUnique = (items, value) => {
return [...new Set(items.map(item => item[value]))]
}

const RoomsFilter = ({ rooms }) => {
const context = useContext(RoomContext)

const { handleChange, type, capacity, price, minPrice, maxPrice, minSize, maxSize, breakfast, pets } = context

let types = getUnique(rooms, 'type')
types = ['all', ...types]

types = types.map((item, i) => {
return (
<option value={item} key={i}>{item}</option>
)
})

return (
<section className='filter-container'>
<Title title='Search rooms' />
<form className='filter-form'>
{/* select type */}
<div className='form-group'>
<label htmlFor='type'>Room type</label>
<select name='type' id='type' value={type} className='form-control' onChange={handleChange}>
{types}
</select>
</div>
{/* end select type */}
</form>
</section>
)
}

export default RoomsFilter
</code>```

RoomsList

```<code>import React from 'react'
import Room from './Room'

const RoomsList = ({ rooms }) => {
console.log(rooms)
if (rooms.length === 0) {
return (
<div className='empty-search'>
<h3>Unfortunately no rooms match your search criteria</h3>
</div>
)
}

return (
<section className='roomslist'>
<div className='roomslist-center'>
{rooms.map(item => {
return <Room key={item.id} room={item} />
})}
</div>
</section>
)
}

export default RoomsList
</code>```

答:
You are not using the setState correctly .. it should be used like this instead

setState(prevState => ({...prevState , sortedRooms: tempRooms}))

Body:
I have a dropdown menu, and selecting different values does not change anything. Previously, it did change just fine. Here is my code:

context.js:

import React, { useState, useEffect } from 'react'
import items from './data'

const RoomContext = React.createContext()

const RoomProvider = ({ children }) => {
    const [state, setState] = useState({
        rooms: [],
        sortedRooms: [],
        featuredRooms: [],
        loading: true,
        type: 'all',
        capacity: 1,
        price: 0,
        minPrice: 0,
        maxPrice: 0,
        minSize: 0,
        maxSize: 0,
        breakfast: false,
        pets: false
    })

    const formatData = items => {
        let tempItems = items.map(item => {
            let id = item.sys.id
            let images = item.fields.images.map(image => image.fields.file.url)
            let room = { ...item.fields, images, id }
            return room
        })
        return tempItems
    }

    const getRoom = slug => {
        let tempRooms = [...state.rooms]
        const room = tempRooms.find(room => room.slug === slug)
        return room
    }

    useEffect(() => {
        let rooms = formatData(items)
        let featuredRoomsTemp = state.rooms.filter(room => room.featured)
        let maxPrice = Math.max(...state.rooms.map(item => item.price))
        let maxSize = Math.max(...state.rooms.map(item => item.size))

        setState({
            ...state,
            rooms,
            featuredRooms: featuredRoomsTemp,
            sortedRooms: rooms,
            loading: false,
            price: maxPrice,
            maxPrice,
            maxSize
        })
    }, [])

      const handleChange = e => {
        const target = e.target
        const value = e.type === 'checkbox' ? target.checked : target.value
        const name = e.target.name

        setState({
            ...state,
            [name]: value
        })
        filterRooms()
    }

    const filterRooms = () => {
        console.log('reached')
        let { rooms, type, capacity, price, minSize, maxSize, breakfast, pets } = state

        let tempRooms = [...rooms]
        if (type !== 'all') {
            // console.log('NOT ALL')
            tempRooms = tempRooms.filter(room => room.type === type)
        }
        console.log('temprooms:' ,tempRooms)

        //ONLY AFTER ADDING THE BELOW SETSTATE,  AM I UNABLE TO CHANGE THE DROPDOWN VALUES. IF I REMOVE THE BELOW, I CAN CHANGE IT JUST FINE. Why would a setState make me unable to change the values?
        setState({
            ...state,
            sortedRooms: tempRooms
        })
    }

    return (
        <RoomContext.Provider value={{
            ...state,
            getRoom,
            handleChange
        }}>
            {children}
        </RoomContext.Provider>
    )
}

const RoomConsumer = RoomContext.Consumer

export function withRoomConsumer(Component) {
    return function ConsumerWrapper(props) {
        return <RoomConsumer>
            {value => <Component {...props} context={value} />}
        </RoomConsumer>
    }
}

export { RoomProvider, RoomConsumer, RoomContext }

RoomsFilter.js

import React, { useContext } from 'react'
import { RoomContext } from '../context'
import Title from './Title'

const getUnique = (items, value) => {
    return [...new Set(items.map(item => item[value]))]
}

const RoomsFilter = ({ rooms }) => {
    const context = useContext(RoomContext)

    const { handleChange, type, capacity, price, minPrice, maxPrice, minSize, maxSize, breakfast, pets } = context

    let types = getUnique(rooms, 'type')
    types = ['all', ...types]

    types = types.map((item, i) => {
        return (
            <option value={item} key={i}>{item}</option>
        )
    })

    return (

            <Title title='Search rooms' />
            <form className='filter-form'>
                {/* select type */}

                    Room type
                    <select name='type' id='type' value={type} className='form-control' onChange={handleChange}>
                        {types}
                    </select>

                {/* end select type */}
            </form>

    )
}

export default RoomsFilter

==================================================================

As you can see, it is only when I added

setState({
            ...state,
            sortedRooms: tempRooms
        })

in filterRooms (in context.js) that I am no longer able to change the dropdown value. Why would adding setState do this?

Please help, and thank you for reading!

===============UPDATE=====================

RoomsContainer is the one that contains the Dropdown menu(RoomsFilter) and the list of rooms below that dropdown menu(RoomsList).

RoomsFilter is the dropdown menu component

RoomsList is the component whose job is to render the rooms

Rooms Container:

import React from 'react'
import RoomsFilter from './RoomsFilter'
import RoomsList from './RoomsList'
import { withRoomConsumer } from '../context'
import Loading from './Loading'

function RoomContainer({ context }) {
const { loading, sortedRooms, rooms } = context
console.log(context)
if (loading) {
return <Loading />
}

return (

<RoomsFilter rooms={rooms} />
<RoomsList rooms={sortedRooms} />

)
}

export default withRoomConsumer(RoomContainer)

RoomsFilter:

import React, { useContext } from 'react'
import { RoomContext } from '../context'
import Title from './Title'

const getUnique = (items, value) => {
return [...new Set(items.map(item => item[value]))]
}

const RoomsFilter = ({ rooms }) => {
const context = useContext(RoomContext)

const { handleChange, type, capacity, price, minPrice, maxPrice, minSize, maxSize, breakfast, pets } = context

let types = getUnique(rooms, 'type')
types = ['all', ...types]

types = types.map((item, i) => {
return (
<option value={item} key={i}>{item}</option>
)
})

return (

<Title title='Search rooms' />
<form className='filter-form'>
{/* select type */}

Room type
<select name='type' id='type' value={type} className='form-control' onChange={handleChange}>
{types}
</select>

{/* end select type */}
</form>

)
}

export default RoomsFilter

RoomsList

import React from 'react'
import Room from './Room'

const RoomsList = ({ rooms }) => {
console.log(rooms)
if (rooms.length === 0) {
return (

Unfortunately no rooms match your search criteria

)
}

return (

{rooms.map(item => {
return <Room key={item.id} room={item} />
})}

)
}

export default RoomsList


问:
How do I fix this intelliJ issue?
In trying to change the intelliJ font from 13 to 12, I accident plugged in 1312, and instead of giving an error, IntelliJ actually made the font 1312 and it's freezing. I was not able to open preferences to change the font to 12. I deleted the application and re-downloaded it, still having problems. its still freezing and not even letting me access the preferences to change the font, I also thought the factory setting would be in place since I am redownloading it. not sure what to do...I have a project due tomorrow so im stressed. </p>

答:
I'm not sure which OS you're running, so I can't provide super-specific guidelines here. But, if you can find Intellij's editor.xml file, it will contain a section like this:

```<code><component name="DefaultFont">
  <option name="FONT_SIZE" value="1312" />
  <option name="FONT_FAMILY" value="Monaco" />
</component>
</code>```

and all you should need to do is change that 1312 to 12.

Here are some tips where you may find that file: https://intellij-support.jetbrains.com/hc/en-us/community/posts/360001219679-Where-does-IntelliJ-IDEA-store-the-editor-font-size-

If you're using Settings Repository to store settings elsewhere, try editing that source instead.

Title: How do I fix this intelliJ issue?

Body:
I'm not sure which OS you're running, so I can't provide super-specific guidelines here. But, if you can find Intellij's editor.xml file, it will contain a section like this:

<component name="DefaultFont">
  <option name="FONT_SIZE" value="1312" />
  <option name="FONT_FAMILY" value="Monaco" />
</component>

and all you should need to do is change that 1312 to 12.

Here are some tips where you may find that file: https://intellij-support.jetbrains.com/hc/en-us/community/posts/360001219679-Where-does-IntelliJ-IDEA-store-the-editor-font-size-

If you're using Settings Repository to store settings elsewhere, try editing that source instead.


问:
Is my Sudoku algorithm considered an "expert system"?
I wrote a code which has all the rules of Sudoku written into it (one occurence of a digit per column, line, and square). The code takes an input (unfilled sudoku grid), and returns a solution by translating logical clauses into DIMACS format and using a SAT solver.

Given that the algorithm respects rules, takes in data, and uses that data to form conclusion based on implications (eg if there is a 1 in the first cell, there cannot be a 1 in the second cell), is this code considered an "expert system"? Thank you.

答:
In the 80's, I had written a clone of the Emycin expert system engine. One important characteristic was the ability for the user to ask WHY the expert system got some conclusion. The system could reply (in an almost natural language) that it applied such and such rules to get to the conclusion.

With this kind of system, the knowledge is modeled and implemented (by a cognitician engineer) as an explicit set of rules. These rules are objects known by the engine. The engine can trigger the rules (forward or backward or maybe using metarules...) and can log the triggered rules and thus explain its conclusions.

(this is my sense for expert systems).


问:
textfield value changing detect in php
```<code> <input name="aa" type="text" id="aa" value="please enter your name" size="22"            maxlength="60" />
 <input name="aab" type="text" id="aab" value="please enter your email" size="22"            maxlength="60" />
</code>```

i have a textfield and it's value is "please enter your name"(likewise i have many fields.i want to add the value to the database only if the value is changed.(if user entered a name)

i used php isset function and it does not work properly.
 how to detect that in php?

答:
If you have an array with previous values you can easily compare all field values against the previous ones you had, and if any of them are different, then update.

UPDATE:
Sorry didn't understand your question at first. As it was mantioned in other answer you better check it in front end and obly after work it through you php code.

Title: textfield value changing detect in php

Body:
 <input name="aa" type="text" id="aa" value="please enter your name" size="22"            maxlength="60" />
 <input name="aab" type="text" id="aab" value="please enter your email" size="22"            maxlength="60" />

i have a textfield and it's value is "please enter your name"(likewise i have many fields.i want to add the value to the database only if the value is changed.(if user entered a name)

i used php isset function and it does not work properly.
 how to detect that in php?


问:
No such file or directory running Python in VS Code with WSL
I'm using VS Code with WSL on my PC, and whenever I try to run a Python file in VS Code, it gives me an error that no such directory or file is found.

I've set WSL as my default shell and the issue, of course, is that VS Code is feeding in the Windows-based path to the python script, without the /mnt/C/... that's needed when using WSL. Is there any way for me to set up VS Code so that I can automatically have VS Code feed in the right, WSL-based file paths (i.e., including the /mnt/C/...)?

Secondly, it also seems that when using the WSL terminal in VS Code, it's using Python 2.7. Since I've never installed Python 2.7 on my PC, I'm assuming it comes with the Linux distro I'm using. Is it also possible to set up VS Code so that even when using the WSL terminal, the python installation that's used is the one I've installed on Windows (which is actually part of an Anaconda distribution)?

答:
You need to make sure to use the Remote - WSL extension so that VS Code treats your environment as Linux instead of as Windows.

As for reusing your Windows install of Python under WSL, I wouldn't try that as Python is compiled for a specific OS and thus makes assumptions that will break under another OS.


问:
Getting error while installing conda-accelerate
I have been trying to install conda-accelerate to use my GPU's for machine learning algorithm however I am getting following error while installing from anaconda prompt:</p>

```<code>(base) C:\Users\Ege>conda install accelerate
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from current channels:

  - accelerate

Current channels:

  - https://repo.anaconda.com/pkgs/main/win-64
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/r/win-64
  - https://repo.anaconda.com/pkgs/r/noarch
  - https://repo.anaconda.com/pkgs/msys2/win-64
  - https://repo.anaconda.com/pkgs/msys2/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.
</code>```

答: See PyOpenGL-accelerate maybe help you.</p>

Body:
I have been trying to install conda-accelerate to use my GPU's for machine learning algorithm however I am getting following error while installing from anaconda prompt:

(base) C:\Users\Ege>conda install accelerate
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from current channels:

  - accelerate

Current channels:

  - https://repo.anaconda.com/pkgs/main/win-64
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/r/win-64
  - https://repo.anaconda.com/pkgs/r/noarch
  - https://repo.anaconda.com/pkgs/msys2/win-64
  - https://repo.anaconda.com/pkgs/msys2/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.

Body: See PyOpenGL-accelerate maybe help you.


问:
Mysql UNION way to differ from which table result row is
Lets say I have below query.

```<code>SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
</code>```

Lest say there is one same city NY in both tables witch will give me:

```<code>| City     |
| -------- |
| NY       |
| NY       |
</code>```

I am fetching this in a HTML table, is there a way to differ from witch MySQL table result row is from, other then making another column in tables itself, for example column type.

Maybe is possible to append something to result set itself in query?

答:
Add an extra column containing a literal value depending on which subquery it is.</p>

```<code>SELECT 'Customers' AS type, City
FROM Customers
UNION
SELECT 'Suppliers' AS type, City
FROM Suppliers
ORDER BY City, type
</code>```

Body:
Lets say I have below query.

SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

Lest say there is one same city NY in both tables witch will give me:

| City     |
| -------- |
| NY       |
| NY       |

I am fetching this in a HTML table, is there a way to differ from witch MySQL table result row is from, other then making another column in tables itself, for example column type.

Maybe is possible to append something to result set itself in query?

Body:
Add an extra column containing a literal value depending on which subquery it is.

SELECT 'Customers' AS type, City
FROM Customers
UNION
SELECT 'Suppliers' AS type, City
FROM Suppliers
ORDER BY City, type


答:
you can add column in your query like following.</p>

```<code>SELECT city, 'c' as type FROM Customers
UNION
SELECT city, 's' as type FROM Suppliers
ORDER BY city, type;
</code>```

Title: Mysql UNION way to differ from which table result row is

Body:
you can add column in your query like following.

SELECT city, 'c' as type FROM Customers
UNION
SELECT city, 's' as type FROM Suppliers
ORDER BY city, type;


问:
How do I open a view controller from the app delegate?
I want to open the "Menu View Controller", when a local notification is opened from the Notification Center. My problem is that I do not know how I can open a view controller from the AppDelegate. All solutions I found did not work, because it were for older Xcode versions before  the SceneDelegate was introduced. This is the function in the AppDelegate where I want to call the view controller.

```<code>func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // missing code to open menu view controller

        completionHandler()

    }
</code>```

I use a tab bar controller to navigate between some view controllers. I am not sure if that makes a difference.
Here is how the important part of my storyboard looks.

I hope you can help me. Thank you!

答:
You have 2 possible ways of doing this:

1. Instantiate your tab bar controller via storyboard.

Go to your storyboard and set a storyboard ID for your tab bar controller inside the identity inspector.

Once you go that, you can instantiate your view controller like this:

```<code>let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
if let tabController = storyboard.instantiateViewController(withIdentifier: "tabControllerID") as? UITabController {
    tabController.selectedIndex = index
}
</code>```

Or, you can access scene delegate from your AppDelegate and use window -> rootViewController to get access to your tabController:

```<code>    let scene = UIApplication.shared.connectedScenes.first
    if let sceneDelegate = scene?.delegate as? SceneDelegate {
        if let tabController = sceneDelegate.window?.rootViewController as? UITabBarController {
              tabController.selectedIndex = index
        }

    }
</code>```

Body:
I want to open the "Menu View Controller", when a local notification is opened from the Notification Center. My problem is that I do not know how I can open a view controller from the AppDelegate. All solutions I found did not work, because it were for older Xcode versions before  the SceneDelegate was introduced. This is the function in the AppDelegate where I want to call the view controller.

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // missing code to open menu view controller

        completionHandler()

    }

I use a tab bar controller to navigate between some view controllers. I am not sure if that makes a difference.
Here is how the important part of my storyboard looks.

I hope you can help me. Thank you!

Body:
You have 2 possible ways of doing this:

1. Instantiate your tab bar controller via storyboard.

Go to your storyboard and set a storyboard ID for your tab bar controller inside the identity inspector.

Once you go that, you can instantiate your view controller like this:

let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
if let tabController = storyboard.instantiateViewController(withIdentifier: "tabControllerID") as? UITabController {
    tabController.selectedIndex = index
}

Or, you can access scene delegate from your AppDelegate and use window -> rootViewController to get access to your tabController:

    let scene = UIApplication.shared.connectedScenes.first
    if let sceneDelegate = scene?.delegate as? SceneDelegate {
        if let tabController = sceneDelegate.window?.rootViewController as? UITabBarController {
              tabController.selectedIndex = index
        }

    }


问:
Firebase functions: http function unable to read body or headers
I have a simple function on my front-end which calls a firebase function on the back-end. Although the request and the API logic are very simple, the call always fails, because the firebase function is unable to detect either the body or the appropriate headers of the request.

Here is the front-end code:

async function updateArtwork(
  artworkId: string,
  title: string,
  medium: string,
  description?: string,
  price?: number,
  printPrice?: number
): Promise<string> {
  try {
    const res = await fetch(`${config.apiUrl}updateArtwork`, {
      method: 'POST',
      body: JSON.stringify({
        artworkId,
        title,
        description,
        price,
        printPrice,
        medium,
      }),
      headers: new Headers({ 'Content-Type': 'application/json' }),
    });
    if (res) {
      return res.json();
    } else {
      throw new Error('Could not save changes to this artwork');
    }
  } catch (err) {
    throw new Error('Could not save changes to this artwork');
  }
}
```

<p>Here's the firebase function:</p>

<pre class="lang-js prettyprint-override"><code>export const updateArtwork = functions.https.onRequest(
  async (request, response) => {
    doChecks(request);
    const {
      artworkId,
      title,
      description,
      price,
      printPrice,
      medium,
    } = request.body;

    try {
      await db.collection('artworks').doc(artworkId).update({
        title,
        description,
        price,
        printPrice,
        medium,
      });
      return cors(request, response, () => {
        return response
          .status(200)
          .json('Successfully saved changes to artist');
      });
    } catch (error) {
      return response.status(500);
    }
  }
);
</code>```

The function doChecks() just logs various things about the request to the console, including the headers and the body. Bafflingly, according to these logs request.body is {}, even though when I check the dev tools network tab, the body is populated. Similarly, the logs tell me that there is no content-type header on the request, while dev tools tells me the content-type is application/json, which is as expected.

In addition, the above call in the front-end makes two API calls, as opposed to the expected one. I know it does this because I did the following:

set a breakpoint on the const res = await fetch... line

hit that breakpoint and checked the dev tools network tab to confirm that no requests have yet been made

clicked "step over" in dev tools to step to the next line (if (res)...)

checked the network tab and saw two POST calls to the same endpoint

What makes this even more strange is that none of the above code has changed recently. It's possible that recent environment changes (upgrading npm packages, etc.) have somehow messed things up, but it's unclear what effect they would have.

Any help on this would be greatly appreciated!

EDIT

Here is more detail on the doChecks() function mentioned above. Here is the function:

const doChecks = (request: any) => {
  console.log('request.body:');
  console.log(request.body);
  console.log('request.headers:');
  console.log(request.headers);
  console.log(`content type is ${request.headers['content-type']}`);
};
```

<p>For the above call, here is what is logged:</p>

<pre class="lang-sh prettyprint-override"><code>>  request.body:
>  {}
>  request.headers:
>  {
>    host: 'localhost:5001',
>    connection: 'keep-alive',
>    accept: '*/*',
>    'access-control-request-method': 'POST',
>    'access-control-request-headers': 'content-type,pragma',
>    origin: 'http://localhost:3001',
>    'sec-fetch-mode': 'cors',
>    'sec-fetch-site': 'same-site',
>    'sec-fetch-dest': 'empty',
>    referer: 'http://localhost:3001/cart',
>    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36',
>    'accept-encoding': 'gzip, deflate, br',
>    'accept-language': 'en-US,en;q=0.9'
>  }
>  content type is undefined
</code>```

答:
After much tearing out of hair, I've found what looks to be the solution. I simply wrapped all the business logic of the firebase function inside the cors() call as below. None of the docs or examples I've seen have done this, so I'm not sure why this works. If anyone knows, please let me know!

export const updateArtwork = functions.https.onRequest(
  async (request, response) => {
    return cors(request, response, async () => {
      try {
        const {
          artworkId,
          title,
          description,
          price,
          printPrice,
          medium,
        } = request.body;

        await db.collection('artworks').doc(artworkId).update({
          title,
          description,
          price,
          printPrice,
          medium,
        });
      } catch (err) {
        return cors(request, response, () => {
          response.status(500).end(err);
        });
      }
      response.status(200).send('Successfully saved changes to artist');
    });
  }
);
```

Body:
I have a simple function on my front-end which calls a firebase function on the back-end. Although the request and the API logic are very simple, the call always fails, because the firebase function is unable to detect either the body or the appropriate headers of the request.

Here is the front-end code:

async function updateArtwork(
  artworkId: string,
  title: string,
  medium: string,
  description?: string,
  price?: number,
  printPrice?: number
): Promise<string> {
  try {
    const res = await fetch(`${config.apiUrl}updateArtwork`, {
      method: 'POST',
      body: JSON.stringify({
        artworkId,
        title,
        description,
        price,
        printPrice,
        medium,
      }),
      headers: new Headers({ 'Content-Type': 'application/json' }),
    });
    if (res) {
      return res.json();
    } else {
      throw new Error('Could not save changes to this artwork');
    }
  } catch (err) {
    throw new Error('Could not save changes to this artwork');
  }
}

Here's the firebase function:

export const updateArtwork = functions.https.onRequest(
  async (request, response) => {
    doChecks(request);
    const {
      artworkId,
      title,
      description,
      price,
      printPrice,
      medium,
    } = request.body;

    try {
      await db.collection('artworks').doc(artworkId).update({
        title,
        description,
        price,
        printPrice,
        medium,
      });
      return cors(request, response, () => {
        return response
          .status(200)
          .json('Successfully saved changes to artist');
      });
    } catch (error) {
      return response.status(500);
    }
  }
);

The function doChecks() just logs various things about the request to the console, including the headers and the body. Bafflingly, according to these logs request.body is {}, even though when I check the dev tools network tab, the body is populated. Similarly, the logs tell me that there is no content-type header on the request, while dev tools tells me the content-type is application/json, which is as expected.

In addition, the above call in the front-end makes two API calls, as opposed to the expected one. I know it does this because I did the following:

set a breakpoint on the const res = await fetch... line

hit that breakpoint and checked the dev tools network tab to confirm that no requests have yet been made

clicked "step over" in dev tools to step to the next line (if (res)...)

checked the network tab and saw two POST calls to the same endpoint

What makes this even more strange is that none of the above code has changed recently. It's possible that recent environment changes (upgrading npm packages, etc.) have somehow messed things up, but it's unclear what effect they would have.

Any help on this would be greatly appreciated!

EDIT

Here is more detail on the doChecks() function mentioned above. Here is the function:

const doChecks = (request: any) => {
  console.log('request.body:');
  console.log(request.body);
  console.log('request.headers:');
  console.log(request.headers);
  console.log(`content type is ${request.headers['content-type']}`);
};

For the above call, here is what is logged:

>  request.body:
>  {}
>  request.headers:
>  {
>    host: 'localhost:5001',
>    connection: 'keep-alive',
>    accept: '*/*',
>    'access-control-request-method': 'POST',
>    'access-control-request-headers': 'content-type,pragma',
>    origin: 'http://localhost:3001',
>    'sec-fetch-mode': 'cors',
>    'sec-fetch-site': 'same-site',
>    'sec-fetch-dest': 'empty',
>    referer: 'http://localhost:3001/cart',
>    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36',
>    'accept-encoding': 'gzip, deflate, br',
>    'accept-language': 'en-US,en;q=0.9'
>  }
>  content type is undefined


问:
Ruby - convert string to date
I have a string like "2011-06-02T23:59:59+05:30".

I want to convert it to date format and need to parse only the date, "2011-06-02".

答:
Time.parse() should allow you to parse the whole date time. Then you can use time.strftime( string ) to format that as just a date in a string. </p>

```
date = Time.parse("2011-06-02T23:59:59+05:30")
date_string = time.strftime("%y-%m-%d")
of
date_string = time.strftime("%F")
```

<p>(see Ruby Doc for Time for more output string formats)
The above should work if you want a string; if you want a date object to handle then the ruby Date class can help you handle it but I belive that everything still needs to be done with Time objects; see Ruby Doc for Date for details of the Date class.  </p>

<p>Hope that helps, let me know if I have headed off in the wrong direction with my answer.  </p>

Title: Ruby - convert string to date

Body:
Time.parse() should allow you to parse the whole date time. Then you can use time.strftime( string ) to format that as just a date in a string.

date = Time.parse("2011-06-02T23:59:59+05:30")
date_string = time.strftime("%y-%m-%d")
of
date_string = time.strftime("%F")

(see Ruby Doc for Time for more output string formats)
The above should work if you want a string; if you want a date object to handle then the ruby Date class can help you handle it but I belive that everything still needs to be done with Time objects; see Ruby Doc for Date for details of the Date class.

Hope that helps, let me know if I have headed off in the wrong direction with my answer.