问:
kernelspec is not installed and Jupyter-notebook not found, though pip says it is
I am trying to run a python script from vs code. A month ago, the environment was working perfectly, but today nope won't run. go figure.
Any and all attempts to install or update packages, e.g. python.exe -m pip install -U jupyter --user, returns "Requirement already satisfied".
Checking jupyter version says its not found.

```<code>python -m jupyter notebook --version
Traceback (most recent call last):
  File "C:\Users\dayneo\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 192, in _run_module_as_main
    return _run_code(code, main_globals, None,
    exec(code, run_globals)
  File "C:\Users\dayneo\AppData\Roaming\Python\Python38\site-packages\jupyter.py", line 10, in <module>
    run_module('jupyter_core')
  File "C:\Users\dayneo\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 208, in run_module
    return _run_code(code, {}, init_globals, run_name, mod_spec)
  File "C:\Users\dayneo\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\dayneo\AppData\Roaming\Python\Python38\site-packages\jupyter_core\__main__.py", line 3, in <module>
    main()
  File "C:\Users\dayneo\AppData\Roaming\Python\Python38\site-packages\jupyter_core\command.py", line 247, in main
    command = _jupyter_abspath(subcommand)
  File "C:\Users\dayneo\AppData\Roaming\Python\Python38\site-packages\jupyter_core\command.py", line 133, in _jupyter_abspath
    raise Exception(
Exception: Jupyter command `jupyter-notebook` not found.
</code>```

Trying to install it, says its already there.

```<code>pip install -U jupyter
Requirement already up-to-date: jupyter in c:\users\dayneo\appdata\roaming\python\python38\site-packages (1.0.0)
Requirement already satisfied, skipping upgrade: nbconvert in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter) (5.6.1)
Requirement already satisfied, skipping upgrade: qtconsole in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter) (4.6.0)
Requirement already satisfied, skipping upgrade: ipywidgets in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter) (7.5.1)
Requirement already satisfied, skipping upgrade: jupyter-console in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter) (6.1.0)
Requirement already satisfied, skipping upgrade: ipykernel in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter) (5.1.4)
Requirement already satisfied, skipping upgrade: notebook in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter) (6.0.3)
Requirement already satisfied, skipping upgrade: entrypoints>=0.2.2 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (0.3)
Requirement already satisfied, skipping upgrade: testpath in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (0.4.4)
Requirement already satisfied, skipping upgrade: jinja2>=2.4 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (2.11.0)
Requirement already satisfied, skipping upgrade: traitlets>=4.2 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (4.3.3)
Requirement already satisfied, skipping upgrade: jupyter-core in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (4.6.1)
Requirement already satisfied, skipping upgrade: bleach in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (3.1.0)
Requirement already satisfied, skipping upgrade: defusedxml in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (0.6.0)
Requirement already satisfied, skipping upgrade: mistune<2,>=0.8.1 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (0.8.4)
Requirement already satisfied, skipping upgrade: pandocfilters>=1.4.1 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (1.4.2)
Requirement already satisfied, skipping upgrade: nbformat>=4.4 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (5.0.4)
Requirement already satisfied, skipping upgrade: pygments in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (2.5.2)
Requirement already satisfied, skipping upgrade: jupyter-client>=4.1 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from qtconsole->jupyter) (5.3.4)
Requirement already satisfied, skipping upgrade: ipython-genutils in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from qtconsole->jupyter) (0.2.0)
Requirement already satisfied, skipping upgrade: ipython>=4.0.0; python_version >= "3.3" in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from ipywidgets->jupyter) (7.11.1)
Requirement already satisfied, skipping upgrade: widgetsnbextension~=3.5.0 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from ipywidgets->jupyter)
(3.5.1)
Requirement already satisfied, skipping upgrade: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter-console->jupyter) (3.0.3)
Requirement already satisfied, skipping upgrade: tornado>=4.2 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from ipykernel->jupyter) (6.0.3)
Requirement already satisfied, skipping upgrade: Send2Trash in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from notebook->jupyter) (1.5.0)
Requirement already satisfied, skipping upgrade: prometheus-client in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from notebook->jupyter) (0.7.1)
Requirement already satisfied, skipping upgrade: pyzmq>=17 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from notebook->jupyter) (18.1.1)
Requirement already satisfied, skipping upgrade: terminado>=0.8.1 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from notebook->jupyter) (0.8.3)
Requirement already satisfied, skipping upgrade: MarkupSafe>=0.23 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jinja2>=2.4->nbconvert->jupyter) (1.1.1)
Requirement already satisfied, skipping upgrade: decorator in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from traitlets>=4.2->nbconvert->jupyter) (4.4.1)
Requirement already satisfied, skipping upgrade: six in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from traitlets>=4.2->nbconvert->jupyter) (1.13.0)
Requirement already satisfied, skipping upgrade: pywin32>=1.0; sys_platform == "win32" in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from jupyter-core->nbconvert->jupyter) (227)
Requirement already satisfied, skipping upgrade: webencodings in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from bleach->nbconvert->jupyter) (0.5.1)
Requirement already satisfied, skipping upgrade: jsonschema!=2.5.0,>=2.4 in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from nbformat>=4.4->nbconvert->jupyter) (3.2.0)
Requirement already satisfied, skipping upgrade: python-dateutil>=2.1 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter-client>=4.1->qtconsole->jupyter) (2.8.1)
Requirement already satisfied, skipping upgrade: pickleshare in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (0.7.5)
Requirement already satisfied, skipping upgrade: backcall in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (0.1.0)
Requirement already satisfied, skipping upgrade: colorama; sys_platform == "win32" in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (0.4.3)
Requirement already satisfied, skipping upgrade: jedi>=0.10 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (0.16.0)
Requirement already satisfied, skipping upgrade: setuptools>=18.5 in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from ipython>=4.0.0;
python_version >= "3.3"->ipywidgets->jupyter) (41.2.0)
Requirement already satisfied, skipping upgrade: wcwidth in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->jupyter-console->jupyter) (0.1.8)
Requirement already satisfied, skipping upgrade: pywinpty>=0.5; os_name == "nt" in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from terminado>=0.8.1->notebook->jupyter) (0.5.7)
Requirement already satisfied, skipping upgrade: pyrsistent>=0.14.0 in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.4->nbconvert->jupyter) (0.15.6)
Requirement already satisfied, skipping upgrade: attrs>=17.4.0 in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.4->nbconvert->jupyter) (19.3.0)
Requirement already satisfied, skipping upgrade: parso>=0.5.2 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jedi>=0.10->ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (0.6.0)
</code>```

How do you proceed from here?

答: The latest version of Python extension 2020 / 02 / 06 is the cause of the error. Try to uninstall the latest version and install another previous version. It should work.</p>

Body:
I am trying to run a python script from vs code. A month ago, the environment was working perfectly, but today nope won't run. go figure.
Any and all attempts to install or update packages, e.g. python.exe -m pip install -U jupyter --user, returns "Requirement already satisfied".
Checking jupyter version says its not found.

python -m jupyter notebook --version
Traceback (most recent call last):
  File "C:\Users\dayneo\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 192, in _run_module_as_main
    return _run_code(code, main_globals, None,
    exec(code, run_globals)
  File "C:\Users\dayneo\AppData\Roaming\Python\Python38\site-packages\jupyter.py", line 10, in <module>
    run_module('jupyter_core')
  File "C:\Users\dayneo\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 208, in run_module
    return _run_code(code, {}, init_globals, run_name, mod_spec)
  File "C:\Users\dayneo\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\dayneo\AppData\Roaming\Python\Python38\site-packages\jupyter_core\__main__.py", line 3, in <module>
    main()
  File "C:\Users\dayneo\AppData\Roaming\Python\Python38\site-packages\jupyter_core\command.py", line 247, in main
    command = _jupyter_abspath(subcommand)
  File "C:\Users\dayneo\AppData\Roaming\Python\Python38\site-packages\jupyter_core\command.py", line 133, in _jupyter_abspath
    raise Exception(
Exception: Jupyter command `jupyter-notebook` not found.

Trying to install it, says its already there.

pip install -U jupyter
Requirement already up-to-date: jupyter in c:\users\dayneo\appdata\roaming\python\python38\site-packages (1.0.0)
Requirement already satisfied, skipping upgrade: nbconvert in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter) (5.6.1)
Requirement already satisfied, skipping upgrade: qtconsole in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter) (4.6.0)
Requirement already satisfied, skipping upgrade: ipywidgets in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter) (7.5.1)
Requirement already satisfied, skipping upgrade: jupyter-console in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter) (6.1.0)
Requirement already satisfied, skipping upgrade: ipykernel in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter) (5.1.4)
Requirement already satisfied, skipping upgrade: notebook in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter) (6.0.3)
Requirement already satisfied, skipping upgrade: entrypoints>=0.2.2 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (0.3)
Requirement already satisfied, skipping upgrade: testpath in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (0.4.4)
Requirement already satisfied, skipping upgrade: jinja2>=2.4 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (2.11.0)
Requirement already satisfied, skipping upgrade: traitlets>=4.2 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (4.3.3)
Requirement already satisfied, skipping upgrade: jupyter-core in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (4.6.1)
Requirement already satisfied, skipping upgrade: bleach in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (3.1.0)
Requirement already satisfied, skipping upgrade: defusedxml in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (0.6.0)
Requirement already satisfied, skipping upgrade: mistune<2,>=0.8.1 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (0.8.4)
Requirement already satisfied, skipping upgrade: pandocfilters>=1.4.1 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (1.4.2)
Requirement already satisfied, skipping upgrade: nbformat>=4.4 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (5.0.4)
Requirement already satisfied, skipping upgrade: pygments in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from nbconvert->jupyter) (2.5.2)
Requirement already satisfied, skipping upgrade: jupyter-client>=4.1 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from qtconsole->jupyter) (5.3.4)
Requirement already satisfied, skipping upgrade: ipython-genutils in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from qtconsole->jupyter) (0.2.0)
Requirement already satisfied, skipping upgrade: ipython>=4.0.0; python_version >= "3.3" in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from ipywidgets->jupyter) (7.11.1)
Requirement already satisfied, skipping upgrade: widgetsnbextension~=3.5.0 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from ipywidgets->jupyter)
(3.5.1)
Requirement already satisfied, skipping upgrade: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter-console->jupyter) (3.0.3)
Requirement already satisfied, skipping upgrade: tornado>=4.2 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from ipykernel->jupyter) (6.0.3)
Requirement already satisfied, skipping upgrade: Send2Trash in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from notebook->jupyter) (1.5.0)
Requirement already satisfied, skipping upgrade: prometheus-client in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from notebook->jupyter) (0.7.1)
Requirement already satisfied, skipping upgrade: pyzmq>=17 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from notebook->jupyter) (18.1.1)
Requirement already satisfied, skipping upgrade: terminado>=0.8.1 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from notebook->jupyter) (0.8.3)
Requirement already satisfied, skipping upgrade: MarkupSafe>=0.23 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jinja2>=2.4->nbconvert->jupyter) (1.1.1)
Requirement already satisfied, skipping upgrade: decorator in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from traitlets>=4.2->nbconvert->jupyter) (4.4.1)
Requirement already satisfied, skipping upgrade: six in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from traitlets>=4.2->nbconvert->jupyter) (1.13.0)
Requirement already satisfied, skipping upgrade: pywin32>=1.0; sys_platform == "win32" in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from jupyter-core->nbconvert->jupyter) (227)
Requirement already satisfied, skipping upgrade: webencodings in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from bleach->nbconvert->jupyter) (0.5.1)
Requirement already satisfied, skipping upgrade: jsonschema!=2.5.0,>=2.4 in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from nbformat>=4.4->nbconvert->jupyter) (3.2.0)
Requirement already satisfied, skipping upgrade: python-dateutil>=2.1 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jupyter-client>=4.1->qtconsole->jupyter) (2.8.1)
Requirement already satisfied, skipping upgrade: pickleshare in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (0.7.5)
Requirement already satisfied, skipping upgrade: backcall in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (0.1.0)
Requirement already satisfied, skipping upgrade: colorama; sys_platform == "win32" in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (0.4.3)
Requirement already satisfied, skipping upgrade: jedi>=0.10 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (0.16.0)
Requirement already satisfied, skipping upgrade: setuptools>=18.5 in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from ipython>=4.0.0;
python_version >= "3.3"->ipywidgets->jupyter) (41.2.0)
Requirement already satisfied, skipping upgrade: wcwidth in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->jupyter-console->jupyter) (0.1.8)
Requirement already satisfied, skipping upgrade: pywinpty>=0.5; os_name == "nt" in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from terminado>=0.8.1->notebook->jupyter) (0.5.7)
Requirement already satisfied, skipping upgrade: pyrsistent>=0.14.0 in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.4->nbconvert->jupyter) (0.15.6)
Requirement already satisfied, skipping upgrade: attrs>=17.4.0 in c:\users\dayneo\appdata\local\programs\python\python38-32\lib\site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.4->nbconvert->jupyter) (19.3.0)
Requirement already satisfied, skipping upgrade: parso>=0.5.2 in c:\users\dayneo\appdata\roaming\python\python38\site-packages (from jedi>=0.10->ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (0.6.0)

How do you proceed from here?


来源: stackexchange

问:
BlackBerry - Thread not responding
I'm sorry that this question is a bit vague but I've not been able to get any useful info from debugging.

I have a thread that I call using new Thread().Start, it will then run for a a short time and I receive this message:

Uncaught exception:Application "my app
  name(201)" is not responding; process
  terminated

Now what's frustrating is I am able to run the same process but without a thread, which then locks up my Application but I can see from my Eclipse console that its working without error. So I know their isn't an error with the functions I'm using on the Thread.

I thought perhaps the issue might lie with me using a "InvokeLater" function to update my GUI with the threads progression, I am spamming this pretty hard and I fear its destroying my thread.

Any suggestions?

To expand upon my post, the issue was due to me calling this code ALOT from my other thread:-

```<code> invokeLater(new Runnable()
        {
            public void run()
            {
                _output.setText(_output.getText() + "\n" + msg);
            }
        });
</code>```

This was building up a queue that quickly crashed my application.

My solution to the option was to use the event thread by adding this code to my function:-

```<code>   synchronized(Application.getEventLock()) {
       _output.setText("new text " + System.currentTimeMillis());
   }
</code>```

答: It could be a deadlock, especially if you extend the timeout and still see it. You could take a thread-dump and see what the UI thread is doing. If it's waiting to acquire a lock, you'd probably want to dig in this direction.</p>

ContentLicense: CC BY-SA 3.0

Title: BlackBerry - Thread not responding

Body:
I'm sorry that this question is a bit vague but I've not been able to get any useful info from debugging.

I have a thread that I call using new Thread().Start, it will then run for a a short time and I receive this message:

Uncaught exception:Application "my app
  name(201)" is not responding; process
  terminated

Now what's frustrating is I am able to run the same process but without a thread, which then locks up my Application but I can see from my Eclipse console that its working without error. So I know their isn't an error with the functions I'm using on the Thread.

I thought perhaps the issue might lie with me using a "InvokeLater" function to update my GUI with the threads progression, I am spamming this pretty hard and I fear its destroying my thread.

Any suggestions?

To expand upon my post, the issue was due to me calling this code ALOT from my other thread:-

 invokeLater(new Runnable()
        {
            public void run()
            {
                _output.setText(_output.getText() + "\n" + msg);
            }
        });

This was building up a queue that quickly crashed my application.

My solution to the option was to use the event thread by adding this code to my function:-

   synchronized(Application.getEventLock()) {
       _output.setText("new text " + System.currentTimeMillis());
   }


问:
URN Problem Forge Model Derivative API - Invalid design parameter
I'm trying to translate an object I've previously uploaded to a Forge bucket, but I'm getting a parameter error. I'm assuming the URN is the issue. I can confirm that the object is uploaded properly, as I have been able to download it from the bucket.

My code is as follows:

I use the getObjectDetails call to get the object URN as the object ID:

```<code>static getObjectUrn (oAuth2TwoLegged, objectName, callback) {
    ObjectsApi.getObjectDetails(bucketKey, objectName, {}, oAuth2TwoLegged, oAuth2TwoLegged.getCredentials()).then((resp) => {
        callback(null, resp.body.objectId);
    }, callback);
}
</code>```

I get back something like:
urn:adsk.objects:os.object:configtest2/f8d215f7-9ff0-474a-87b9-632ca745b39eresult.zip

My request body looks like this:

```<code>let data = urn;
var buf = new Buffer(data, 'base64');
var plain_buf = buf.toString();
console.log(plain_buf);

const resolvedTemplate = {
                        'input': {
                            "urn": plain_buf,
                            "compressedUrn": true,
                            "rootFilename": self.rootFilename
                        },
                        'output': {
                            "destination": {
                              "region": "us"
                            },
                            "formats": [
                              {
                                "type": "svf",
                                "views": [
                                  "3d"
                                ]
                              }
                            ]
                          },
                    };
</code>```

I've tried a couple different variations of the urn before and after encoding it, to no avail. My root file name is PlaysetGA.iam, although this is a .zip folder, so I've also tried the path inside the folder which is Playset/PlaysetGA.iam.

I've checked out the following page:
https://forge.autodesk.com/en/docs/model-derivative/v2/tutorials/prepare-file-for-viewer/
and this question:
Model Derivative API Post Job - 400 Bad Request "Invalid 'design' parameter"

This is the response I'm getting:
{"diagnostic":"Invalid 'design' parameter."}

Obviously, I'm missing something. Thanks!

Edit:
I've updated my .zip folder so my rootfile is in the base file path. This the the root directory:

Root folder

答: Currently the POST job endpoint only supports file names, not file paths, in the rootFilename parameter. If you want to translate a ZIP file, you'll need to make sure that the root filename is available directly in the root of the archive.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to translate an object I've previously uploaded to a Forge bucket, but I'm getting a parameter error. I'm assuming the URN is the issue. I can confirm that the object is uploaded properly, as I have been able to download it from the bucket.

My code is as follows:

I use the getObjectDetails call to get the object URN as the object ID:

static getObjectUrn (oAuth2TwoLegged, objectName, callback) {
    ObjectsApi.getObjectDetails(bucketKey, objectName, {}, oAuth2TwoLegged, oAuth2TwoLegged.getCredentials()).then((resp) => {
        callback(null, resp.body.objectId);
    }, callback);
}

I get back something like:
urn:adsk.objects:os.object:configtest2/f8d215f7-9ff0-474a-87b9-632ca745b39eresult.zip

My request body looks like this:

let data = urn;
var buf = new Buffer(data, 'base64');
var plain_buf = buf.toString();
console.log(plain_buf);

const resolvedTemplate = {
                        'input': {
                            "urn": plain_buf,
                            "compressedUrn": true,
                            "rootFilename": self.rootFilename
                        },
                        'output': {
                            "destination": {
                              "region": "us"
                            },
                            "formats": [
                              {
                                "type": "svf",
                                "views": [
                                  "3d"
                                ]
                              }
                            ]
                          },
                    };

I've tried a couple different variations of the urn before and after encoding it, to no avail. My root file name is PlaysetGA.iam, although this is a .zip folder, so I've also tried the path inside the folder which is Playset/PlaysetGA.iam.

I've checked out the following page:
https://forge.autodesk.com/en/docs/model-derivative/v2/tutorials/prepare-file-for-viewer/
and this question:
Model Derivative API Post Job - 400 Bad Request "Invalid 'design' parameter"

This is the response I'm getting:
{"diagnostic":"Invalid 'design' parameter."}

Obviously, I'm missing something. Thanks!

Edit:
I've updated my .zip folder so my rootfile is in the base file path. This the the root directory:

Root folder


问:
Feature Scaling
I read it from a post that someone said:

For feature scaling, you learn the means and standard deviation of the training set, and then:

Standardize the training set using the training set means and
standard deviations.

Standardize any test set using the training set means and standard
deviations.

But now my question is, after fitting a model using scaled training data, should I then apply this fitted model onto scaled or unscaled test data? Thanks!

答:
Yes, you should also scale the test data. If you have scaled your training data and fitted a model to that scaled data, then the test set should also undergo equivalent preprocessing as well. This is standard practice, as it ensures that the model is always provided a data set of consistent form as input.

In Python, the process might look as follows:

scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
```

There is a detailed write up on this topic on another thread that might be of interest to you.

Title: Feature Scaling

Body:
Yes, you should also scale the test data. If you have scaled your training data and fitted a model to that scaled data, then the test set should also undergo equivalent preprocessing as well. This is standard practice, as it ensures that the model is always provided a data set of consistent form as input.

In Python, the process might look as follows:

scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

There is a detailed write up on this topic on another thread that might be of interest to you.


问:
Files from another git repo in the project root directory
I have several boiler-plate files that I would like to reuse in multiple projects.  These files (such as a Makefile, gitpod config files, or CI/CD config files) need to reside in the base directory of the project, so I can't create a subdirectory with another repo.

How do to have these files in the project, but also have a link back to a common utility project so I can pull updates to all projects?

答:
The easiest, most pain-free way to do this if possible is to use a submodule with symlinks.  That makes updating as easy as possible.  However, it may not be possible in all cases, so there are other things you can try.

You can take your boilerplate repo and merge it into your project repo with --allow-unrelated-histories.  If you need to pull in additional changes, you can then merge in additional changes from the boilerplate repository.

Note that this will work poorly if you already have files with the same names in your project repository, so you may want to avoid that.


问:
Can`t exit from program
Trying to exit the program by importing sys.exit(), break and ask == False, but nothing works. Full code here</p>

```<code>#import sys

def body_cycle(*args):

    if option == "/":
        error_func_for_zero(first_number, second_number, option)
        print(division_option(first_number, second_number))
        print()
        print(begin)

def error_func_for_zero(*args):

    try:
       first_number / 0 or second_number / 0

    except ZeroDivisionError:
       print("YOU CANNOT DIVIDE BY ZERO!")
       print(begin)

def division_option(*args):

    return first_number / second_number

begin = " "

while begin:

    print("Hello, I am calculator. ")
    print("Please, enter your numbers (just integers) ! ")

    print()

    first_number = int(input("First number: "))

    print()

    second_number = int(input("Second number: "))

    print()

    option = input("Remember: you can't divide by zero.\nChoose your option (+, -, *, /): ")

    print(body_cycle(first_number, second_number, option))

ask = " "

while ask:

    exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'? \nChoice: ")

    if exit_or_continue == "Y" or "y":
       print("OK")

    elif exit_or_continue == "N" or "n":
       #break
       ask == False

    else:
       print("Break program. ")
       break
</code>```

答:
You just want to replace ask == False by ask  = False.

In addition, you could really use a simpler code structure. The whole thing before begin can be compacted down to:

```<code>def operation(a, b, option):

    if option == "+":
        return a + b

    elif option == "-":
        return a - b

    elif option == "*":
        return a * b

    elif option == "/":
        try:
            return a / b
        except ZeroDivsionError
            return "YOU CANNOT DIVIDE BY ZERO!"
</code>```

The rest can be put in a single loop instead of two, like so:

```<code>print("Hello, I am calculator. ")

while True:
    print("Please, enter your numbers (just integers) ! ")
    print()

    first_number = int(input("First number: "))
    print()

    second_number = int(input("Second number: "))
    print()

    option = input("Remember: you can't divide by zero.\n
                    Choose your option (+, -, *, /): ")

    # Result.
    print(operation(first_number, second_number, option))

    exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'.\n
                              Choice: ").lower()

    if exit_or_continue == "y":
       print("OK")

    elif exit_or_continue == "n":
       break
</code>```

Title: Can`t exit from program

Body:
Trying to exit the program by importing sys.exit(), break and ask == False, but nothing works. Full code here

#import sys

def body_cycle(*args):

    if option == "/":
        error_func_for_zero(first_number, second_number, option)
        print(division_option(first_number, second_number))
        print()
        print(begin)

def error_func_for_zero(*args):

    try:
       first_number / 0 or second_number / 0

    except ZeroDivisionError:
       print("YOU CANNOT DIVIDE BY ZERO!")
       print(begin)

def division_option(*args):

    return first_number / second_number

begin = " "

while begin:

    print("Hello, I am calculator. ")
    print("Please, enter your numbers (just integers) ! ")

    print()

    first_number = int(input("First number: "))

    print()

    second_number = int(input("Second number: "))

    print()

    option = input("Remember: you can't divide by zero.\nChoose your option (+, -, *, /): ")

    print(body_cycle(first_number, second_number, option))

ask = " "

while ask:

    exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'? \nChoice: ")

    if exit_or_continue == "Y" or "y":
       print("OK")

    elif exit_or_continue == "N" or "n":
       #break
       ask == False

    else:
       print("Break program. ")
       break

Body:
You just want to replace ask == False by ask  = False.

In addition, you could really use a simpler code structure. The whole thing before begin can be compacted down to:

def operation(a, b, option):

    if option == "+":
        return a + b

    elif option == "-":
        return a - b

    elif option == "*":
        return a * b

    elif option == "/":
        try:
            return a / b
        except ZeroDivsionError
            return "YOU CANNOT DIVIDE BY ZERO!"

The rest can be put in a single loop instead of two, like so:

print("Hello, I am calculator. ")

while True:
    print("Please, enter your numbers (just integers) ! ")
    print()

    first_number = int(input("First number: "))
    print()

    second_number = int(input("Second number: "))
    print()

    option = input("Remember: you can't divide by zero.\n
                    Choose your option (+, -, *, /): ")

    # Result.
    print(operation(first_number, second_number, option))

    exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'.\n
                              Choice: ").lower()

    if exit_or_continue == "y":
       print("OK")

    elif exit_or_continue == "n":
       break


问:
Logstash-Logback Encoder: “IllegalAccessError: failed to access class […]”
I try to send logs from a java application with the Logstash tcp socket appender to logstash. The java app. already works with logback 1.1.9 (slf4j) and other appenders.

Now I added the following lines to the logback-test.xml:

```<code><configuration>
    <appender name="logstash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
        <destination>[IP]:5010</destination>
        <encoder class="net.logstash.logback.encoder.LogstashEncoder">
            <fieldNames>
                <message>log_msg</message>
            </fieldNames>
        </encoder>
        <keepAliveDuration>5 minutes</keepAliveDuration>
    </appender>

<root>
<level value="info"/>
<appender-ref ref="logstash" />
</root>
</configuration>
</code>```

But when I add the appender and start my java application, I get an error from the JVM Launcher "A Java Exception has occured" and I get the following console text:

```<code>Exception in thread "main" java.lang.IllegalAccessError: failed to access class ch.qos.logback.core.status.OnPrintStreamStatusListenerBase from class net.logstash.logback.status.LevelFilteringStatusListener (ch.qos.logback.core.status.OnPrintStreamStatusListenerBase and net.logstash.logback.status.LevelFilteringStatusListener are in unnamed module of loader 'app')
    at net.logstash.logback.status.LevelFilteringStatusListener.setDelegate(LevelFilteringStatusListener.java:67)
    at net.logstash.logback.appender.AsyncDisruptorAppender.start(AsyncDisruptorAppender.java:370)
    at net.logstash.logback.appender.AbstractLogstashTcpSocketAppender.start(AbstractLogstashTcpSocketAppender.java:1009)
    at ch.qos.logback.core.joran.action.AppenderAction.end(AppenderAction.java:90)
    at ch.qos.logback.core.joran.spi.Interpreter.callEndAction(Interpreter.java:309)
    at ch.qos.logback.core.joran.spi.Interpreter.endElement(Interpreter.java:193)
    at ch.qos.logback.core.joran.spi.Interpreter.endElement(Interpreter.java:179)
    at ch.qos.logback.core.joran.spi.EventPlayer.play(EventPlayer.java:62)
    at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:158)
    at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:145)
    at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:103)
    at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:53)
    at ch.qos.logback.classic.util.ContextInitializer.configureByResource(ContextInitializer.java:75)
    at ch.qos.logback.classic.util.ContextInitializer.autoConfig(ContextInitializer.java:150)
    at org.slf4j.impl.StaticLoggerBinder.init(StaticLoggerBinder.java:84)
    at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:55)
    at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
    at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
    at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:412)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:383)
</code>```

I included the logstash 6.3 jar-file and because of this error, I also tried it with an older version, 4.9. Does anybody know if that is compatible to logback 1.1.9?
I'm not using Spring-Boot.

---------Edit 17.02.2020-----------

My input of the logstash.conf file (because I don't get any log from my java application):

```<code>input {
   tcp {
      mode => "server"
      port => 5010
      codec => json
   }
}
</code>```

答:
You can avoid the exception you encountered by applying any of the following solutions:

A) Use logback version >= 1.1.10

OR

B) Add <addDefaultStatusListener>false</addDefaultStatusListener> to your appender definition (see details here)

OR

C) Add a status listener to your logback configuration (which prevents logstash-logback-encoder from adding a default status listener).

The exception occurs because logstash-logback-encoder versions >= 6.0 reference logback's ch.qos.logback.core.status.OnPrintStreamStatusListenerBase class when adding a default status listener.  OnPrintStreamStatusListenerBase was made public in logback 1.1.10, and was package-private before then.

Applying any of the above solutions will avoid the exception you encountered.  However, keep in mind that logstash-logback-encoder versions >= 4.8 are compiled and tested against logback 1.2.x.  Therefore, you might encounter other errors when using logback 1.1.x.  The logstash-logback-encoder readme contains the following statement on this topic:

Older versions than the ones specified in the pom file might work, but the versions in the pom file are what testing has been performed against.

Body:
I try to send logs from a java application with the Logstash tcp socket appender to logstash. The java app. already works with logback 1.1.9 (slf4j) and other appenders.

Now I added the following lines to the logback-test.xml:

<configuration>
    <appender name="logstash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
        <destination>[IP]:5010</destination>
        <encoder class="net.logstash.logback.encoder.LogstashEncoder">
            <fieldNames>
                <message>log_msg</message>
            </fieldNames>
        </encoder>
        <keepAliveDuration>5 minutes</keepAliveDuration>
    </appender>

<root>
<level value="info"/>
<appender-ref ref="logstash" />
</root>
</configuration>

But when I add the appender and start my java application, I get an error from the JVM Launcher "A Java Exception has occured" and I get the following console text:

Exception in thread "main" java.lang.IllegalAccessError: failed to access class ch.qos.logback.core.status.OnPrintStreamStatusListenerBase from class net.logstash.logback.status.LevelFilteringStatusListener (ch.qos.logback.core.status.OnPrintStreamStatusListenerBase and net.logstash.logback.status.LevelFilteringStatusListener are in unnamed module of loader 'app')
    at net.logstash.logback.status.LevelFilteringStatusListener.setDelegate(LevelFilteringStatusListener.java:67)
    at net.logstash.logback.appender.AsyncDisruptorAppender.start(AsyncDisruptorAppender.java:370)
    at net.logstash.logback.appender.AbstractLogstashTcpSocketAppender.start(AbstractLogstashTcpSocketAppender.java:1009)
    at ch.qos.logback.core.joran.action.AppenderAction.end(AppenderAction.java:90)
    at ch.qos.logback.core.joran.spi.Interpreter.callEndAction(Interpreter.java:309)
    at ch.qos.logback.core.joran.spi.Interpreter.endElement(Interpreter.java:193)
    at ch.qos.logback.core.joran.spi.Interpreter.endElement(Interpreter.java:179)
    at ch.qos.logback.core.joran.spi.EventPlayer.play(EventPlayer.java:62)
    at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:158)
    at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:145)
    at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:103)
    at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:53)
    at ch.qos.logback.classic.util.ContextInitializer.configureByResource(ContextInitializer.java:75)
    at ch.qos.logback.classic.util.ContextInitializer.autoConfig(ContextInitializer.java:150)
    at org.slf4j.impl.StaticLoggerBinder.init(StaticLoggerBinder.java:84)
    at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:55)
    at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
    at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
    at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:412)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:383)

I included the logstash 6.3 jar-file and because of this error, I also tried it with an older version, 4.9. Does anybody know if that is compatible to logback 1.1.9?
I'm not using Spring-Boot.

---------Edit 17.02.2020-----------

My input of the logstash.conf file (because I don't get any log from my java application):

input {
   tcp {
      mode => "server"
      port => 5010
      codec => json
   }
}


问:
Streaming Video to YouTube (API)
I've been given the job of developing a website where registered users can register, and then using their webcam on our site stream live video to our youtube account, via our website.

But finding information on this has proven quite difficult, and I'm beginning to think the worst; It's not currently possible.

I did find one Google result that mentioned this streaming technology but upon clicking the link found absolutely no relevent information whatsoever. Does anybody know if this can be done? Where the API would be and and links/resources would be extremely helpful and appreciated.

Thank you!

答: I am no expert in this area but what if the stream is stored on your server first and then uploaded to youTube as a normal video file? I believe Red5 offers a plugin which you can use to allow people to record video from their webcam. A quick google search gives me this http://www.red5-recorder.com/ .. check it out, it might be useful for your purpose.</p>

Title: Streaming Video to YouTube (API)


问:
What's the underlying implimentation of integer division in python?
I am running python 3.7.3

Regarding the integer division operator: "//" (double divide, double forward slash, double division operator? I'm not sure the exact name.)

It does not seem to give consistent results, and many of the explanations I've found don't fully explain its results.

Here[What is the reason for having '//' in Python? (and other places) it's said that the "//" operator gives the quotient without the remainder. As if a // b is the same as floor(a / b) (or rounding up if a / b is negative).

However, sometimes it does not give that answer.  For example,1 // 0.2 evaluates to 4. However 1 / 0.2 returns 5, and math.floor(1 / 2) also returns 5.  It's giving a number one less than what integer division should.  The // operator returns a 5 if you divide 10 by 2, but 1 divided 0.2 does not work correctly.

This problem comes up other times I use the // operator to divide floating point numbers.  Like 5 // 0.2 or 100 // 0.2.  I don't know if this is some quirk of floating point arithmetic, but these problems seem to go away if you type math.floor(5 / 0.2) (or any other set of numbers giving issues).  Except when you divide negative numbers, in which case you have to use math.ceil() instead of math.floor()

My current solution is this:

```<code>import math
</code>```

```<code>def integerDivision(a,b):
    tmp = a / b
    if tmp > 1:
        return(math.floor(tmp))
    else:
        return(math.ceil(tmp))
</code>```

What is the implementation of the // operator that makes it not give the right result in some floating point cases? Is there a better way to get around this issue of the // operator, other than the above code?

答:
This isn't about implementation. This is about the operator's semantics. Regardless of implementation, the // operator is required to give you the results you're seeing when applied to floats, and those results really are correct (for floats). If you don't want these results, floats are probably the wrong tool for what you're doing.

1 // 0.2 gives the floating-point number representing the floor of the exact value of the quotient of its arguments. However, the right-hand argument does not quite have the value you typed in. The right-hand argument's value is the closest value to 0.2 representable in 64-bit IEEE binary floating point, which is slightly higher than 0.2:

```<code>>>> import decimal
>>> decimal.Decimal(0.2)
Decimal('0.200000000000000011102230246251565404236316680908203125')
</code>```

The exact value of the quotient is thus slightly less than 5, so 1 // 0.2 gives you 4.0.

1 / 0.2 gives you 5.0 because the exact value of the quotient isn't representable as a float. The result needs to be rounded, and it rounds to 5.0. // does not perform this rounding; it computes the floor of the exact value, not the floor of a rounded float. (The result of the // may need to be rounded, but that's a different rounding.)

With all that said, the implementation needs to be more complex than floor(x / y), because that would give the wrong result. CPython bases its // implementation for floats on fmod. You can see the implementation in Objects/floatobject.c in the CPython source repository.

```<code>static PyObject *
float_divmod(PyObject *v, PyObject *w)
{
    double vx, wx;
    double div, mod, floordiv;
    CONVERT_TO_DOUBLE(v, vx);
    CONVERT_TO_DOUBLE(w, wx);
    if (wx == 0.0) {
        PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
        return NULL;
    }
    PyFPE_START_PROTECT("divmod", return 0)
    mod = fmod(vx, wx);
    /* fmod is typically exact, so vx-mod is *mathematically* an
       exact multiple of wx.  But this is fp arithmetic, and fp
       vx - mod is an approximation; the result is that div may
       not be an exact integral value after the division, although
       it will always be very close to one.
    */
    div = (vx - mod) / wx;
    if (mod) {
        /* ensure the remainder has the same sign as the denominator */
        if ((wx < 0) != (mod < 0)) {
            mod += wx;
            div -= 1.0;
        }
    }
    else {
        /* the remainder is zero, and in the presence of signed zeroes
           fmod returns different results across platforms; ensure
           it has the same sign as the denominator. */
        mod = copysign(0.0, wx);
    }
    /* snap quotient to nearest integral value */
    if (div) {
        floordiv = floor(div);
        if (div - floordiv > 0.5)
            floordiv += 1.0;
    }
    else {
        /* div is zero - get the same sign as the true quotient */
        floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
    }
    PyFPE_END_PROTECT(floordiv)
    return Py_BuildValue("(dd)", floordiv, mod);
}

static PyObject *
float_floor_div(PyObject *v, PyObject *w)
{
    PyObject *t, *r;

    t = float_divmod(v, w);
    if (t == NULL || t == Py_NotImplemented)
        return t;
    assert(PyTuple_CheckExact(t));
    r = PyTuple_GET_ITEM(t, 0);
    Py_INCREF(r);
    Py_DECREF(t);
    return r;
}
</code>```

Other argument types will use other implementations, depending on the types.

Body:
I am running python 3.7.3

Regarding the integer division operator: "//" (double divide, double forward slash, double division operator? I'm not sure the exact name.)

It does not seem to give consistent results, and many of the explanations I've found don't fully explain its results.

Here[What is the reason for having '//' in Python? (and other places) it's said that the "//" operator gives the quotient without the remainder. As if a // b is the same as floor(a / b) (or rounding up if a / b is negative).

However, sometimes it does not give that answer.  For example,1 // 0.2 evaluates to 4. However 1 / 0.2 returns 5, and math.floor(1 / 2) also returns 5.  It's giving a number one less than what integer division should.  The // operator returns a 5 if you divide 10 by 2, but 1 divided 0.2 does not work correctly.

This problem comes up other times I use the // operator to divide floating point numbers.  Like 5 // 0.2 or 100 // 0.2.  I don't know if this is some quirk of floating point arithmetic, but these problems seem to go away if you type math.floor(5 / 0.2) (or any other set of numbers giving issues).  Except when you divide negative numbers, in which case you have to use math.ceil() instead of math.floor()

My current solution is this:

import math

def integerDivision(a,b):
    tmp = a / b
    if tmp > 1:
        return(math.floor(tmp))
    else:
        return(math.ceil(tmp))

What is the implementation of the // operator that makes it not give the right result in some floating point cases? Is there a better way to get around this issue of the // operator, other than the above code?

Body:
This isn't about implementation. This is about the operator's semantics. Regardless of implementation, the // operator is required to give you the results you're seeing when applied to floats, and those results really are correct (for floats). If you don't want these results, floats are probably the wrong tool for what you're doing.

1 // 0.2 gives the floating-point number representing the floor of the exact value of the quotient of its arguments. However, the right-hand argument does not quite have the value you typed in. The right-hand argument's value is the closest value to 0.2 representable in 64-bit IEEE binary floating point, which is slightly higher than 0.2:

>>> import decimal
>>> decimal.Decimal(0.2)
Decimal('0.200000000000000011102230246251565404236316680908203125')

The exact value of the quotient is thus slightly less than 5, so 1 // 0.2 gives you 4.0.

1 / 0.2 gives you 5.0 because the exact value of the quotient isn't representable as a float. The result needs to be rounded, and it rounds to 5.0. // does not perform this rounding; it computes the floor of the exact value, not the floor of a rounded float. (The result of the // may need to be rounded, but that's a different rounding.)

With all that said, the implementation needs to be more complex than floor(x / y), because that would give the wrong result. CPython bases its // implementation for floats on fmod. You can see the implementation in Objects/floatobject.c in the CPython source repository.

static PyObject *
float_divmod(PyObject *v, PyObject *w)
{
    double vx, wx;
    double div, mod, floordiv;
    CONVERT_TO_DOUBLE(v, vx);
    CONVERT_TO_DOUBLE(w, wx);
    if (wx == 0.0) {
        PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
        return NULL;
    }
    PyFPE_START_PROTECT("divmod", return 0)
    mod = fmod(vx, wx);
    /* fmod is typically exact, so vx-mod is *mathematically* an
       exact multiple of wx.  But this is fp arithmetic, and fp
       vx - mod is an approximation; the result is that div may
       not be an exact integral value after the division, although
       it will always be very close to one.
    */
    div = (vx - mod) / wx;
    if (mod) {
        /* ensure the remainder has the same sign as the denominator */
        if ((wx < 0) != (mod < 0)) {
            mod += wx;
            div -= 1.0;
        }
    }
    else {
        /* the remainder is zero, and in the presence of signed zeroes
           fmod returns different results across platforms; ensure
           it has the same sign as the denominator. */
        mod = copysign(0.0, wx);
    }
    /* snap quotient to nearest integral value */
    if (div) {
        floordiv = floor(div);
        if (div - floordiv > 0.5)
            floordiv += 1.0;
    }
    else {
        /* div is zero - get the same sign as the true quotient */
        floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
    }
    PyFPE_END_PROTECT(floordiv)
    return Py_BuildValue("(dd)", floordiv, mod);
}

static PyObject *
float_floor_div(PyObject *v, PyObject *w)
{
    PyObject *t, *r;

    t = float_divmod(v, w);
    if (t == NULL || t == Py_NotImplemented)
        return t;
    assert(PyTuple_CheckExact(t));
    r = PyTuple_GET_ITEM(t, 0);
    Py_INCREF(r);
    Py_DECREF(t);
    return r;
}

Other argument types will use other implementations, depending on the types.


问:
Sonarcloud is not authorized using Travis CI and Maven
I have an experimental project on my Github used for the practising the CI service integrations. I struggle with using Sonarcloud.

I have followed both Tavis CI + Sonarcloud tutorial and Maven example. Mz first confusion starts with the token and properties file whereas the first source suggests creating sonar-project.properties file and the Maven example source does not have any. Here where the documentation is very unclear.

I ignored the properties file and I have done the following steps:

Generated token on sonarcloud.io for my project: e53.....239

Encrypted token on travis-encrypt.github.io since it's the most comfortable way for a Windows user. The 2 following inputs resulted in g3s.....+Q=:

NicharNET/Gistintex

SONAR_TOKEN="e53...239" - I tried both to wrap between quotation marks and without.

Added to Settings -> Environment variable key SONAR_TOKEN with the value of the generated Sonarcloud token e53...239.

Completed travis.yml with the secure token:

```<code>language: java
sudo: false
jdk: oraclejdk8

addons:
    sonarcloud:
    organization: "nicharnet-github"
    token:
        secure: "g3sLTdS597mklh1I9HgXr71NRCiOk2n9I41PL2wklnAidwibfocyEcWvSQxjmbhNTjdrcW0cAfzh73Ago8hwfdloraryDY9Ng9L1runxayShtPOqZMPI6nz8zUwLaDfqJVwXWv6A3xICOMFl0UhvF351GPErHhrUO7YIa8el3kESeotYy7kkTzeQ7BA239y7EVFw8H4OCW2gjP2G/InxKnlXfNjgQA3GsnZdJ3uWO3No5kwt5ybfuCCV42cp/UczLIzNbo0RW9Z9jBl5IFMzJaUQUfWV3Pp5QEPmpB7Anr/4W1EtjJPjpSIC/+jBmbrkvC/CSzzTPjaH9LzEQ5m4F5JpRw01blqgKH/153qfs1jRgZK6WVRuhe7yAATHCO/IM0DM+kC0mUJTcXKyv9pRm93E4wp+KzdHYy0LdA83wFgMmvlB8pcm20ImAe7B2SBFx5TGtETa6ea6k2BS+DfBXe6sLBnrl1zZB8nxCDnYiwT1BJFxizgv3EJ6Krjd3cSSxr6PGnXDD/yTeFNJarpMbA+wR6AQetJ89LiDBXYiw6GPgWk/A4vUDIsIaXGqCpydeZHkr2ufS1Ap4yYS0Um2GeDeQXTsBTSCg7BViFgduUI1NPYT1avKg7b64nsdpdjBVofOvzJsgiT66WlaJmt23BUCJsnmXwwEcW1387b4G+Q="

script:
    - mvn clean install org.jacoco:jacoco-maven-plugin:prepare-agent sonar:sonar
</code>```

Committed and pushed changes into the repository and Travis CI started to work and resulted in:

Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.4.1.1168:sonar (default-cli) on project gistintex: Not authorized. Please check the properties sonar.login and sonar.password.

The error could be found on my Travis CI build. What do I do wrong?

I have skimmed through Error using Travis CI with Sonarcloud: Not authorized. Please check the properties sonar.login and sonar.password SO question and Travis CI Sonarqube analysis article, which unfortunately didn't help me though. My GitHub project source.

I have tried to add these plugins to pom.xml and run the analysis locally:

org.codehaus.mojo: sonar-maven-plugin: 5.1

org.sonarsource.scanner.maven: sonar-maven-plugin: 3.4.1.1168

Running this on my machine resulted in the correct Sonarcloud analysis:

```<code>mvn sonar:sonar \
   -Dsonar.organization=nicharnet-github \
   -Dsonar.host.url=https://sonarcloud.io \
   -Dsonar.login=e53.....239
</code>```

However, my goal is to run the analysis after every committed version using Travis CI. I am sure I have done wrong the key encryption but I can't figure what exactly.

答:
The key encryption problem usually happens when you execute the generation without the login command against travis.com instead of travis.org

In order to run on every commit you could connect your repo with SonarCloud Scan, generate a secret in your sonarcloud.io project page and there you will find instructions to modify your .travis.yml

if you use travis.org

```<code>travis encrypt <YOUR_SONAR_SECRET>
</code>```

if you use travis.com

```<code>travis login --pro
</code>```

then generate your token like this:

```<code>travis encrypt --pro <YOUR_SONAR_SECRET>
</code>```

finally you need to add your pipeline instruction to your .travis.yml file

Check in your Travis CI repo settings when it should be triggered

here some related links:

Error using Travis CI with Sonarcloud: Not authorized. Please check the properties sonar.login and sonar.password

https://docs.travis-ci.com/user/encryption-keys/#usage

https://github.com/marketplace/actions/sonarcloud-scan

https://sonarcloud.io/documentation/integrations/github/

Body:
I have an experimental project on my Github used for the practising the CI service integrations. I struggle with using Sonarcloud.

I have followed both Tavis CI + Sonarcloud tutorial and Maven example. Mz first confusion starts with the token and properties file whereas the first source suggests creating sonar-project.properties file and the Maven example source does not have any. Here where the documentation is very unclear.

I ignored the properties file and I have done the following steps:

Generated token on sonarcloud.io for my project: e53.....239

Encrypted token on travis-encrypt.github.io since it's the most comfortable way for a Windows user. The 2 following inputs resulted in g3s.....+Q=:

NicharNET/Gistintex

SONAR_TOKEN="e53...239" - I tried both to wrap between quotation marks and without.

Added to Settings -> Environment variable key SONAR_TOKEN with the value of the generated Sonarcloud token e53...239.

Completed travis.yml with the secure token:

language: java
sudo: false
jdk: oraclejdk8

addons:
    sonarcloud:
    organization: "nicharnet-github"
    token:
        secure: "g3sLTdS597mklh1I9HgXr71NRCiOk2n9I41PL2wklnAidwibfocyEcWvSQxjmbhNTjdrcW0cAfzh73Ago8hwfdloraryDY9Ng9L1runxayShtPOqZMPI6nz8zUwLaDfqJVwXWv6A3xICOMFl0UhvF351GPErHhrUO7YIa8el3kESeotYy7kkTzeQ7BA239y7EVFw8H4OCW2gjP2G/InxKnlXfNjgQA3GsnZdJ3uWO3No5kwt5ybfuCCV42cp/UczLIzNbo0RW9Z9jBl5IFMzJaUQUfWV3Pp5QEPmpB7Anr/4W1EtjJPjpSIC/+jBmbrkvC/CSzzTPjaH9LzEQ5m4F5JpRw01blqgKH/153qfs1jRgZK6WVRuhe7yAATHCO/IM0DM+kC0mUJTcXKyv9pRm93E4wp+KzdHYy0LdA83wFgMmvlB8pcm20ImAe7B2SBFx5TGtETa6ea6k2BS+DfBXe6sLBnrl1zZB8nxCDnYiwT1BJFxizgv3EJ6Krjd3cSSxr6PGnXDD/yTeFNJarpMbA+wR6AQetJ89LiDBXYiw6GPgWk/A4vUDIsIaXGqCpydeZHkr2ufS1Ap4yYS0Um2GeDeQXTsBTSCg7BViFgduUI1NPYT1avKg7b64nsdpdjBVofOvzJsgiT66WlaJmt23BUCJsnmXwwEcW1387b4G+Q="

script:
    - mvn clean install org.jacoco:jacoco-maven-plugin:prepare-agent sonar:sonar

Committed and pushed changes into the repository and Travis CI started to work and resulted in:

Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.4.1.1168:sonar (default-cli) on project gistintex: Not authorized. Please check the properties sonar.login and sonar.password.

The error could be found on my Travis CI build. What do I do wrong?

I have skimmed through Error using Travis CI with Sonarcloud: Not authorized. Please check the properties sonar.login and sonar.password SO question and Travis CI Sonarqube analysis article, which unfortunately didn't help me though. My GitHub project source.

I have tried to add these plugins to pom.xml and run the analysis locally:

org.codehaus.mojo: sonar-maven-plugin: 5.1

org.sonarsource.scanner.maven: sonar-maven-plugin: 3.4.1.1168

Running this on my machine resulted in the correct Sonarcloud analysis:

mvn sonar:sonar \
   -Dsonar.organization=nicharnet-github \
   -Dsonar.host.url=https://sonarcloud.io \
   -Dsonar.login=e53.....239

However, my goal is to run the analysis after every committed version using Travis CI. I am sure I have done wrong the key encryption but I can't figure what exactly.

Body:
The key encryption problem usually happens when you execute the generation without the login command against travis.com instead of travis.org

In order to run on every commit you could connect your repo with SonarCloud Scan, generate a secret in your sonarcloud.io project page and there you will find instructions to modify your .travis.yml

if you use travis.org

travis encrypt <YOUR_SONAR_SECRET>

if you use travis.com

travis login --pro

then generate your token like this:

travis encrypt --pro <YOUR_SONAR_SECRET>

finally you need to add your pipeline instruction to your .travis.yml file

Check in your Travis CI repo settings when it should be triggered

here some related links:

Error using Travis CI with Sonarcloud: Not authorized. Please check the properties sonar.login and sonar.password

https://docs.travis-ci.com/user/encryption-keys/#usage

https://github.com/marketplace/actions/sonarcloud-scan

https://sonarcloud.io/documentation/integrations/github/


问:
Pytest: How to redirect logs to console and tmp file created using tmp_path fixture
I am writing one script using pytest  framework, where I need to redirect logs to console as well as temp file created by using fixture(tmp_path). I have written below code, file  is getting created but console logs or logs in files are not observed :

```<code>import os
import logging
from datetime import datetime

global LOG_FILENAME

script_name = os.path.splitext(os.path.basename(__file__))[0]
LOG_FILENAME = datetime.now().strftime(script_name + "_%H_%M_%S_%d_%m_%Y.log")

def test_create_file(tmp_path):
    d = tmp_path / "Logs"
    d.mkdir()
    p = d / LOG_FILENAME

    p.write("content")
    logging.info(p.strpath)
    logging.basicConfig(filename=str(p), level=logging.INFO)
    logging.info(str(p))

    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
    console.setFormatter(formatter)
    logging.getLogger("").addHandler(console)

    logging.info("This is log1 message")
    logging.info("This is log2 message")
    assert p.read_text() == "content"
</code>```

The output I was expecting that my log1 and log2 message should be captured in log file which I created above as well as visible in console. But none of the requirement is fulfilled.
Below is my output:

```<code>nishantsaha@ztphost:~/home/nishantsaha/tests$ python3 -m pytest -v test_tmpdir.py -s
========================================================== test session starts ==========================================================
platform linux -- Python 3.6.9, pytest-5.1.2, py-1.8.0, pluggy-0.13.1 -- /usr/bin/python3
cachedir: .pytest_cache
Test order randomisation NOT enabled. Enable with --random-order or --random-order-bucket=<bucket_type>
metadata: {'Python': '3.6.9', 'Platform': 'Linux-4.15.0-76-generic-x86_64-with-Ubuntu-18.04-bionic', 'Packages': {'pytest': '5.1.2', 'py': '1.8.0', 'pluggy': '0.13.1'}, 'Plugins': {'random-order': '1.0.4', 'json-report': '1.2.0', 'metadata': '1.8.0'}}
rootdir: /home/nishantsaha/tests
plugins: random-order-1.0.4, json-report-1.2.0, metadata-1.8.0
collected 1 item

test_tmpdir.py::test_create_file FAILED
</code>```

Any pointers to what I am missing and how to solve this? If I am using same code but without fixture, in that case logs to file and console both are observed

答:
You need setup your logger("") level to INFO or below, setup handler level only isn't enough.

```<code>logging.getLogger("").setLevel('INFO')
</code>```

By default logger's level is WARNING(30). The effective level is the intersection of your logger's level and handler's level, offered by getEffectiveLevel().

Body:
I am writing one script using pytest  framework, where I need to redirect logs to console as well as temp file created by using fixture(tmp_path). I have written below code, file  is getting created but console logs or logs in files are not observed :

import os
import logging
from datetime import datetime

global LOG_FILENAME

script_name = os.path.splitext(os.path.basename(__file__))[0]
LOG_FILENAME = datetime.now().strftime(script_name + "_%H_%M_%S_%d_%m_%Y.log")

def test_create_file(tmp_path):
    d = tmp_path / "Logs"
    d.mkdir()
    p = d / LOG_FILENAME

    p.write("content")
    logging.info(p.strpath)
    logging.basicConfig(filename=str(p), level=logging.INFO)
    logging.info(str(p))

    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
    console.setFormatter(formatter)
    logging.getLogger("").addHandler(console)

    logging.info("This is log1 message")
    logging.info("This is log2 message")
    assert p.read_text() == "content"

The output I was expecting that my log1 and log2 message should be captured in log file which I created above as well as visible in console. But none of the requirement is fulfilled.
Below is my output:

nishantsaha@ztphost:~/home/nishantsaha/tests$ python3 -m pytest -v test_tmpdir.py -s
========================================================== test session starts ==========================================================
platform linux -- Python 3.6.9, pytest-5.1.2, py-1.8.0, pluggy-0.13.1 -- /usr/bin/python3
cachedir: .pytest_cache
Test order randomisation NOT enabled. Enable with --random-order or --random-order-bucket=<bucket_type>
metadata: {'Python': '3.6.9', 'Platform': 'Linux-4.15.0-76-generic-x86_64-with-Ubuntu-18.04-bionic', 'Packages': {'pytest': '5.1.2', 'py': '1.8.0', 'pluggy': '0.13.1'}, 'Plugins': {'random-order': '1.0.4', 'json-report': '1.2.0', 'metadata': '1.8.0'}}
rootdir: /home/nishantsaha/tests
plugins: random-order-1.0.4, json-report-1.2.0, metadata-1.8.0
collected 1 item

test_tmpdir.py::test_create_file FAILED

Any pointers to what I am missing and how to solve this? If I am using same code but without fixture, in that case logs to file and console both are observed

Body:
You need setup your logger("") level to INFO or below, setup handler level only isn't enough.

logging.getLogger("").setLevel('INFO')

By default logger's level is WARNING(30). The effective level is the intersection of your logger's level and handler's level, offered by getEffectiveLevel().


问:
Android: Unable to add Constraint Set correctly programmatically in Constraint Layout
I have the following xml:

```<code><androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

                <include
                    android:id="@+id/image1"
                    layout="@layout/layout_circular_image"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_bias="0"
                    app:layout_constraintVertical_bias="0"/>

                <include
                    android:id="@+id/image2"
                    layout="@layout/layout_circular_image"
                    android:layout_marginStart="50dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintStart_toStartOf="@+id/image1"
                    app:layout_constraintEnd_toEndOf="@+id/image1"
                    app:layout_constraintHorizontal_bias="0"
                    app:layout_constraintVertical_bias="0"/>

                <include
                    android:id="@+id/image3"
                    layout="@layout/layout_circular_image"
                    android:layout_marginStart="50dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintStart_toStartOf="@+id/image2"
                    app:layout_constraintEnd_toEndOf="@+id/image2"
                    app:layout_constraintHorizontal_bias="0"
                    app:layout_constraintVertical_bias="0"/>

        </androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Now, these are 3 image layouts which are being used within the constraint layout. But I would like to do this dynamically since the number of image views can change.
So I created the following class:

```<code>class MultipleCircularImagesLayout : ConstraintLayout {

lateinit var binding: LayoutMultipleCircularImagesBinding

constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
    init(context)
}

constructor(context: Context) : super(context) {
    init(context)
}

constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    init(context)
}

private fun init(context: Context) {
    binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.layout_multiple_circular_images, this, true)
}

var childImages: List<String> = emptyList()
set(value) {
    field = value

    var previousCircularImageLayout: CircularImageLayout? = null

    for(url in value) {

        val circularImageLayout = CircularImageLayout(context)
        circularImageLayout.id = View.generateViewId()

        val params = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)

        val constraintSet = ConstraintSet()
        constraintSet.clone(binding.layout)

        constraintSet.connect(circularImageLayout.id, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP)
        constraintSet.connect(circularImageLayout.id, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM)

        if (previousCircularImageLayout != null) {
            constraintSet.connect(circularImageLayout.id, ConstraintSet.START, previousCircularImageLayout.id, ConstraintSet.START, 50)
            constraintSet.connect(circularImageLayout.id, ConstraintSet.END, previousCircularImageLayout.id, ConstraintSet.END)
        } else {
            constraintSet.connect(circularImageLayout.id, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START)
            constraintSet.connect(circularImageLayout.id, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END)
            constraintSet.setHorizontalBias(circularImageLayout.id, 0f)
        }
        circularImageLayout.layoutParams = params
        constraintSet.applyTo(this)

        binding.layout.addView(circularImageLayout)
        ImageUtils.loadImage(url, circularImageLayout.binding.image)
        previousCircularImageLayout = circularImageLayout
    }

    invalidate()
}
}
</code>```

When childImages list is set, only one image is displayed within the layout when I do it programatically. But it works perfectly when I hardcode it via the XML shown above.

Could someone please help me understand what is wrong with the code above?

答:
You are trying to connect views in the layout before they are added. The general sequence to add and connect views to a ConstraintLayout is:

Create a view (make sure to generate an id)

Add view to layout (with appropriate layout params)

Repeat above for each view

Clone the constraint set from the layout

Make all the connections for the new views in the constraint set

Apply the constraint set to the layout.

Make this change and you will be one step closer.

Body:
I have the following xml:

<androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

                <include
                    android:id="@+id/image1"
                    layout="@layout/layout_circular_image"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_bias="0"
                    app:layout_constraintVertical_bias="0"/>

                <include
                    android:id="@+id/image2"
                    layout="@layout/layout_circular_image"
                    android:layout_marginStart="50dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintStart_toStartOf="@+id/image1"
                    app:layout_constraintEnd_toEndOf="@+id/image1"
                    app:layout_constraintHorizontal_bias="0"
                    app:layout_constraintVertical_bias="0"/>

                <include
                    android:id="@+id/image3"
                    layout="@layout/layout_circular_image"
                    android:layout_marginStart="50dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintStart_toStartOf="@+id/image2"
                    app:layout_constraintEnd_toEndOf="@+id/image2"
                    app:layout_constraintHorizontal_bias="0"
                    app:layout_constraintVertical_bias="0"/>

        </androidx.constraintlayout.widget.ConstraintLayout>

Now, these are 3 image layouts which are being used within the constraint layout. But I would like to do this dynamically since the number of image views can change.
So I created the following class:

class MultipleCircularImagesLayout : ConstraintLayout {

lateinit var binding: LayoutMultipleCircularImagesBinding

constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
    init(context)
}

constructor(context: Context) : super(context) {
    init(context)
}

constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    init(context)
}

private fun init(context: Context) {
    binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.layout_multiple_circular_images, this, true)
}

var childImages: List<String> = emptyList()
set(value) {
    field = value

    var previousCircularImageLayout: CircularImageLayout? = null

    for(url in value) {

        val circularImageLayout = CircularImageLayout(context)
        circularImageLayout.id = View.generateViewId()

        val params = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)

        val constraintSet = ConstraintSet()
        constraintSet.clone(binding.layout)

        constraintSet.connect(circularImageLayout.id, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP)
        constraintSet.connect(circularImageLayout.id, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM)

        if (previousCircularImageLayout != null) {
            constraintSet.connect(circularImageLayout.id, ConstraintSet.START, previousCircularImageLayout.id, ConstraintSet.START, 50)
            constraintSet.connect(circularImageLayout.id, ConstraintSet.END, previousCircularImageLayout.id, ConstraintSet.END)
        } else {
            constraintSet.connect(circularImageLayout.id, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START)
            constraintSet.connect(circularImageLayout.id, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END)
            constraintSet.setHorizontalBias(circularImageLayout.id, 0f)
        }
        circularImageLayout.layoutParams = params
        constraintSet.applyTo(this)

        binding.layout.addView(circularImageLayout)
        ImageUtils.loadImage(url, circularImageLayout.binding.image)
        previousCircularImageLayout = circularImageLayout
    }

    invalidate()
}
}

When childImages list is set, only one image is displayed within the layout when I do it programatically. But it works perfectly when I hardcode it via the XML shown above.

Could someone please help me understand what is wrong with the code above?


问:
Why is there no simple inbult conveter for Date to LocalDate in java?
Curious about the design choice - is there any authoritative source about the design decision to not have a simple converter for LocalDate -> Date and viceversa baked into the LocalDate object?

I'm fed up of moving these objects around with the completely clunky

```<code>java.util.Date.from(dateToConvert.atStartOfDay()
  .atZone(ZoneId.systemDefault())
  .toInstant());
</code>```

and the other one,

```<code>dateToConvert.toInstant()
  .atZone(ZoneId.systemDefault())
  .toLocalDateTime();
</code>```

And while i know I cannot have date.toLocalDate(nullable ZoneId), it would at least be of some use to know why (if only so I never ever justify a decision using the same logic).

答:
You might as well ask why there is no built in conversion method to turn a File object into an integer: The 2 types are almost entirely unrelated.

But, I hear you say, hold the phone, rzwitserloot! What the heck are you on about? Date and LocalDate are unrelated???

Yes, they are.

Because java.util.Date is a silly name. That's NOT what j.u.Date represents; that's why all the date-related methods in this object are deprecated. Once you see that a class named Date has a method called getHours that should hopefully be a good indication that whomever named it was, let's just go with 'having an off day'. That aint no date.

j.u.Date represents 'a moment in time'. It is the exact equivalent to java.time.Instant. Its internal storage is a single long representing epoch-millis and nothing more.

This has almost no relationship whatsoever with LocalDate.

Yes, MANY systems use a j.u.Date object as a way to represent the same notion that LocalDate is trying to represent, but that is because those systems messed up, and are using an entirely inappropriate type for it. They may be excused; they just fell for the same trap you did: They got thrown off by the name of this class.

Perhaps one might argue: Okay, but, hey, we live in this world and not a fairytale one, so given that so many times 'I need to convert this j.u.Date to LocalDate' comes up, it should be easier, right? Well, enabling bad behaviour just because it is common – let's just say the word is out on whether that's a good idea. Also, that job rather fundamentally is very very tricky. How do we do this conversion? Should I take the moment in time as represented by the j.u.Date object, check out what the actual calendar date is in the current system default locale (as in, go to where the server is. Now go out the building. Find a person. Ask them: What date is it right now? What do they answer?) – or should they go UTC locale? (Go to Greenwich and ask there. Unless it is summer, then ask: What date was it one hour ago?).

The answers obviously won't be the same in many cases, and yet neither strategy is obviously superior to the other. Thus, making such a convenience method is just going to cause epic reams of confusion. You're missing a crucial bit of info, if not more – the job of converting a j.u.Date to a LocalDate cannot be done without further context unless you're willing to just toss a coin on every missing bit of info you have. You might as well invoke a Random instance's .nextInt(365) to figure it out.

Body:
Curious about the design choice - is there any authoritative source about the design decision to not have a simple converter for LocalDate -> Date and viceversa baked into the LocalDate object?

I'm fed up of moving these objects around with the completely clunky

java.util.Date.from(dateToConvert.atStartOfDay()
  .atZone(ZoneId.systemDefault())
  .toInstant());

and the other one,

dateToConvert.toInstant()
  .atZone(ZoneId.systemDefault())
  .toLocalDateTime();

And while i know I cannot have date.toLocalDate(nullable ZoneId), it would at least be of some use to know why (if only so I never ever justify a decision using the same logic).


问:
Python Time without seconds
So I need to display current time, I only print now.hour and now.minutes, however there is always 00 that's displayed for seconds that I would like to take away

this is my code

```<code>    now = datetime.datetime.now()
    print(datetime.time(now.hour, now.minute))
</code>```

this is my out put

```<code>16:40:00
</code>```

答:
You can use strftime to format the time stored in now.

```<code>now
>2020-02-17 09:47:52.429173

print(datetime.strftime(now, '%H:%M'))
09:47
</code>```

The string located in datetime.strftime(--, 'here') defines the formatting that will be returned. You can find more of strftime's formatting specifications here.

Title: Python Time without seconds

Body:
So I need to display current time, I only print now.hour and now.minutes, however there is always 00 that's displayed for seconds that I would like to take away

this is my code

    now = datetime.datetime.now()
    print(datetime.time(now.hour, now.minute))

this is my out put

16:40:00

Body:
You can use strftime to format the time stored in now.

now
>2020-02-17 09:47:52.429173

print(datetime.strftime(now, '%H:%M'))
09:47

The string located in datetime.strftime(--, 'here') defines the formatting that will be returned. You can find more of strftime's formatting specifications here.


问:
How can I convert an array into an Android resource?
I'm new to Android programming, so please let me know if I'm doing anything stupid. However, I currently have an array String[] gamesList that is dynamically generated from a database.

I want to use each element of an array in a Spinner, but the Adapter has a method signature of (Context, int, int). The first and third inputs I can do, but the second is asking for the id of a resource; but I don't have a R.array.someRandomName resource, I only have a local array.

Is there some way to make the array a resource, or if not, how do I do this?

答: If the list of strings is fixed, you can use a String Array. You can also use an ArrayAdapter for dynamically generated arrays of strings.</p>


问:
How do I create padding around the text of a UILabel?
I'm styling a UILabel programmatically and having trouble getting any padding around the label's text:

After studying many SO threads on the subject (this one, in particular) I thought I'd found a solution but it has no affect on the label. I've created a custom class for the label that subclasses UILabel:

```<code>// Swift 3 (I know, I know...)

class PublicationTypeBadge: UILabel {
    var textInsets = UIEdgeInsets.zero {
        didSet { invalidateIntrinsicContentSize() }
    }

    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let insetRect = UIEdgeInsetsInsetRect(bounds, textInsets)
        let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
        let invertedInsets = UIEdgeInsets(top: -textInsets.top,
                                          left: -textInsets.left,
                                          bottom: -textInsets.bottom,
                                          right: -textInsets.right)
        return UIEdgeInsetsInsetRect(textRect, invertedInsets)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, textInsets))
    }
}
</code>```

And I invoke it like so:

```<code>func setPubTypeBadge(publication: PublicationModel, indexPathRow: Int) {
    if let pubType = publication.publicationType,
        let pubEnum = PublicationType(rawValue: pubType) {
        pubTypeBadge.attributedText = pubEnum.getBadgeLabel(using: pubType)
    }

    let rect = pubTypeBadge.textRect(forBounds: pubTypeBadge.frame, limitedToNumberOfLines: 1)
    pubTypeBadge.drawText(in: rect)
    pubTypeBadge.layer.borderColor = UIColor.dsShade3.cgColor
    pubTypeBadge.layer.borderWidth = 1
    pubTypeBadge.layer.cornerRadius = 4
}
</code>```

which does absolutely nothing as far as the padding/insets are concerned. I simplly want 6pts of space on the left/right between the text and the border and 4pts on the top/bottom. Any help greatly appreciated.

答:
You can just add empty space before and after the text:

titleLabel.text = " \(itemName) "

Body:
I'm styling a UILabel programmatically and having trouble getting any padding around the label's text:

After studying many SO threads on the subject (this one, in particular) I thought I'd found a solution but it has no affect on the label. I've created a custom class for the label that subclasses UILabel:

// Swift 3 (I know, I know...)

class PublicationTypeBadge: UILabel {
    var textInsets = UIEdgeInsets.zero {
        didSet { invalidateIntrinsicContentSize() }
    }

    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let insetRect = UIEdgeInsetsInsetRect(bounds, textInsets)
        let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
        let invertedInsets = UIEdgeInsets(top: -textInsets.top,
                                          left: -textInsets.left,
                                          bottom: -textInsets.bottom,
                                          right: -textInsets.right)
        return UIEdgeInsetsInsetRect(textRect, invertedInsets)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, textInsets))
    }
}

And I invoke it like so:

func setPubTypeBadge(publication: PublicationModel, indexPathRow: Int) {
    if let pubType = publication.publicationType,
        let pubEnum = PublicationType(rawValue: pubType) {
        pubTypeBadge.attributedText = pubEnum.getBadgeLabel(using: pubType)
    }

    let rect = pubTypeBadge.textRect(forBounds: pubTypeBadge.frame, limitedToNumberOfLines: 1)
    pubTypeBadge.drawText(in: rect)
    pubTypeBadge.layer.borderColor = UIColor.dsShade3.cgColor
    pubTypeBadge.layer.borderWidth = 1
    pubTypeBadge.layer.cornerRadius = 4
}

which does absolutely nothing as far as the padding/insets are concerned. I simplly want 6pts of space on the left/right between the text and the border and 4pts on the top/bottom. Any help greatly appreciated.


问:
How can I keep a while loop going if the string contains a letter
```<code>while (firstName.//includes a,b,c,d,e,f,g.etc)
{
  //other code here
}
</code>```

I want the while loop to keep going if it includes a letter, please help.

答:
Use .*?[\\p{L}].* as the regex.

If you are sure that your text is purely in English, you can use .*?[A-Za-z].* or .*?[\\p{Alpha}].* alternatively.

Explanation:

.*? looks reluctantly for any character until it yields to another pattern (e.g. [\\p{L}] in this case).

[\\p{L}] looks for a single letter because of [] around \\p{L} where \\p{L} specifies any letter (including unicode).

.* looks for any character.

Demo:

```<code>public class Main {
    public static void main(String[] args) {
        String[] arr = { "123a", "a123", "abc", "123", "123a456", "123ß456" };
        for (String firstName : arr) {
            if (firstName.matches(".*?[\\p{L}].*")) {
                System.out.println(firstName + " meets the criteria.");
            }
        }
    }
}
</code>```

Output:

```<code>123a meets the criteria.
a123 meets the criteria.
abc meets the criteria.
123a456 meets the criteria.
123ß456 meets the criteria.
</code>```

Note that if .*?[A-Za-z].* is used, 123ß456 won't meet the criteria because ß is not part of English alphabets.

Body:
while (firstName.//includes a,b,c,d,e,f,g.etc)
{
  //other code here
}

I want the while loop to keep going if it includes a letter, please help.

Body:
Use .*?[\\p{L}].* as the regex.

If you are sure that your text is purely in English, you can use .*?[A-Za-z].* or .*?[\\p{Alpha}].* alternatively.

Explanation:

.*? looks reluctantly for any character until it yields to another pattern (e.g. [\\p{L}] in this case).

[\\p{L}] looks for a single letter because of [] around \\p{L} where \\p{L} specifies any letter (including unicode).

.* looks for any character.

Demo:

public class Main {
    public static void main(String[] args) {
        String[] arr = { "123a", "a123", "abc", "123", "123a456", "123ß456" };
        for (String firstName : arr) {
            if (firstName.matches(".*?[\\p{L}].*")) {
                System.out.println(firstName + " meets the criteria.");
            }
        }
    }
}

Output:

123a meets the criteria.
a123 meets the criteria.
abc meets the criteria.
123a456 meets the criteria.
123ß456 meets the criteria.

Note that if .*?[A-Za-z].* is used, 123ß456 won't meet the criteria because ß is not part of English alphabets.


问:
Eloquent hasMany relation without id
I to count how many registration exist from the same nation.
So far, I came um with the following solution:
Method inside the Controller:

class Camp extends Model // ...
{
    protected $with = ['registrations_nation_count',...];
    // ...

    public function registrations_nation_count()
    {
        return $this->hasMany(CampRegistration::class)
            ->select(['camp_id','nation',DB::raw('COUNT(*) as count')])
            ->groupBy('nation');
    }
}

```

<p>This generates the following output:</p>

```      "registrations_nation_count": [
            {
                "camp_id": 1,
                "nation": "en",
                "count": 2
            },
            {
                "camp_id": 1,
                "nation": "fr",
                "count": 1
            }
        ]
```

<p>Now I would like to remove the camp_id column from the output. I already tried to simply remove it from the select but this leads to no output at all.
Is there any way to hide it?</p>

<p>Database:</p>

```
+-------+--------------------+
| camps | camp_registrations |
+-------+--------------------+
| id    | id                 |
| ...   | camp_id            |
|       | nation             |
|       | ...                |
+-------+--------------------+
```

答:
You can't not-select the columns that are used to query the relation. In your example, this is the parent model's id and related model's camp_id.

I would strongly advise against having a ->select([..]) columns in the relationship definition. It will unnecessarily limit the use of the relationship.

Instead, you should omit the columns in some sort of transformer (such Eloquent resources) that transforms the resource for the end-user to see.

Title: Eloquent hasMany relation without id

Body:
I to count how many registration exist from the same nation.
So far, I came um with the following solution:
Method inside the Controller:

class Camp extends Model // ...
{
    protected $with = ['registrations_nation_count',...];
    // ...

    public function registrations_nation_count()
    {
        return $this->hasMany(CampRegistration::class)
            ->select(['camp_id','nation',DB::raw('COUNT(*) as count')])
            ->groupBy('nation');
    }
}

This generates the following output:

      "registrations_nation_count": [
            {
                "camp_id": 1,
                "nation": "en",
                "count": 2
            },
            {
                "camp_id": 1,
                "nation": "fr",
                "count": 1
            }
        ]

Now I would like to remove the camp_id column from the output. I already tried to simply remove it from the select but this leads to no output at all.
Is there any way to hide it?

Database:

+-------+--------------------+
| camps | camp_registrations |
+-------+--------------------+
| id    | id                 |
| ...   | camp_id            |
|       | nation             |
|       | ...                |
+-------+--------------------+


问:
When to delete old entries from MySQL DB?
So I run this TYPO3 website with nearly 80 tables. TYPO3 don't delete records really, it only writes an "1" into the table field deleted to mark them. This leads to a big table with many records that are not visible in the application but have to be processed in every database query.

My question is: Until how many dead entries should you keep those entries before facing disadvantages like performance decrease? Is there any known number of entries no matter the server hardware?

Thanks in advance!

答:
TYPO3 has an included task to do cleanups for old/deleted entries, called:

Table garbage collection : cleans up old records from any table in the database.
  See https://docs.typo3.org/c/typo3/cms-scheduler/master/en-us/Installation/BaseTasks/Index.html#table-garbage-collection-task

You may decide, which kind of entries should be cleaned in which period, depend on your use case and your server environment.


问:
using python in c++ basics
can anyone show me a basic program that includes python in a c++ program? i have gotten #include <Python.h> to work, but thats about it. how do you create a string, int, and include a module that is not part of the python library?

答:
Maybe the main Python doc can help here: http://docs.python.org/extending/

Here's a simple module written in C: http://docs.python.org/extending/extending.html#a-simple-example

Title: using python in c++ basics


问:
Write a function to use n percent of cpu usage
My goal is to have a function that receives an int (0-100) and uses that amount of cpu usage on a thread. So if it was given 17, the cpu usage would be 17%. 54, 54%.

I've tried writing functions that add/multiply varying amounts of numbers depending on the input but they always ended up using similar amounts of cpu usage.

This is the basic idea I had but I would continue the varying amounts of multiplications based on the input.

```<code>#include <cstdlib>
#include <iostream>
using namespace std;

int main() {
  int cpu_use;
  cin >> cpu_use;

  int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y,
      z, aa, ba, ca, da, ea, fa, ga, ha, ia, ja, ka, la, ma, na, oa, pa, qa, ra,
      sa, ta, ua, va, wa, xa, ya, za, ab, bb, cb, db, eb, fb, gb, hb, ib, jb,
      kb, lb, mb, nb, ob, pb, qb, rb, sb, tb, ub, vb, wb, xb, yb, zb, ac, bc,
      cc, dc, ec, fc, gc, hc, ic, jc, kc, lc, mc, nc, oc, pc, qc, rc, sc, tc,
      uc, vc;

    switch (cpu_use) {
    case 1:
      a + a;
      break;
    case 2:
      a *a *b *b;
      break;
    case 3:
      a *a *b *b *c *c;
      break;
    case 4:
      a *a *b *b *c *c *d *d;
      break;
    }
  } while (1);

  return 0;
}
</code>```

答:
There isn't a definitive way to do this without the use of external tools. One potential method could be to write a program that attempts to use as much CPU as possible, such as the ones described here - How to get 100% CPU usage from a C program.
Then you could try to limit the CPU usage to a value you want. There are methods described here -C++: Limiting CPU usage intentionally.

This problem is difficult to solve and seems out of scope for someone learning C++ to be given.

Body:
My goal is to have a function that receives an int (0-100) and uses that amount of cpu usage on a thread. So if it was given 17, the cpu usage would be 17%. 54, 54%.

I've tried writing functions that add/multiply varying amounts of numbers depending on the input but they always ended up using similar amounts of cpu usage.

This is the basic idea I had but I would continue the varying amounts of multiplications based on the input.

#include <cstdlib>
#include <iostream>
using namespace std;

int main() {
  int cpu_use;
  cin >> cpu_use;

  int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y,
      z, aa, ba, ca, da, ea, fa, ga, ha, ia, ja, ka, la, ma, na, oa, pa, qa, ra,
      sa, ta, ua, va, wa, xa, ya, za, ab, bb, cb, db, eb, fb, gb, hb, ib, jb,
      kb, lb, mb, nb, ob, pb, qb, rb, sb, tb, ub, vb, wb, xb, yb, zb, ac, bc,
      cc, dc, ec, fc, gc, hc, ic, jc, kc, lc, mc, nc, oc, pc, qc, rc, sc, tc,
      uc, vc;

    switch (cpu_use) {
    case 1:
      a + a;
      break;
    case 2:
      a *a *b *b;
      break;
    case 3:
      a *a *b *b *c *c;
      break;
    case 4:
      a *a *b *b *c *c *d *d;
      break;
    }
  } while (1);

  return 0;
}