问:
Bind resolve_handler to resolver async_resolve using boost::asio
I have this code. How can I bind my method resolve_handler with the expected iterator and error parameters? Is it the correct way to break down the connection logic?</p>

```<code>void FileClient::start()
{
    try {
        boost::asio::ip::tcp::resolver::query query("ip", "port");
        resolver_.async_resolve(query, boost::bind(
            &FileClient::resolve_handler, this
        ));
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }
}

void FileClient::resolve_handler(const boost::system::error_code &_error,
                                 boost::asio::ip::tcp::resolver::iterator _it)
{
    if (!_error)
        socket_.async_connect(*_it, boost::bind(
            &FileClient::connect_handler, this, boost::asio::placeholders::error
        ));
    else
        std::cerr << "resolve_handler error: " << _error << std::endl;
}
</code>```

答:
There are examples in boost.asio tutorials, for example, from this HTTP async client

```<code>tcp::resolver::query query(server, "http");
    resolver_.async_resolve(query,
        boost::bind(&client::handle_resolve, this,
          boost::asio::placeholders::error,
          boost::asio::placeholders::iterator));
</code>```

...

```<code>void handle_resolve(const boost::system::error_code& err,
                    tcp::resolver::iterator endpoint_iterator)
{
    if (!err)
    {
        // Attempt a connection to the first endpoint in the list. Each endpoint
        // will be tried until we successfully establish a connection.
         tcp::endpoint endpoint = *endpoint_iterator;
         socket_.async_connect(endpoint,
                         boost::bind(&client::handle_connect, this,
                         boost::asio::placeholders::error, ++endpoint_iterator));
    }
    else
    {
        std::cout << "Error: " << err.message() << "\n";
    }
}
</code>```

(their handle_connect continues to increment endpoint_iterator as necessary)

Body:
I have this code. How can I bind my method resolve_handler with the expected iterator and error parameters? Is it the correct way to break down the connection logic?

void FileClient::start()
{
    try {
        boost::asio::ip::tcp::resolver::query query("ip", "port");
        resolver_.async_resolve(query, boost::bind(
            &FileClient::resolve_handler, this
        ));
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }
}

void FileClient::resolve_handler(const boost::system::error_code &_error,
                                 boost::asio::ip::tcp::resolver::iterator _it)
{
    if (!_error)
        socket_.async_connect(*_it, boost::bind(
            &FileClient::connect_handler, this, boost::asio::placeholders::error
        ));
    else
        std::cerr << "resolve_handler error: " << _error << std::endl;
}

Body:
There are examples in boost.asio tutorials, for example, from this HTTP async client

tcp::resolver::query query(server, "http");
    resolver_.async_resolve(query,
        boost::bind(&client::handle_resolve, this,
          boost::asio::placeholders::error,
          boost::asio::placeholders::iterator));

...

void handle_resolve(const boost::system::error_code& err,
                    tcp::resolver::iterator endpoint_iterator)
{
    if (!err)
    {
        // Attempt a connection to the first endpoint in the list. Each endpoint
        // will be tried until we successfully establish a connection.
         tcp::endpoint endpoint = *endpoint_iterator;
         socket_.async_connect(endpoint,
                         boost::bind(&client::handle_connect, this,
                         boost::asio::placeholders::error, ++endpoint_iterator));
    }
    else
    {
        std::cout << "Error: " << err.message() << "\n";
    }
}

(their handle_connect continues to increment endpoint_iterator as necessary)


来源: stackexchange

问:
Batch file: Find if substring is in string (not in a file)
In a batch file, I have a string abcdefg.  I want to check if bcd is in the string.

Unfortunately it seems all of the solutions I'm finding search a file for a substring, not a string for a substring.

Is there an easy solution for this?

答:
The solutions that search a file for a substring can also search a string, eg. find or findstr.

In your case, the easy solution would be to pipe a string into the command instead of supplying a filename eg.

case-sensitive string:

echo "abcdefg" | find "bcd"

ignore case of string:

echo "abcdefg" | find /I "bcd"

IF no match found, you will get a blank line response on CMD and %ERRORLEVEL% set to 1

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
git submodule add + not working + getting ssl server issue
I am trying to add a submodule myapp to my admin directory, bith of which are gits. But I keep getting SSL certificate problem. I have done git config http.sslVerify false to try and get it to work (but I am not fully sure why this should help, it worked when I wanted to push to a master git push -u origin master).Any ideas?

```<code>$ pwd
/c/Users/UserName/dir/admin
$ git submodule add ../myapp/
Cloning into 'myapp'...
fatal: unable to access 'https://myserver.com/gogs/user1/myapp/': SSL certificate problem: unable to get local issuer certificate
Clone of 'https://myserver.com/gogs/user1/myapp' into submodule path 'myapp' failed
$ git config --list |grep ssl
http.sslverify=false
$
</code>```

EDIT1

Tried it again in a similar environment using ssh but something wrong with my access rights. Any ideas?

```<code>$ git submodule add ssh:../../lte_data_day_summary/
Cloning into 'sceal/lte_data_day_summary'...
ssh: Could not resolve hostname ssh: Temporary failure in name resolution
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
Clone of 'ssh:../../lte_data_day_summary/' into submodule path 'sceal/lte_data_day_summary' failed
$ pwd
/c/Users/User Name/dir1/dir2/sceal
</code>```

EDIT2 - notes to self

global config

```<code>$ git config --global --list
user.email=you@example.com
http.sslverify=false
</code>```

local config -- why is there 2? is this local and global?

```<code>$ git config --list | grep ssl
http.sslverify=false
http.sslverify=false
</code>```

答:
This might be the cause: [PATCH] submodule: stop sanitizing config options - Jeff King

```<code>
The point of having a whitelist of command-line config
options to pass to submodules was two-fold:

  1. It prevented obvious nonsense like using core.worktree
     for multiple repos.

  2. It could prevent surprise when the user did not mean
     for the options to leak to the submodules (e.g.,
     http.sslverify=false).

For case 1, the answer is mostly "if it hurts, don't do
that". For case 2, we can note that any such example has a
matching inverted surprise (e.g., a user who meant
http.sslverify=true to apply everywhere, but it didn't).
</code>```

The configuration might be dropped in order to avoid passing them to the submodules and causing unintended results (like cloning a certificate verifiable HTTPS submodule without verification).  A workaround is to set the GIT_SSL_NO_VERIFY environment variable to the git submodule command:

# Set the environment variable is sufficient, no content is necessary
GIT_SSL_NO_VERIFY= git submodule add ...
```

Body:
I am trying to add a submodule myapp to my admin directory, bith of which are gits. But I keep getting SSL certificate problem. I have done git config http.sslVerify false to try and get it to work (but I am not fully sure why this should help, it worked when I wanted to push to a master git push -u origin master).Any ideas?

$ pwd
/c/Users/UserName/dir/admin
$ git submodule add ../myapp/
Cloning into 'myapp'...
fatal: unable to access 'https://myserver.com/gogs/user1/myapp/': SSL certificate problem: unable to get local issuer certificate
Clone of 'https://myserver.com/gogs/user1/myapp' into submodule path 'myapp' failed
$ git config --list |grep ssl
http.sslverify=false
$

EDIT1

Tried it again in a similar environment using ssh but something wrong with my access rights. Any ideas?

$ git submodule add ssh:../../lte_data_day_summary/
Cloning into 'sceal/lte_data_day_summary'...
ssh: Could not resolve hostname ssh: Temporary failure in name resolution
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
Clone of 'ssh:../../lte_data_day_summary/' into submodule path 'sceal/lte_data_day_summary' failed
$ pwd
/c/Users/User Name/dir1/dir2/sceal

EDIT2 - notes to self

global config

$ git config --global --list
user.email=you@example.com
http.sslverify=false

local config -- why is there 2? is this local and global?

$ git config --list | grep ssl
http.sslverify=false
http.sslverify=false

Body:
This might be the cause: [PATCH] submodule: stop sanitizing config options - Jeff King

The point of having a whitelist of command-line config
options to pass to submodules was two-fold:

  1. It prevented obvious nonsense like using core.worktree
     for multiple repos.

  2. It could prevent surprise when the user did not mean
     for the options to leak to the submodules (e.g.,
     http.sslverify=false).

For case 1, the answer is mostly "if it hurts, don't do
that". For case 2, we can note that any such example has a
matching inverted surprise (e.g., a user who meant
http.sslverify=true to apply everywhere, but it didn't).

The configuration might be dropped in order to avoid passing them to the submodules and causing unintended results (like cloning a certificate verifiable HTTPS submodule without verification).  A workaround is to set the GIT_SSL_NO_VERIFY environment variable to the git submodule command:

# Set the environment variable is sufficient, no content is necessary
GIT_SSL_NO_VERIFY= git submodule add ...


问:
Out-FINcodedCommand.ps1 is not recognized - executing a script in the current directory
I have seen this script https://github.com/danielbohannon/Out-FINcodedCommand/blob/master/README.md

And when I try the the example given I get the error

Out-FINcodedCommand.ps1 : The term 'Out-FINcodedCommand.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that
the path is correct and try again.
At line:1 char:1
Out-FINcodedCommand.ps1 -command "iex (iwr https://github.com/danielb ...
CategoryInfo : ObjectNotFound: (Out-FINcodedCommand.ps1:String) [], CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundException
```

Can you help?

答:
Where are you running it.  Add .\ in front of it

```<code>.\Out-FINcodedCommand.ps1
</code>```

If it is in a directory that you are not cd to, then the .\ needs to be in front of the whole string

```<code>.\Downloads\Out-FINcodedCommand-master\Out-FINcodedCommand-master\Out-FINcodedCommand.ps1
</code>```

Body:
I have seen this script https://github.com/danielbohannon/Out-FINcodedCommand/blob/master/README.md

And when I try the the example given I get the error

Out-FINcodedCommand.ps1 : The term 'Out-FINcodedCommand.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that
the path is correct and try again.
At line:1 char:1
Out-FINcodedCommand.ps1 -command "iex (iwr https://github.com/danielb ...
CategoryInfo : ObjectNotFound: (Out-FINcodedCommand.ps1:String) [], CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundException

Can you help?

Body:
Where are you running it.  Add .\ in front of it

.\Out-FINcodedCommand.ps1

If it is in a directory that you are not cd to, then the .\ needs to be in front of the whole string

.\Downloads\Out-FINcodedCommand-master\Out-FINcodedCommand-master\Out-FINcodedCommand.ps1


问:
Create a new window in Qt which depends on the parent window, but appears outside of the parent window
I want to implement a log for my application, and I want it to be in another window. But of course it should close when the main window is closed.

The main window is created with class Window which inherits from QWidget.

When I create the second window the same way and pass into the constructor "this" as parent, that does not work, everything that is inside new window appears inside parent window. But when I don't pass anything into the constructor of new window, it does not close when the parent window closed.

答: As @hyde commented, you should set Qt::Window for the window flags when you create the window widget, and then you can give it a parent and it will be a "secondary window" and will close when the parent closes.  Inheriting from QDialog is fine, but brings along additional baggage that you may not want/need; the simple answer to the question is to use Qt::Window.


问:
Why I can't find the process of the project while I attach to the remote server?
I want to debug my program on the remote server computer(Windows Server 2012R) that followed this tutorial:https://learn.microsoft.com/en-us/visualstudio/debugger/remote-debugging-aspnet-on-a-remote-iis-computer?view=vs-2019#BKMK_msvsmon

I am using the Visual Studio 2019 16.5 preview 2.0, and I have installed the Visual Studio 2019 Remote Debugger on the server computer already.

As you see, now I connect to the remote server successfully.

Meanwhile, I can't find the process of the project in Visual Studio of the local computer.

I have checked that the process of the project has run successfully via the Visual Studio Code on the remote server.

Why it turns out to be this? How can I solve it? Thank you.

答:
Copied from the comments.

You might study more about Windows session isolation so as to understand how IIS worker processes are created under system session (session 0) and run under their application pool identities.

As a result, when you try to remote debug, by default you won't be able to see w3wp.exe because they don't belong to the account you log on to that machine (XX\Administrator in your case).

You have to check "Show processes from all users" and then the desired processes should appear.


问:
subprocess.Popen tries to write to nonexistent pipe
Why doesn't the following work?

```<code>import subprocess

process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None)
</code>```

The output I get is the following:

```<code>The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
</code>```

After which the process terminates without an error. I'm running Windows 7.

答: I'm running windows 10 and have the same problem. The error goes away for me if I set stdout and stderr to the same value. Try setting them both to subprocess.PIPE instead of just stdout.</p>

Body:
Why doesn't the following work?

import subprocess

process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None)

The output I get is the following:

The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.

After which the process terminates without an error. I'm running Windows 7.


问:
GloVe for Python 3.7 version
I am trying to install GloVe package from Pypi on Python version 3.7 but it keeps returning the same error written below. Is there any way to use GloVe? I have also tried to install it from https://github.com/stanfordnlp/GloVe  but it also ends with error.
Thank you for your help!    </p>

```<code>pip install glove Collecting glove   Using cached glove-1.0.2.tar.gz (44 kB) Requirement already satisfied: numpy in d:\anaconda\lib\site-packages (from glove) (1.16.4) Building wheels for collected packages: glove   Building wheel for glove (setup.py) ... error   ERROR: Command errored out with exit status 1:    command: 'd:\anaconda\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Dell\\AppData\\Local\\Temp\\pip-install-vlqonr2u\\glove\\setup.py'"'"';
__file__='"'"'C:\\Users\\Dell\\AppData\\Local\\Temp\\pip-install-vlqonr2u\\glove\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Dell\AppData\Local\Temp\pip-wheel-c3ip0qox'
       cwd: C:\Users\Dell\AppData\Local\Temp\pip-install-vlqonr2u\glove\   Complete output (67 lines):   running bdist_wheel   running build   running build_py   creating build   creating build\lib.win-amd64-3.7   creating build\lib.win-amd64-3.7\glove   copying glove\glove.py -> build\lib.win-amd64-3.7\glove   copying glove\__init__.py -> build\lib.win-amd64-3.7\glove   running egg_info   writing glove.egg-info\PKG-INFO   writing dependency_links to glove.egg-info\dependency_links.txt   writing requirements to glove.egg-info\requires.txt   writing top-level names to glove.egg-info\top_level.txt   reading manifest file 'glove.egg-info\SOURCES.txt'   Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "C:\Users\Dell\AppData\Local\Temp\pip-install-vlqonr2u\glove\setup.py", line 85, in <module>
      include_package_data=True,
    File "d:\anaconda\lib\site-packages\setuptools\__init__.py", line 144, in setup
      return distutils.core.setup(**attrs)
    File "d:\anaconda\lib\distutils\core.py", line 148, in setup
      dist.run_commands()
    File "d:\anaconda\lib\distutils\dist.py", line 966, in run_commands
      self.run_command(cmd)
    File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
      cmd_obj.run()
    File "d:\anaconda\lib\site-packages\wheel\bdist_wheel.py", line 223, in run
      self.run_command('build')
    File "d:\anaconda\lib\distutils\cmd.py", line 313, in run_command
      self.distribution.run_command(command)
    File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
      cmd_obj.run()
    File "d:\anaconda\lib\distutils\command\build.py", line 135, in run
      self.run_command(cmd_name)
    File "d:\anaconda\lib\distutils\cmd.py", line 313, in run_command
      self.distribution.run_command(command)
    File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
      cmd_obj.run()
    File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 53, in run
      self.build_package_data()
    File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 118, in build_package_data
      for package, src_dir, build_dir, filenames in self.data_files:
    File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 66, in __getattr__
      self.data_files = self._get_data_files()
    File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 82, in _get_data_files
      self.analyze_manifest()
    File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 138, in analyze_manifest
      self.run_command('egg_info')
    File "d:\anaconda\lib\distutils\cmd.py", line 313, in run_command
      self.distribution.run_command(command)
    File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
      cmd_obj.run()
    File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 297, in run
      self.find_sources()
    File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 304, in find_sources
      mm.run()
    File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 535, in run
      self.add_defaults()
    File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 579, in add_defaults
      self.read_manifest()
    File "d:\anaconda\lib\site-packages\setuptools\command\sdist.py", line 220, in read_manifest
      self.filelist.append(line)
    File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 477, in append
      path = convert_path(item)
    File "d:\anaconda\lib\distutils\util.py", line 110, in convert_path
      raise ValueError("path '%s' cannot be absolute" % pathname)   ValueError: path '/Users/jonathanraiman/Desktop/Coding/python_packages/glove/glove/glove_inner.cpp' cannot be absolute   ----------------------------------------   ERROR: Failed building wheel for glove   Running setup.py clean for glove Failed to build glove Installing collected packages: glove
    Running setup.py install for glove ... error
    ERROR: Command errored out with exit status 1:
     command: 'd:\anaconda\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Dell\\AppData\\Local\\Temp\\pip-install-vlqonr2u\\glove\\setup.py'"'"';
__file__='"'"'C:\\Users\\Dell\\AppData\\Local\\Temp\\pip-install-vlqonr2u\\glove\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Dell\AppData\Local\Temp\pip-record-mo9f0x8b\install-record.txt'
--single-version-externally-managed --compile --install-headers 'd:\anaconda\Include\glove'
         cwd: C:\Users\Dell\AppData\Local\Temp\pip-install-vlqonr2u\glove\
    Complete output (69 lines):
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.7
    creating build\lib.win-amd64-3.7\glove
    copying glove\glove.py -> build\lib.win-amd64-3.7\glove
    copying glove\__init__.py -> build\lib.win-amd64-3.7\glove
    running egg_info
    writing glove.egg-info\PKG-INFO
    writing dependency_links to glove.egg-info\dependency_links.txt
    writing requirements to glove.egg-info\requires.txt
    writing top-level names to glove.egg-info\top_level.txt
    reading manifest file 'glove.egg-info\SOURCES.txt'
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\Dell\AppData\Local\Temp\pip-install-vlqonr2u\glove\setup.py", line 85, in <module>
        include_package_data=True,
      File "d:\anaconda\lib\site-packages\setuptools\__init__.py", line 144, in setup
        return distutils.core.setup(**attrs)
      File "d:\anaconda\lib\distutils\core.py", line 148, in setup
        dist.run_commands()
      File "d:\anaconda\lib\distutils\dist.py", line 966, in run_commands
        self.run_command(cmd)
      File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "d:\anaconda\lib\site-packages\setuptools\command\install.py", line 61, in run
        return orig.install.run(self)
      File "d:\anaconda\lib\distutils\command\install.py", line 545, in run
        self.run_command('build')
      File "d:\anaconda\lib\distutils\cmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "d:\anaconda\lib\distutils\command\build.py", line 135, in run
        self.run_command(cmd_name)
      File "d:\anaconda\lib\distutils\cmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 53, in run
        self.build_package_data()
      File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 118, in build_package_data
        for package, src_dir, build_dir, filenames in self.data_files:
      File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 66, in __getattr__
        self.data_files = self._get_data_files()
      File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 82, in _get_data_files
        self.analyze_manifest()
      File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 138, in analyze_manifest
        self.run_command('egg_info')
      File "d:\anaconda\lib\distutils\cmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 297, in run
        self.find_sources()
      File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 304, in find_sources
        mm.run()
      File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 535, in run
        self.add_defaults()
      File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 579, in add_defaults
        self.read_manifest()
      File "d:\anaconda\lib\site-packages\setuptools\command\sdist.py", line 220, in read_manifest
        self.filelist.append(line)
      File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 477, in append
        path = convert_path(item)
      File "d:\anaconda\lib\distutils\util.py", line 110, in convert_path
        raise ValueError("path '%s' cannot be absolute" % pathname)
    ValueError: path '/Users/jonathanraiman/Desktop/Coding/python_packages/glove/glove/glove_inner.cpp' cannot be absolute
    ---------------------------------------- ERROR: Command errored out with exit status 1: 'd:\anaconda\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Dell\\AppData\\Local\\Temp\\pip-install-vlqonr2u\\glove\\setup.py'"'"';
__file__='"'"'C:\\Users\\Dell\\AppData\\Local\\Temp\\pip-install-vlqonr2u\\glove\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Dell\AppData\Local\Temp\pip-record-mo9f0x8b\install-record.txt'
--single-version-externally-managed --compile --install-headers 'd:\anaconda\Include\glove' Check the logs for full command output.<
</code>```

答:
You could source install it. clone it from github then</p>

```<code>pip install .
</code>```

Title: GloVe for Python 3.7 version

Body:
I am trying to install GloVe package from Pypi on Python version 3.7 but it keeps returning the same error written below. Is there any way to use GloVe? I have also tried to install it from https://github.com/stanfordnlp/GloVe  but it also ends with error.
Thank you for your help!

pip install glove Collecting glove   Using cached glove-1.0.2.tar.gz (44 kB) Requirement already satisfied: numpy in d:\anaconda\lib\site-packages (from glove) (1.16.4) Building wheels for collected packages: glove   Building wheel for glove (setup.py) ... error   ERROR: Command errored out with exit status 1:    command: 'd:\anaconda\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Dell\\AppData\\Local\\Temp\\pip-install-vlqonr2u\\glove\\setup.py'"'"';
__file__='"'"'C:\\Users\\Dell\\AppData\\Local\\Temp\\pip-install-vlqonr2u\\glove\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Dell\AppData\Local\Temp\pip-wheel-c3ip0qox'
       cwd: C:\Users\Dell\AppData\Local\Temp\pip-install-vlqonr2u\glove\   Complete output (67 lines):   running bdist_wheel   running build   running build_py   creating build   creating build\lib.win-amd64-3.7   creating build\lib.win-amd64-3.7\glove   copying glove\glove.py -> build\lib.win-amd64-3.7\glove   copying glove\__init__.py -> build\lib.win-amd64-3.7\glove   running egg_info   writing glove.egg-info\PKG-INFO   writing dependency_links to glove.egg-info\dependency_links.txt   writing requirements to glove.egg-info\requires.txt   writing top-level names to glove.egg-info\top_level.txt   reading manifest file 'glove.egg-info\SOURCES.txt'   Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "C:\Users\Dell\AppData\Local\Temp\pip-install-vlqonr2u\glove\setup.py", line 85, in <module>
      include_package_data=True,
    File "d:\anaconda\lib\site-packages\setuptools\__init__.py", line 144, in setup
      return distutils.core.setup(**attrs)
    File "d:\anaconda\lib\distutils\core.py", line 148, in setup
      dist.run_commands()
    File "d:\anaconda\lib\distutils\dist.py", line 966, in run_commands
      self.run_command(cmd)
    File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
      cmd_obj.run()
    File "d:\anaconda\lib\site-packages\wheel\bdist_wheel.py", line 223, in run
      self.run_command('build')
    File "d:\anaconda\lib\distutils\cmd.py", line 313, in run_command
      self.distribution.run_command(command)
    File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
      cmd_obj.run()
    File "d:\anaconda\lib\distutils\command\build.py", line 135, in run
      self.run_command(cmd_name)
    File "d:\anaconda\lib\distutils\cmd.py", line 313, in run_command
      self.distribution.run_command(command)
    File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
      cmd_obj.run()
    File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 53, in run
      self.build_package_data()
    File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 118, in build_package_data
      for package, src_dir, build_dir, filenames in self.data_files:
    File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 66, in __getattr__
      self.data_files = self._get_data_files()
    File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 82, in _get_data_files
      self.analyze_manifest()
    File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 138, in analyze_manifest
      self.run_command('egg_info')
    File "d:\anaconda\lib\distutils\cmd.py", line 313, in run_command
      self.distribution.run_command(command)
    File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
      cmd_obj.run()
    File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 297, in run
      self.find_sources()
    File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 304, in find_sources
      mm.run()
    File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 535, in run
      self.add_defaults()
    File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 579, in add_defaults
      self.read_manifest()
    File "d:\anaconda\lib\site-packages\setuptools\command\sdist.py", line 220, in read_manifest
      self.filelist.append(line)
    File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 477, in append
      path = convert_path(item)
    File "d:\anaconda\lib\distutils\util.py", line 110, in convert_path
      raise ValueError("path '%s' cannot be absolute" % pathname)   ValueError: path '/Users/jonathanraiman/Desktop/Coding/python_packages/glove/glove/glove_inner.cpp' cannot be absolute   ----------------------------------------   ERROR: Failed building wheel for glove   Running setup.py clean for glove Failed to build glove Installing collected packages: glove
    Running setup.py install for glove ... error
    ERROR: Command errored out with exit status 1:
     command: 'd:\anaconda\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Dell\\AppData\\Local\\Temp\\pip-install-vlqonr2u\\glove\\setup.py'"'"';
__file__='"'"'C:\\Users\\Dell\\AppData\\Local\\Temp\\pip-install-vlqonr2u\\glove\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Dell\AppData\Local\Temp\pip-record-mo9f0x8b\install-record.txt'
--single-version-externally-managed --compile --install-headers 'd:\anaconda\Include\glove'
         cwd: C:\Users\Dell\AppData\Local\Temp\pip-install-vlqonr2u\glove\
    Complete output (69 lines):
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.7
    creating build\lib.win-amd64-3.7\glove
    copying glove\glove.py -> build\lib.win-amd64-3.7\glove
    copying glove\__init__.py -> build\lib.win-amd64-3.7\glove
    running egg_info
    writing glove.egg-info\PKG-INFO
    writing dependency_links to glove.egg-info\dependency_links.txt
    writing requirements to glove.egg-info\requires.txt
    writing top-level names to glove.egg-info\top_level.txt
    reading manifest file 'glove.egg-info\SOURCES.txt'
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\Dell\AppData\Local\Temp\pip-install-vlqonr2u\glove\setup.py", line 85, in <module>
        include_package_data=True,
      File "d:\anaconda\lib\site-packages\setuptools\__init__.py", line 144, in setup
        return distutils.core.setup(**attrs)
      File "d:\anaconda\lib\distutils\core.py", line 148, in setup
        dist.run_commands()
      File "d:\anaconda\lib\distutils\dist.py", line 966, in run_commands
        self.run_command(cmd)
      File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "d:\anaconda\lib\site-packages\setuptools\command\install.py", line 61, in run
        return orig.install.run(self)
      File "d:\anaconda\lib\distutils\command\install.py", line 545, in run
        self.run_command('build')
      File "d:\anaconda\lib\distutils\cmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "d:\anaconda\lib\distutils\command\build.py", line 135, in run
        self.run_command(cmd_name)
      File "d:\anaconda\lib\distutils\cmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 53, in run
        self.build_package_data()
      File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 118, in build_package_data
        for package, src_dir, build_dir, filenames in self.data_files:
      File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 66, in __getattr__
        self.data_files = self._get_data_files()
      File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 82, in _get_data_files
        self.analyze_manifest()
      File "d:\anaconda\lib\site-packages\setuptools\command\build_py.py", line 138, in analyze_manifest
        self.run_command('egg_info')
      File "d:\anaconda\lib\distutils\cmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "d:\anaconda\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 297, in run
        self.find_sources()
      File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 304, in find_sources
        mm.run()
      File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 535, in run
        self.add_defaults()
      File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 579, in add_defaults
        self.read_manifest()
      File "d:\anaconda\lib\site-packages\setuptools\command\sdist.py", line 220, in read_manifest
        self.filelist.append(line)
      File "d:\anaconda\lib\site-packages\setuptools\command\egg_info.py", line 477, in append
        path = convert_path(item)
      File "d:\anaconda\lib\distutils\util.py", line 110, in convert_path
        raise ValueError("path '%s' cannot be absolute" % pathname)
    ValueError: path '/Users/jonathanraiman/Desktop/Coding/python_packages/glove/glove/glove_inner.cpp' cannot be absolute
    ---------------------------------------- ERROR: Command errored out with exit status 1: 'd:\anaconda\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Dell\\AppData\\Local\\Temp\\pip-install-vlqonr2u\\glove\\setup.py'"'"';
__file__='"'"'C:\\Users\\Dell\\AppData\\Local\\Temp\\pip-install-vlqonr2u\\glove\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Dell\AppData\Local\Temp\pip-record-mo9f0x8b\install-record.txt'
--single-version-externally-managed --compile --install-headers 'd:\anaconda\Include\glove' Check the logs for full command output.<

Body:
You could source install it. clone it from github then

pip install .


问:
How to calcluate sum of column python pandas
I am simply trying to get the sum of a column ('Value') in a dataframe in python. I believe I am creating the dataframe, but I am not sure. I am getting a result back, however, it's not the result I imagine when it comes to .sum().

```<code>import csv
import pandas as pd

with open('new_taste.csv', 'r') as csv_trades:
    csv_reader = csv.DictReader(csv_trades)

    df = pd.DataFrame(data=csv_reader)
    total = df['Value'].sum()
    df.loc['Value'] = pd.Series(df['Value'].sum(), index=['Value'])
    print(df['Value'])

</code>```

is giving me

```<code>0                                                      133
1                                                      180
2                                                     -117
3                                                     -159
4                                                        1
                               ...
316                                                     14
317                                                     14
318                                                     19
319                                                     18
Value    133180-117-15911-84-3-10-23434245-23-3085-5241...
Name: Value, Length: 321, dtype: object
</code>```

I noticed it's bringing back every number, not the sum of the numbers. I would like to bring back the sum.

答:
It seems return string values after recognizing df['Value'] values to string.

How about change 9th line of your code to below

df.loc['Value'] = pd.Series(df['Value'].sum(), index=['Value'])

And could you share what it returns to "total" variable.

Body:
I am simply trying to get the sum of a column ('Value') in a dataframe in python. I believe I am creating the dataframe, but I am not sure. I am getting a result back, however, it's not the result I imagine when it comes to .sum().

import csv
import pandas as pd

with open('new_taste.csv', 'r') as csv_trades:
    csv_reader = csv.DictReader(csv_trades)

    df = pd.DataFrame(data=csv_reader)
    total = df['Value'].sum()
    df.loc['Value'] = pd.Series(df['Value'].sum(), index=['Value'])
    print(df['Value'])

is giving me

0                                                      133
1                                                      180
2                                                     -117
3                                                     -159
4                                                        1
                               ...
316                                                     14
317                                                     14
318                                                     19
319                                                     18
Value    133180-117-15911-84-3-10-23434245-23-3085-5241...
Name: Value, Length: 321, dtype: object

I noticed it's bringing back every number, not the sum of the numbers. I would like to bring back the sum.


问:
swf upload to amazon s3 subdirectory
I am successful in uploading to amazon s3 bucket using post and swf upload but can any one tell me how to upload to a subdirectory inside my bucket.

I am using php as my server side language.

Thanks in advance

答:
you should include the file path in your policy and post parameters. for example, when setting your policy array, set the key of the file to be "/path/../filename.ext".

```<code>array("starts-with", '$key', $this->file_key);
</code>```

use that in the key in post parameters

Title: swf upload to amazon s3 subdirectory

Body:
you should include the file path in your policy and post parameters. for example, when setting your policy array, set the key of the file to be "/path/../filename.ext".

array("starts-with", '$key', $this->file_key);

use that in the key in post parameters


问:
Producing executable jar in NetBeans
I'm using NetBeans 6.5 and for some reason it won't produce executable jar "out of the box".

I set my project to be the main project, defined main class in the project properties "run" menu and it works flawlessly when I press F6 to run it.

I looked at the manifest file and it indeed didn't define the main class there, and also omitted the library dependencies.

Am I missing something? Is there a way (other than manually altering the manifest file) to produce executable jar files?

EDIT: yes, I tried clean and rebuild and it produced the jar in the dist folder, still with the same manifest.mf

```<code>Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.1
Created-By: 10.0-b23 (Sun Microsystems Inc.)
</code>```

答:
Did you clean the project and rebuild?  It sound like you're doing it right.  Heres some references just in case:

http://www.velocityreviews.com/forums/t141385-how-to-create-executable-jar-in-netbeans-ide.html
http://dr.berkeley.edu/REM/wiki/index.php/Making_a_Java_executable_jar_in_Netbeans

OwnerDisplayName: Dani

ContentLicense: CC BY-SA 2.5

Title: Producing executable jar in NetBeans

Body:
I'm using NetBeans 6.5 and for some reason it won't produce executable jar "out of the box".

I set my project to be the main project, defined main class in the project properties "run" menu and it works flawlessly when I press F6 to run it.

I looked at the manifest file and it indeed didn't define the main class there, and also omitted the library dependencies.

Am I missing something? Is there a way (other than manually altering the manifest file) to produce executable jar files?

EDIT: yes, I tried clean and rebuild and it produced the jar in the dist folder, still with the same manifest.mf

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.1
Created-By: 10.0-b23 (Sun Microsystems Inc.)

LastEditorDisplayName: Dani

OwnerDisplayName: John Ellinwood


问:
Is this a bug in IE8 / jQuery?
I am targeting my form with a submit listener.

The HTML

```<code><div id="entry-form">
   <form method="post" action="">
       <input type="submit" value="submit" />
   </form>
</div>
</code>```

The Script:

```<code>    $(document).ready(function(){

        $("#entry-form form").submit(function(e){
            e.preventDefault();
            alert("In Submit Form");
        });

    });
</code>```

This works fine in all the browsers I have tested thus far. However when I try to use a section tag rather than a div:

```<code><section id="entry-form">
   <form method="post" action="">
       <input type="submit" value="submit" />
   </form>
</section>
</code>```

The submit listener will no longer work in IE8 and instead IE8 submits the form with a page refresh. This is not the case in FF where it will work as intended.

Is this a known bug with IE8 and jQuery?

答: Most html5 features, including "section", are not supported in IE browsers earlier than IE9.</p>

Title: Is this a bug in IE8 / jQuery?

Body:
I am targeting my form with a submit listener.

The HTML

   <form method="post" action="">
       <input type="submit" value="submit" />
   </form>

The Script:

    $(document).ready(function(){

        $("#entry-form form").submit(function(e){
            e.preventDefault();
            alert("In Submit Form");
        });

    });

This works fine in all the browsers I have tested thus far. However when I try to use a section tag rather than a div:

   <form method="post" action="">
       <input type="submit" value="submit" />
   </form>

The submit listener will no longer work in IE8 and instead IE8 submits the form with a page refresh. This is not the case in FF where it will work as intended.

Is this a known bug with IE8 and jQuery?


问:
Scheme/Racket: How to do repeating in defining syntax
I can define the infix '+' as below in Racket:

```<code>(require syntax/parse/define (only-in racket (#%app racket:#%app)))
(define-syntax-parser #%app
  [(_ Value1 {~datum +} Value2)
  #'(+ Value1 Value2)]

  [(_ Xs ...)
  #'(racket:#%app Xs ...)]
)
(displayln (1 + 2))
</code>```

I want to add multiple infix '+' using ~between but it doesn't work:

```<code>(require syntax/parse/define (only-in racket (#%app racket:#%app)))
(define-syntax-parser #%app
  [(_ {~between {Value1 {~datum +}} 1 100} Value2)
  #'(+ Value1 Value2)]

  [(_ Xs ...)
  #'(racket:#%app Xs ...)]
)
(displayln (1 + 2))
</code>```

The syntax in Racket is here: https://docs.racket-lang.org/syntax/stxparse-patterns.html with ~between but no ~repeat.

How to use ~between property to repeat items in syntax?

I have a work-around but it doesn't look pure multiple infix +, need to wrap every left entry in brackets:

```<code>(require syntax/parse/define (only-in racket (#%app racket:#%app)))
(define-syntax-parser #%app
  [(_ {Value1 {~datum +}} ... Value2)
  #'(+ Value1 ... Value2)]

  [(_ Xs ...)
  #'(racket:#%app Xs ...)]
)
(displayln ({1 +} {2 +} 3))
</code>```

答:
What you want is a combination of ~seq and ...+.

```<code>(define-syntax-parser #%app
  [(_ {~seq Value1 {~datum +}} ...+ Value2)
   #'(+ Value1 ... Value2)]
  [(_ Xs ...)
   #'(racket:#%app Xs ...)])
</code>```

The ~seq matches a sequence of things without requiring them to be grouped by brackets as your workaround did.

The ...+ is a repetition pattern to match one-or-more things, as opposed to zero-or-more. This makes sure that (f) isn't accidentally interpreted as (+ f).

One more note, when you're defining #%app directly, as opposed to defining under a different name and then renaming the export, you need to be extra careful about implicit recursive uses. For instance (+ + x) is an infinite loop. To fix that you could use racket:#%app in both outputs, like #'(racket:#%app + Value1 ... Value2).

```<code>(define-syntax-parser #%app
  [(_ {~seq Value1 {~datum +}} ...+ Value2)
   #'(racket:#%app + Value1 ... Value2)]
  [(_ Xs ...)
   #'(racket:#%app Xs ...)])
</code>```

Body:
I can define the infix '+' as below in Racket:

(require syntax/parse/define (only-in racket (#%app racket:#%app)))
(define-syntax-parser #%app
  [(_ Value1 {~datum +} Value2)
  #'(+ Value1 Value2)]

  [(_ Xs ...)
  #'(racket:#%app Xs ...)]
)
(displayln (1 + 2))

I want to add multiple infix '+' using ~between but it doesn't work:

(require syntax/parse/define (only-in racket (#%app racket:#%app)))
(define-syntax-parser #%app
  [(_ {~between {Value1 {~datum +}} 1 100} Value2)
  #'(+ Value1 Value2)]

  [(_ Xs ...)
  #'(racket:#%app Xs ...)]
)
(displayln (1 + 2))

The syntax in Racket is here: https://docs.racket-lang.org/syntax/stxparse-patterns.html with ~between but no ~repeat.

How to use ~between property to repeat items in syntax?

I have a work-around but it doesn't look pure multiple infix +, need to wrap every left entry in brackets:

(require syntax/parse/define (only-in racket (#%app racket:#%app)))
(define-syntax-parser #%app
  [(_ {Value1 {~datum +}} ... Value2)
  #'(+ Value1 ... Value2)]

  [(_ Xs ...)
  #'(racket:#%app Xs ...)]
)
(displayln ({1 +} {2 +} 3))

Body:
What you want is a combination of ~seq and ...+.

(define-syntax-parser #%app
  [(_ {~seq Value1 {~datum +}} ...+ Value2)
   #'(+ Value1 ... Value2)]
  [(_ Xs ...)
   #'(racket:#%app Xs ...)])

The ~seq matches a sequence of things without requiring them to be grouped by brackets as your workaround did.

The ...+ is a repetition pattern to match one-or-more things, as opposed to zero-or-more. This makes sure that (f) isn't accidentally interpreted as (+ f).

One more note, when you're defining #%app directly, as opposed to defining under a different name and then renaming the export, you need to be extra careful about implicit recursive uses. For instance (+ + x) is an infinite loop. To fix that you could use racket:#%app in both outputs, like #'(racket:#%app + Value1 ... Value2).

(define-syntax-parser #%app
  [(_ {~seq Value1 {~datum +}} ...+ Value2)
   #'(racket:#%app + Value1 ... Value2)]
  [(_ Xs ...)
   #'(racket:#%app Xs ...)])


问:
Unable to override AttachBaseContext() in xamarin android
I tried to use this method.

```<code>protected override void AttachBaseContext(context @base)
{
    Context con = LanguageManager.NewLocale(@base,
    LanguageManager.SelectNewLanguage(@base));
    base.AttachBaseContext(@base));
}
</code>```

When I run my app it got crash automatically.

答:
As you provide less information, if you want to make a function which could change language
in your application.

1.the LanguageManager class

```<code>internal class LanguageManager
{
    private const string MYLANGUAGE = "myLanguage";
    private const string MYPREF = "myPreference";

    public static Context LoadLanguage(Context context)
    {
        var loadedLanguage = GetLanguage(context, Locale.Default.Language);
        return ChangeLanguage(context, loadedLanguage);
    }

    public static Context ChangeLanguage(Context context, string language)
    {
        SaveLanguage(context, language);
        if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
        {
            return ChangeForAPI24(context, language);
        }
        return ChangeForLegacy(context, language);
    }

    private static string GetLanguage(Context context, string Language)
    {
        var privatePreference = context.GetSharedPreferences(MYPREF, FileCreationMode.Private);
        return privatePreference.GetString(MYLANGUAGE, Language);
    }

    private static void SaveLanguage(Context context, string language)
    {
        var privatePreference = context.GetSharedPreferences(MYPREF, FileCreationMode.Private);
        var editor = privatePreference.Edit();
        editor.PutString(MYLANGUAGE, language);
        editor.Apply();
    }

    private static Context ChangeForAPI24(Context context, string language)
    {
        // for api >= 24
        var locale = new Locale(language);
        Locale.Default = locale;
        var configuration = context.Resources.Configuration;
        configuration.SetLocale(locale);
        configuration.SetLayoutDirection(locale);

        return context.CreateConfigurationContext(configuration);
    }

    private static Context ChangeForLegacy(Context context, string language)
    {
        var locale = new Locale(language);
        Locale.Default = locale;
        var resources = context.Resources;
        var configuration = resources.Configuration;
        configuration.Locale = locale;
        resources.UpdateConfiguration(configuration, resources.DisplayMetrics);
        return context;
    }
}
</code>```

2.MainActivity which includes a TextView and a Button;

3.in BaseActivity

```<code>public class BaseActivity: AppCompatActivity
{
    protected override void AttachBaseContext(Context @base)
    {
        base.AttachBaseContext(LanguageManager.LoadLanguage(@base));
    }

}
</code>```

4.in SettingActivity which could set the language,the axml similar to yours

```<code>public class SettingActivity : BaseActivity, CompoundButton.IOnCheckedChangeListener
{
    private Switch swCh;
    private Switch swEn;
    private Switch swTh;
    private Bundle s;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.setting);
        // Create your application here
        initView();
    }

    private void initView()
    {
        Button back = FindViewById<Button>(Resource.Id.back);
        back.Click += delegate { Finish(); };
        swCh = FindViewById<Switch>(Resource.Id.switch1);
        swEn = FindViewById<Switch>(Resource.Id.switch2);
        swTh = FindViewById<Switch>(Resource.Id.switch3);
        var s = GetSharedPreferences("myPreference", FileCreationMode.Private).GetString( "myLanguage", Locale.Default.Language);
        switch (s)
        {
            case "ch":
                swCh.Checked = true;
                break;
            case "en":
                swEn.Checked = true;
                break;
            case "th":
                swTh.Checked = true;
                break;
        }
        swCh.SetOnCheckedChangeListener(this);
        swEn.SetOnCheckedChangeListener(this);
        swTh.SetOnCheckedChangeListener(this);
    }

    public void OnCheckedChanged(CompoundButton buttonView, bool isChecked)
    {
        if (isChecked)
        {

        switch (buttonView.Id)
        {
            case Resource.Id.switch1:
                swEn.Checked = false;
                swTh.Checked = false;
                LanguageManager.ChangeLanguage(this, "ch");
                break;
            case Resource.Id.switch2:
                swCh.Checked = false;
                swTh.Checked = false;
                LanguageManager.ChangeLanguage(this, "en");
                    break;
            case Resource.Id.switch3:
                swEn.Checked = false;
                swCh.Checked = false;
                LanguageManager.ChangeLanguage(this, "th");
                    break;
        }
             //restart application to change language
            Intent intent = new Intent(this, typeof(MainActivity));
            intent.SetFlags(ActivityFlags.ClearTask | ActivityFlags.NewTask);
            StartActivity(intent);
        }
    }

}
</code>```

you could refer to here

Body:
I tried to use this method.

protected override void AttachBaseContext(context @base)
{
    Context con = LanguageManager.NewLocale(@base,
    LanguageManager.SelectNewLanguage(@base));
    base.AttachBaseContext(@base));
}

When I run my app it got crash automatically.

Body:
As you provide less information, if you want to make a function which could change language
in your application.

1.the LanguageManager class

internal class LanguageManager
{
    private const string MYLANGUAGE = "myLanguage";
    private const string MYPREF = "myPreference";

    public static Context LoadLanguage(Context context)
    {
        var loadedLanguage = GetLanguage(context, Locale.Default.Language);
        return ChangeLanguage(context, loadedLanguage);
    }

    public static Context ChangeLanguage(Context context, string language)
    {
        SaveLanguage(context, language);
        if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
        {
            return ChangeForAPI24(context, language);
        }
        return ChangeForLegacy(context, language);
    }

    private static string GetLanguage(Context context, string Language)
    {
        var privatePreference = context.GetSharedPreferences(MYPREF, FileCreationMode.Private);
        return privatePreference.GetString(MYLANGUAGE, Language);
    }

    private static void SaveLanguage(Context context, string language)
    {
        var privatePreference = context.GetSharedPreferences(MYPREF, FileCreationMode.Private);
        var editor = privatePreference.Edit();
        editor.PutString(MYLANGUAGE, language);
        editor.Apply();
    }

    private static Context ChangeForAPI24(Context context, string language)
    {
        // for api >= 24
        var locale = new Locale(language);
        Locale.Default = locale;
        var configuration = context.Resources.Configuration;
        configuration.SetLocale(locale);
        configuration.SetLayoutDirection(locale);

        return context.CreateConfigurationContext(configuration);
    }

    private static Context ChangeForLegacy(Context context, string language)
    {
        var locale = new Locale(language);
        Locale.Default = locale;
        var resources = context.Resources;
        var configuration = resources.Configuration;
        configuration.Locale = locale;
        resources.UpdateConfiguration(configuration, resources.DisplayMetrics);
        return context;
    }
}

2.MainActivity which includes a TextView and a Button;

3.in BaseActivity

public class BaseActivity: AppCompatActivity
{
    protected override void AttachBaseContext(Context @base)
    {
        base.AttachBaseContext(LanguageManager.LoadLanguage(@base));
    }

}

4.in SettingActivity which could set the language,the axml similar to yours

public class SettingActivity : BaseActivity, CompoundButton.IOnCheckedChangeListener
{
    private Switch swCh;
    private Switch swEn;
    private Switch swTh;
    private Bundle s;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.setting);
        // Create your application here
        initView();
    }

    private void initView()
    {
        Button back = FindViewById<Button>(Resource.Id.back);
        back.Click += delegate { Finish(); };
        swCh = FindViewById<Switch>(Resource.Id.switch1);
        swEn = FindViewById<Switch>(Resource.Id.switch2);
        swTh = FindViewById<Switch>(Resource.Id.switch3);
        var s = GetSharedPreferences("myPreference", FileCreationMode.Private).GetString( "myLanguage", Locale.Default.Language);
        switch (s)
        {
            case "ch":
                swCh.Checked = true;
                break;
            case "en":
                swEn.Checked = true;
                break;
            case "th":
                swTh.Checked = true;
                break;
        }
        swCh.SetOnCheckedChangeListener(this);
        swEn.SetOnCheckedChangeListener(this);
        swTh.SetOnCheckedChangeListener(this);
    }

    public void OnCheckedChanged(CompoundButton buttonView, bool isChecked)
    {
        if (isChecked)
        {

        switch (buttonView.Id)
        {
            case Resource.Id.switch1:
                swEn.Checked = false;
                swTh.Checked = false;
                LanguageManager.ChangeLanguage(this, "ch");
                break;
            case Resource.Id.switch2:
                swCh.Checked = false;
                swTh.Checked = false;
                LanguageManager.ChangeLanguage(this, "en");
                    break;
            case Resource.Id.switch3:
                swEn.Checked = false;
                swCh.Checked = false;
                LanguageManager.ChangeLanguage(this, "th");
                    break;
        }
             //restart application to change language
            Intent intent = new Intent(this, typeof(MainActivity));
            intent.SetFlags(ActivityFlags.ClearTask | ActivityFlags.NewTask);
            StartActivity(intent);
        }
    }

}

you could refer to here


问:
How to iterate/foreach array in SwiftUI
I have this array of dictionaries.

```<code>let deckColors = [
    ["name": "blue", "desc": "desc1"],
    ["name": "yellow", "desc": "desc2"],
]
</code>```

And my view:

```<code>struct ContentView: View {
    var body: some View {
        ForEach(0 ..< deckColors.count) {value in
            Text(deckColors[value]["name"])
        }
    }
}
</code>```

How can I make it work? Currently getting this error: Protocol type Any cannot conform to StringProtocol because only concrete types can conform to protocols

答:
I would put your deck colors into an enum and then iterate on that. </p>

```<code>enum DeckColor: String, CaseIterable {
    case blue
    case yellow

    var desc: String {
        switch self {
            case .blue: return "desc1"
            case .yellow: return "desc2"
        }
    }
}

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading) {
            ForEach(DeckColor.allCases, id: \.self) { color in
                Text(color.rawValue)
            }
        }
    }
}
</code>```

Title: How to iterate/foreach array in SwiftUI

Body:
I have this array of dictionaries.

let deckColors = [
    ["name": "blue", "desc": "desc1"],
    ["name": "yellow", "desc": "desc2"],
]

And my view:

struct ContentView: View {
    var body: some View {
        ForEach(0 ..< deckColors.count) {value in
            Text(deckColors[value]["name"])
        }
    }
}

How can I make it work? Currently getting this error: Protocol type Any cannot conform to StringProtocol because only concrete types can conform to protocols

Body:
I would put your deck colors into an enum and then iterate on that.

enum DeckColor: String, CaseIterable {
    case blue
    case yellow

    var desc: String {
        switch self {
            case .blue: return "desc1"
            case .yellow: return "desc2"
        }
    }
}

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading) {
            ForEach(DeckColor.allCases, id: \.self) { color in
                Text(color.rawValue)
            }
        }
    }
}


问:
I have a button I need to turn color on fist click and change back to original color on second click
I can get the button change color on first click but not on second click. Not sure how to execute. Console log to true as expected.</p>

```<code>        var clicked = true,

            button = document.getElementById("buttonProps");

        button.addEventListener("click", function () {

            if (clicked) {
                this.style.backgroundColor = "skyblue";
            } else {

                this.style.backgroundColor = "lightgray";
            }

        });
        console.log(clicked)
</code>```

答:
You need to toggle the clicked variable

var clicked = true

button = document.getElementById("buttonProps");

button.addEventListener("click", function() {

  if (clicked) {
    this.style.backgroundColor = "skyblue";
  } else {
    this.style.backgroundColor = "lightgray";
  }
  clicked = !clicked

});
console.log(clicked)
```

Body:
I can get the button change color on first click but not on second click. Not sure how to execute. Console log to true as expected.

        var clicked = true,

            button = document.getElementById("buttonProps");

        button.addEventListener("click", function () {

            if (clicked) {
                this.style.backgroundColor = "skyblue";
            } else {

                this.style.backgroundColor = "lightgray";
            }

        });
        console.log(clicked)


问:
Obtaining XPATH for Selenium
In a previous question
a user provides the following solution to the problem.

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='title
login_title' and text()='Login']//following::div[1]//input[@class='text header_login_text_box
ignore_interaction']"))).send_keys("someemail@email.com")

</code>```

However, when I go into my chrome inspect element, I get the following XPATH by going copy>XPATH, which when added like the following, no longer works. It also doesn't give an error, just no email is typed into the box.

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='__w2_wHsckeIm21_email']"))).send_keys("someemail@email.com")
</code>```

What's the difference between the two? Why does only the first one work and how do I obtain this long working version of xpath.

答:
First of all you don't need such a long xpath to locate the email element. Simply you can use

```<code>//form[@class='inline_login_form']//input[@name='email']
</code>```

And I don't recommend using id to identify in this case as it's dynamic (meaning the id will change each time you navigate to this page). So it's not a good idea to use the id to locate the element.

There are multiple ways to write locator for this element like

//form[@class='inline_login_form']//input[@name='email']

//input[@name='email'][@class='text header_login_text_box ignore_interaction']

//input[@name='email'][starts-with(@class,'text header_login_text_box')]

I don't want to keep on giving all the possible options. The idea I chosen the //form[@class='inline_login_form']//input[@name='email'] is, it's clear that I am locating the input element with name email under form. If you try to locate the element with only //input[@name='email'], then there are 2 elements and Selenium will pick the first element (which we don't want this case) and it's not intractable.

If you want to learn more about xpath and how to develop the correct xpath for your target element refer to this post

Title: Obtaining XPATH for Selenium

Body:
In a previous question
a user provides the following solution to the problem.

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='title
login_title' and text()='Login']//following::div[1]//input[@class='text header_login_text_box
ignore_interaction']"))).send_keys("someemail@email.com")

However, when I go into my chrome inspect element, I get the following XPATH by going copy>XPATH, which when added like the following, no longer works. It also doesn't give an error, just no email is typed into the box.

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='__w2_wHsckeIm21_email']"))).send_keys("someemail@email.com")

What's the difference between the two? Why does only the first one work and how do I obtain this long working version of xpath.

Body:
First of all you don't need such a long xpath to locate the email element. Simply you can use

//form[@class='inline_login_form']//input[@name='email']

And I don't recommend using id to identify in this case as it's dynamic (meaning the id will change each time you navigate to this page). So it's not a good idea to use the id to locate the element.

There are multiple ways to write locator for this element like

//form[@class='inline_login_form']//input[@name='email']

//input[@name='email'][@class='text header_login_text_box ignore_interaction']

//input[@name='email'][starts-with(@class,'text header_login_text_box')]

I don't want to keep on giving all the possible options. The idea I chosen the //form[@class='inline_login_form']//input[@name='email'] is, it's clear that I am locating the input element with name email under form. If you try to locate the element with only //input[@name='email'], then there are 2 elements and Selenium will pick the first element (which we don't want this case) and it's not intractable.

If you want to learn more about xpath and how to develop the correct xpath for your target element refer to this post


问:
Need help determining how to approach building my project
I'd like to create something similar to a family tree online app (like geni.com). I'm unsure what languages I should use to build it with. My IT strong points aren't in programming and this project is going to require me to sit down and learn some languages. My problem right now is that I don't know what languages I should use.

So with the idea of a family tree online app in mind here are some of the specifications.
- I do not want to use flash.
- The app needs to be zoomable and scrollable (sort of like google maps)
- The app needs to be able to add content without reloading the page. Perhaps there's a little "+" sign and when I click it, I can add a tag/title/description/picture
- The app needs to be able to save your work for that user to retrieve later on.
- The layout that a user is able to create in is sort of widget based where the user can add a new bubble and then in that bubble they are able to add text or content.

I started programming this with HTML5 canvas and Javascript, but I'm stuck on creating a connection to the database that isn't directly from Javascript (because that seems very insecure to me). But I'm not just stumped on how to interact securely with the database (I don't even have a database picked out), but also I'm concerned that I won't be able to build out the app with just javascript and may need something else like ajax or something but I'm unfamiliar with what each language does nowadays.

答:
As someone has already pointed out, you will need to work with a server side language as well. (Ruby, Python, PHP)  You are exactly right there you should not be attempting a database connection via javascript in the browser.

You'll need to build out a server side application to handle the basic operations of your application.

I'd strongly recommend reading up on the MVC design pattern, and possibly looking into Ruby on Rails as your backend framework, it plays very nicely with ajax like features, and has a somewhat shorter learning curve, I believe, than some other frameworks / languages.


问:
How to display props in the html format in React function component?
Want to pass customized html element into function component, but seems it's treated as plain string.

```<code><html>
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

<body>

<div id="mydiv"></div>
<script type="text/babel" src="t21.js"></script>

</body>
</html>
</code>```

The js file is

```<code>const InfoMsg = (props) => {
    return <div>
        {props.parm}
        </div>;
}

const Hello = (props) => {
        console.log(props);
        let divElem;

        switch (props.type)
        {
            case 'info':
                divElem = InfoMsg(props);
                break;
        }

    return divElem;
}

ReactDOM.render(<Hello type='info' parm='<h2>info</h2>' />, document.getElementById('mydiv'));
</code>```

How to let InfoMsg return

info

 ? Right now it's returning
"
info
"
.

答:
You are passing it through as a string.

Therefor it will display as a string.

You can try: dangerouslySetInnerHTML option.

Or you could pass it through as a dom object.

```<code><Hello type='info' parm={<h2>info</h2>} />
</code>```

Body:
Want to pass customized html element into function component, but seems it's treated as plain string.

The js file is

const InfoMsg = (props) => {
    return

        {props.parm}

;
}

const Hello = (props) => {
        console.log(props);
        let divElem;

        switch (props.type)
        {
            case 'info':
                divElem = InfoMsg(props);
                break;
        }

    return divElem;
}

ReactDOM.render(<Hello type='info' parm='
info
' />, document.getElementById('mydiv'));

How to let InfoMsg return

info

 ? Right now it's returning
"
info
"
.

Body:
You are passing it through as a string.

Therefor it will display as a string.

You can try: dangerouslySetInnerHTML option.

Or you could pass it through as a dom object.

<Hello type='info' parm={<h2>info</h2>} />


问:
NVIDIA-SMI failed. Could'nt communicate with Nvidia driver
I am running a cloud instance on a gpu node. I installed CUDA and nvidia-smi showed the driver details, memory utlilization. After a couple of days, I face this error
"NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running".

I installed the latest driver (Nvidia-375.39 for Tesla M40 Gpus). I still face the same issue. Is there any way to
i) debug why nvidia-smi is not able to communicate with the driver?
ii)check if the driver is running properly.

答:
This is an operating system issue. The solution will depend on your operating system. For example, if you are running Ubuntu 16 the solution might be something like this:

Uninstall / purge all Nvidia drivers

```<code>sudo apt-get remove --purge nvidia* && sudo apt autoremove
</code>```

Download Nvidia driver from Nvidia's website (.run file)

Body:
This is an operating system issue. The solution will depend on your operating system. For example, if you are running Ubuntu 16 the solution might be something like this:

Uninstall / purge all Nvidia drivers

sudo apt-get remove --purge nvidia* && sudo apt autoremove

Download Nvidia driver from Nvidia's website (.run file)


问:
Why do we need TLSNotary in Blockchain?
Using HTTPS, we could actually get the certificate and the public key of google.

In the case that we do not care about privacy. How about letting the smart contract to check the signature of the data sent by a website.

A simpler solution: Maybe hard code the public key of the data source into the smart contract?

答:
Your idea is reasonable, and has been invented in 2015 by Emercoin team.

emerSSL already stores in the blockchain hash of user's SSL-certificate. And this system already works in production, for example, on Livecoin exhcange.

Title: Why do we need TLSNotary in Blockchain?


问:
How to put a SQL Query Output as a excel file to Azure Data Lake in SSIS
So basically, I want to get all this done in the SSIS package itself.

```<code>SQL Query output -> Convert to Excel file without any local files -> Upload to Azure Blob.
</code>```

The "azure blob destination" has only the options for CSV, etc. But nothing to directly make it excel.

Converting it to excel require a local file as there excel file destination has only system file options.

If there is any way to get the output as excel file directly instead of CSV, then upload to Azure Blob.

Any help would be appreciated. Thanks.

答:
In SSIS, we can not put a SQL Query Output as a excel file to Azure Data Lake without using a local excel file.

Not only SSIS does't support do this, we can't find any other tools or scripts can achieve that.

Hope this helps.

Body:
So basically, I want to get all this done in the SSIS package itself.

SQL Query output -> Convert to Excel file without any local files -> Upload to Azure Blob.

The "azure blob destination" has only the options for CSV, etc. But nothing to directly make it excel.

Converting it to excel require a local file as there excel file destination has only system file options.

If there is any way to get the output as excel file directly instead of CSV, then upload to Azure Blob.

Any help would be appreciated. Thanks.


问:
How can curl perform a get request with a data payload?
The introductory materials on ElasticSearch include the following example curl request:

```<code>curl -X GET "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
    "query": {
        "query_string" : {
            "query" : "(new york city) OR (big apple)",
            "default_field" : "content"
        }
    }
}
'
</code>```

This request has two parameter which I thought were incompatible:

-X GET, which specifies that the request is a GET.

-d [...], which specifies that the request has a data payload.

I thought that specifying a data payload was only possible in a PUT or POST requests, because GET requests do not have any concept of a data payload. Is this a valid curl command? What does it do, exactly?

答:
Above curl request is a valid request, in fact, if you have index and data, then you can check the output of your command.

I tried it in my system and ES index and it gave me proper response.

```<code>curl -v -X GET "localhost:9500/querytime/_search?pretty" -H 'Content-Type: application/json' -d'
{
    "query": {
        "query_string" : {
            "query" : "(avengers) OR (big apple)",
            "default_field" : "movie_name"
        }
    }
}'
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 9500 (#0)
> GET /querytime/_search?pretty HTTP/1.1
> Host: localhost:9500
> User-Agent: curl/7.64.1
> Accept: */*
> Content-Type: application/json
> Content-Length: 156
>
* upload completely sent off: 156 out of 156 bytes
< HTTP/1.1 200 OK
< content-type: application/json; charset=UTF-8
< content-length: 905
<
{
  "took" : 4,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 3,
      "relation" : "eq"
    },
    "max_score" : 0.14874382,
    "hits" : [
      {
        "_index" : "querytime",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 0.14874382,
        "_source" : {
          "movie_name" : "Avengers: Infinity War"
        }
      }
    ]
  }
}
</code>```

As mentioned in the official manual of curl command, if you are using *nix based system, then you can search below in the manual of curl.

-G, --get
                When  used,  this option will make all data specified with -d, --data, --data-binary or --data-urlencode to be used in an
  HTTP GET request instead of the POST request that otherwise would be
  used. The
                data will be appended to the URL with a '?' separator

As explained in this SO answer, it also depends on the web-server to parse the body in GET request.

Body:
The introductory materials on ElasticSearch include the following example curl request:

curl -X GET "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
    "query": {
        "query_string" : {
            "query" : "(new york city) OR (big apple)",
            "default_field" : "content"
        }
    }
}
'

This request has two parameter which I thought were incompatible:

-X GET, which specifies that the request is a GET.

-d [...], which specifies that the request has a data payload.

I thought that specifying a data payload was only possible in a PUT or POST requests, because GET requests do not have any concept of a data payload. Is this a valid curl command? What does it do, exactly?

Body:
Above curl request is a valid request, in fact, if you have index and data, then you can check the output of your command.

I tried it in my system and ES index and it gave me proper response.

curl -v -X GET "localhost:9500/querytime/_search?pretty" -H 'Content-Type: application/json' -d'
{
    "query": {
        "query_string" : {
            "query" : "(avengers) OR (big apple)",
            "default_field" : "movie_name"
        }
    }
}'
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 9500 (#0)
> GET /querytime/_search?pretty HTTP/1.1
> Host: localhost:9500
> User-Agent: curl/7.64.1
> Accept: */*
> Content-Type: application/json
> Content-Length: 156
>
* upload completely sent off: 156 out of 156 bytes
< HTTP/1.1 200 OK
< content-type: application/json; charset=UTF-8
< content-length: 905
<
{
  "took" : 4,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 3,
      "relation" : "eq"
    },
    "max_score" : 0.14874382,
    "hits" : [
      {
        "_index" : "querytime",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 0.14874382,
        "_source" : {
          "movie_name" : "Avengers: Infinity War"
        }
      }
    ]
  }
}

As mentioned in the official manual of curl command, if you are using *nix based system, then you can search below in the manual of curl.

-G, --get
                When  used,  this option will make all data specified with -d, --data, --data-binary or --data-urlencode to be used in an
  HTTP GET request instead of the POST request that otherwise would be
  used. The
                data will be appended to the URL with a '?' separator

As explained in this SO answer, it also depends on the web-server to parse the body in GET request.


问:
Why does Keras model.predict never execute on this simple machine learning model I've setup?
```<code>import numpy as np
import keras as ks

model = ks.Sequential([ks.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')

xs=np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype = float)
ys=np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype = float)

model.fit(xs, ys, epochs=500)

print(model.predict([10.0]))
</code>```

The model.predict never executes no matter how long I wait. What tests can I do to diagnose the problem? What questions should I be asking myself to find the issue?

答:
I went back and fixed my build?

First I reinstalled tensorflow. My original command was:

```<code>pip install tensorflow-gpu==2.0
</code>```

Which I did an install using the following:

```<code>pip install tensorflow
</code>```

And then I made sure to follow the following steps for Windows.

https://docs.nvidia.com/deeplearning/sdk/cudnn-install/index.html

Body:
import numpy as np
import keras as ks

model = ks.Sequential([ks.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')

xs=np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype = float)
ys=np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype = float)

model.fit(xs, ys, epochs=500)

print(model.predict([10.0]))

The model.predict never executes no matter how long I wait. What tests can I do to diagnose the problem? What questions should I be asking myself to find the issue?

Body:
I went back and fixed my build?

First I reinstalled tensorflow. My original command was:

pip install tensorflow-gpu==2.0

Which I did an install using the following:

pip install tensorflow

And then I made sure to follow the following steps for Windows.

https://docs.nvidia.com/deeplearning/sdk/cudnn-install/index.html


问:
Selecting data from both current and previous records
I'd like my query to return a list of "churned" accounts, meaning existing account_ids in the below table with the latest record of plan_id = 4. This represents a once paying account no longer paying, or "churning."

With that, I need to include the previous value for the account's plan_id and calculate the monthly revenue lost from the account's previous price.

Here's an example of what the schema looks like when I join the two tables I'm using. (You'll notice accounts with plan_id = 4 have NULL metadata because they don't have revenue.):

```<code>| account_id | plan_id | start_date           | plan_interval | price  | id     |
|------------|---------|----------------------|---------------|--------|--------|
| 2          | 1       | 2018-01-03T14:52:13Z | month         | 39     | 1      |
| 1          | 3       | 2018-02-07T11:10:17Z | year          | 999    | 3      |
| 1          | 2       | 2018-02-07T11:11:17Z | month         | 99     | 2      |
| 2          | 4       | 2018-03-25T07:09:00Z | (null)        | (null) | (null) |
</code>```

I would like the output to be this, grouped on the month and previous_plan_id:

```<code>| month | previous_plan_id | num_churned | monthly_revenue_churned (mrr) |
|-------|------------------|-------------|-------------------------------|
| 3     | 3                | 1           | 83.25                         |
</code>```

So far, I've compiled this query. I still need to pull the previous plan_id when an account_id moves to plan_id = 4, and the previous price for that churned account (calculated as monthly revenue or "mrr").

```<code>SELECT
MONTH(s.start) AS month,
s.plan_id,
COUNT(*) AS num_churned,
SUM(CASE WHEN p.plan_interval = 'month'
     THEN p.price * 0.01
     ELSE (p.price * 0.01)/12 END) AS mrr
FROM subscriptions s
  LEFT JOIN plans p
  ON p.id = s.plan_id
WHERE s.start = (SELECT MAX(s2.start)
                  FROM subscriptions s2
                  WHERE s.plan_id = 4)
      AND s.school_id > 1 IN (SELECT COUNT(DISTINCT s.school_id)
                          FROM subscriptions)
GROUP BY month, s.plan_id;
</code>```

I think perhaps a LAG clause would work but my question is: what can I add to this query to achieve the desired output?

Here's an example: sqlfiddle

答:
I'm not sure what your calculations are really supposed to be -- the data in your fiddle does not match the data in the question.  But you can do something like this:

```<code>select s.*, p.price / 12
from (select s.*,
             lag(plan_id) over (partition by account_id order by start_date) as prev_plan_id,
             lag(start_date) over (partition by account_id order by start_date) as prev_start_date
      from subscriptions s
     ) s join
     plans p
     on s.prev_plan_id = p.id
where plan_id = 4 and prev_plan_id <> 4;
</code>```

Here is a db<>fiddle, which supports more recent versions of MySQL.

Body:
I'd like my query to return a list of "churned" accounts, meaning existing account_ids in the below table with the latest record of plan_id = 4. This represents a once paying account no longer paying, or "churning."

With that, I need to include the previous value for the account's plan_id and calculate the monthly revenue lost from the account's previous price.

Here's an example of what the schema looks like when I join the two tables I'm using. (You'll notice accounts with plan_id = 4 have NULL metadata because they don't have revenue.):

| account_id | plan_id | start_date           | plan_interval | price  | id     |
|------------|---------|----------------------|---------------|--------|--------|
| 2          | 1       | 2018-01-03T14:52:13Z | month         | 39     | 1      |
| 1          | 3       | 2018-02-07T11:10:17Z | year          | 999    | 3      |
| 1          | 2       | 2018-02-07T11:11:17Z | month         | 99     | 2      |
| 2          | 4       | 2018-03-25T07:09:00Z | (null)        | (null) | (null) |

I would like the output to be this, grouped on the month and previous_plan_id:

| month | previous_plan_id | num_churned | monthly_revenue_churned (mrr) |
|-------|------------------|-------------|-------------------------------|
| 3     | 3                | 1           | 83.25                         |

So far, I've compiled this query. I still need to pull the previous plan_id when an account_id moves to plan_id = 4, and the previous price for that churned account (calculated as monthly revenue or "mrr").

SELECT
MONTH(s.start) AS month,
s.plan_id,
COUNT(*) AS num_churned,
SUM(CASE WHEN p.plan_interval = 'month'
     THEN p.price * 0.01
     ELSE (p.price * 0.01)/12 END) AS mrr
FROM subscriptions s
  LEFT JOIN plans p
  ON p.id = s.plan_id
WHERE s.start = (SELECT MAX(s2.start)
                  FROM subscriptions s2
                  WHERE s.plan_id = 4)
      AND s.school_id > 1 IN (SELECT COUNT(DISTINCT s.school_id)
                          FROM subscriptions)
GROUP BY month, s.plan_id;

I think perhaps a LAG clause would work but my question is: what can I add to this query to achieve the desired output?

Here's an example: sqlfiddle

Body:
I'm not sure what your calculations are really supposed to be -- the data in your fiddle does not match the data in the question.  But you can do something like this:

select s.*, p.price / 12
from (select s.*,
             lag(plan_id) over (partition by account_id order by start_date) as prev_plan_id,
             lag(start_date) over (partition by account_id order by start_date) as prev_start_date
      from subscriptions s
     ) s join
     plans p
     on s.prev_plan_id = p.id
where plan_id = 4 and prev_plan_id <> 4;

Here is a db<>fiddle, which supports more recent versions of MySQL.


问:
Call an async function again and again until expected result in Node JS
Let's say I have 4 tasks

Take a screenshot of a website (using some API service)

Download the screenshot to your local hardDrive

Upload the screenshot from the local hardDrive to a Google Cloud Bucket

Use GC-Vision API to detect text on that screenshot

If the result of task #4 is equal to -1, that means I didn't find what I'm looking for, so I need to do this all over again until the result doesn't equal -1 (which probably means I found what I need).

Now some code:

```<code>const screenshot = require("./thum/takeScreenshot");
const googleVisionAPI = require("./gc-vision-api/findTextInButton");
const matchURL = /^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$/;
const UploadToGcBucket = require("./gc-storage/saveScreenshot");
const downloadImage = require("./downloadFile");

// let's wait for the bucket to replicate before searching text
function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

const workHard = async () => {
  // 1. Take a screenshot
  const takeAscreenShot = async () => {
    let scShotTaken = await `https:${screenshot.thumURL}`;
    console.log("screenshot captured!!! ", scShotTaken);
    return scShotTaken;
  };

  //  2. Download it to local hard-drive
  const downloadScreenshot = async url => {
    let download = await downloadImage.downloadImage(url);
    return download;
  };

  // 3. Upload it to Google Cloud Bucket
  const uploadToGCBucket = async () => {
    let upload = await UploadToGcBucket.UploadToGcBucket();
    return upload;
  };

  // 4. Check if the appointment's button is present
  const checkMagicButton = async () => {
    // wait a little bit for replication
    await timeout(5000);

    let searchAppointment = await googleVisionAPI.findMagicButton(
      `some_picture_in_a_cloud_bucket.jpg`
    );
    return searchAppointment;
  };

  takeAscreenShot()
    .then(pic => {
      // Verify if it looks like a URL
      let verifyURL = matchURL.test(pic);

      if (!verifyURL) {
        return "The screenshot doesn't look like a valid URL, check the Thumb API";
      }

      downloadScreenshot(pic)
        .then(() => {
          uploadToGCBucket()
            .then(() => {
              checkMagicButton()
                .then(button => {
                  if (button === -1) {
                    throw new Error();
                  }
                })
                .catch(makeCatch("AI finding button ERROR"));
            })
            .catch(makeCatch("Uploading to GC Bucket ERROR"));
        })
        .catch(makeCatch("Downloading ERROR"));
    })
    .catch(makeCatch("ScreenShot ERROR"));
};

const makeCatch = msg => err => {
  console.log("Problem with " + msg, err);
  throw new Error(); // this is important- this rejects the Promise, so it stops the hardWork
};

const tryWork = () => {
  workHard().catch(error => {
    setInterval(tryWork, 5000);
  });
};

tryWork();

</code>```

so...how do I call HardWork() all over again let's say in 5 minutes if I don't find what I need.

答:
You're using async functions already, and everything looks Promise-based already, so you can make hardWork async and then await each Promise inside of it. If final task fails, reject. In the caller of hardWork, if the Promise ultimately rejects, set a timeout to call it again in 5 minutes, otherwise you're done:

```<code>const hardWork = async () => {
  // I assume this next line was psuedo-code for an API call or something
  await `https:${screenshot.thumURL}`;

  const image = await downloadImage.downloadImage();
  await UploadToGcBucket.UploadToGcBucket(image);
  await timeout(5000);
  const button = await googleVisionAPI.findMagicButton(`some_screenshot.jpg`);
  if (button === -1) {
    throw new Error();
  }
  // success
};

const tryWork = () => {
  hardWork()
    .catch((error) => {
      setTimeout(tryWork, 5 * 60 * 1000); // 5 minutes
    });
};
tryWork();
</code>```

If you need different error messages for the different possible errors, I'd make a higher-order function that you can pass into .catch that  logs the message, to keep the code DRY:

```<code>const makeCatch = msg => (err) => {
  console.log('Problem with ' + msg, err);
  throw new Error(); // this is important- this rejects the Promise, so it stops the hardWork
};

// ...

await downloadImage.downloadImage()
  .catch(makeCatch('downloadImage'));
await UploadToGcBucket.UploadToGcBucket(image)
  .catch(makeCatch('upload to gc'));
await timeout(5000);
const button = await googleVisionAPI.findMagicButton(`some_screenshot.jpg`)
  .catch(makeCatch('findButton'));
</code>```

Live snippet:

// dummied up API calls below...
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
const downloadImage = () => new Promise(resolve => setTimeout(resolve, 200));
const uploadToGcBucket = () => new Promise(resolve => setTimeout(resolve, 200));
// the below function will resolve to -1 70% of the time, and to 0 30% of the time
const findMagicButton = () => new Promise(resolve => setTimeout(resolve, 200, Math.floor(Math.random() - 0.7)));
// dummied up API calls above...

const hardWork = async () => {
  const image = await downloadImage();
  await uploadToGcBucket(image);
  await timeout(500);
  const button = await findMagicButton(`some_screenshot.jpg`);
  if (button === -1) {
    throw new Error();
  }
  console.log('success');
};

const tryWork = () => {
  hardWork()
    .catch((error) => {
      console.log('failure, retry');
      setTimeout(tryWork, 2 * 1000); // 2 seconds
    });
};
console.log('start');
tryWork();```

Body:
Let's say I have 4 tasks

Take a screenshot of a website (using some API service)

Download the screenshot to your local hardDrive

Upload the screenshot from the local hardDrive to a Google Cloud Bucket

Use GC-Vision API to detect text on that screenshot

If the result of task #4 is equal to -1, that means I didn't find what I'm looking for, so I need to do this all over again until the result doesn't equal -1 (which probably means I found what I need).

Now some code:

const screenshot = require("./thum/takeScreenshot");
const googleVisionAPI = require("./gc-vision-api/findTextInButton");
const matchURL = /^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$/;
const UploadToGcBucket = require("./gc-storage/saveScreenshot");
const downloadImage = require("./downloadFile");

// let's wait for the bucket to replicate before searching text
function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

const workHard = async () => {
  // 1. Take a screenshot
  const takeAscreenShot = async () => {
    let scShotTaken = await `https:${screenshot.thumURL}`;
    console.log("screenshot captured!!! ", scShotTaken);
    return scShotTaken;
  };

  //  2. Download it to local hard-drive
  const downloadScreenshot = async url => {
    let download = await downloadImage.downloadImage(url);
    return download;
  };

  // 3. Upload it to Google Cloud Bucket
  const uploadToGCBucket = async () => {
    let upload = await UploadToGcBucket.UploadToGcBucket();
    return upload;
  };

  // 4. Check if the appointment's button is present
  const checkMagicButton = async () => {
    // wait a little bit for replication
    await timeout(5000);

    let searchAppointment = await googleVisionAPI.findMagicButton(
      `some_picture_in_a_cloud_bucket.jpg`
    );
    return searchAppointment;
  };

  takeAscreenShot()
    .then(pic => {
      // Verify if it looks like a URL
      let verifyURL = matchURL.test(pic);

      if (!verifyURL) {
        return "The screenshot doesn't look like a valid URL, check the Thumb API";
      }

      downloadScreenshot(pic)
        .then(() => {
          uploadToGCBucket()
            .then(() => {
              checkMagicButton()
                .then(button => {
                  if (button === -1) {
                    throw new Error();
                  }
                })
                .catch(makeCatch("AI finding button ERROR"));
            })
            .catch(makeCatch("Uploading to GC Bucket ERROR"));
        })
        .catch(makeCatch("Downloading ERROR"));
    })
    .catch(makeCatch("ScreenShot ERROR"));
};

const makeCatch = msg => err => {
  console.log("Problem with " + msg, err);
  throw new Error(); // this is important- this rejects the Promise, so it stops the hardWork
};

const tryWork = () => {
  workHard().catch(error => {
    setInterval(tryWork, 5000);
  });
};

tryWork();

so...how do I call HardWork() all over again let's say in 5 minutes if I don't find what I need.

Body:
You're using async functions already, and everything looks Promise-based already, so you can make hardWork async and then await each Promise inside of it. If final task fails, reject. In the caller of hardWork, if the Promise ultimately rejects, set a timeout to call it again in 5 minutes, otherwise you're done:

const hardWork = async () => {
  // I assume this next line was psuedo-code for an API call or something
  await `https:${screenshot.thumURL}`;

  const image = await downloadImage.downloadImage();
  await UploadToGcBucket.UploadToGcBucket(image);
  await timeout(5000);
  const button = await googleVisionAPI.findMagicButton(`some_screenshot.jpg`);
  if (button === -1) {
    throw new Error();
  }
  // success
};

const tryWork = () => {
  hardWork()
    .catch((error) => {
      setTimeout(tryWork, 5 * 60 * 1000); // 5 minutes
    });
};
tryWork();

If you need different error messages for the different possible errors, I'd make a higher-order function that you can pass into .catch that  logs the message, to keep the code DRY:

const makeCatch = msg => (err) => {
  console.log('Problem with ' + msg, err);
  throw new Error(); // this is important- this rejects the Promise, so it stops the hardWork
};

// ...

await downloadImage.downloadImage()
  .catch(makeCatch('downloadImage'));
await UploadToGcBucket.UploadToGcBucket(image)
  .catch(makeCatch('upload to gc'));
await timeout(5000);
const button = await googleVisionAPI.findMagicButton(`some_screenshot.jpg`)
  .catch(makeCatch('findButton'));

Live snippet:

// dummied up API calls below...
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
const downloadImage = () => new Promise(resolve => setTimeout(resolve, 200));
const uploadToGcBucket = () => new Promise(resolve => setTimeout(resolve, 200));
// the below function will resolve to -1 70% of the time, and to 0 30% of the time
const findMagicButton = () => new Promise(resolve => setTimeout(resolve, 200, Math.floor(Math.random() - 0.7)));
// dummied up API calls above...

const hardWork = async () => {
  const image = await downloadImage();
  await uploadToGcBucket(image);
  await timeout(500);
  const button = await findMagicButton(`some_screenshot.jpg`);
  if (button === -1) {
    throw new Error();
  }
  console.log('success');
};

const tryWork = () => {
  hardWork()
    .catch((error) => {
      console.log('failure, retry');
      setTimeout(tryWork, 2 * 1000); // 2 seconds
    });
};
console.log('start');
tryWork();