问:
Manually changing the sound output device on linux
If you haven't heard of SoundSwitch, its an app for windows that allows you to switch sound output/input devices with a keyboard shortcut. I've made a similar app for linux, but I cant get it to work properly. The majority of the app is done, and if you want to see the full code, its here: https://github.com/boskobs/sound-Source-Switch-4-Linux
Bellow is the part responsible for applying the changes:

```<code>   os.system("pacmd set-default-sink " + str(nextindex))
   output = subprocess.getoutput("pacmd list-sink-inputs")
   for item in output.split("\n"):
      if "index:" in item:
         inputindex = item.strip().replace("index: ","")
         os.system("pacmd move-sink-input " + str(inputindex) + " " + str(nextindex))
</code>```

It changes the default sound output device, and transfers all of the current apps to that device. The problem occurs when I exit an app and switch the output device. Next time I start that app, the device it outputs sound to is the old one that was active before the switch. How can I make the new default output device really work as a default?

答:
[NOTE] Make sure to click on the image links to follow this solution.

Ubuntu 20.04

Run pacmd list-cards to list the audio devices.

pacmd list-cards output

Output devices in settings should match list-cards

To set a device run pacmd set-default-sink bluez_sink.38_18_4C_12_44_0B.a2dp_sink with your own device name.

Then once this works, you can create some keyboard shortcuts.

Keyboard shortcut

add code to shortcut and set

I use ctrl + Home as mine. You can do this for all audio devices and switch between them with ease.

Body:
If you haven't heard of SoundSwitch, its an app for windows that allows you to switch sound output/input devices with a keyboard shortcut. I've made a similar app for linux, but I cant get it to work properly. The majority of the app is done, and if you want to see the full code, its here: https://github.com/boskobs/sound-Source-Switch-4-Linux
Bellow is the part responsible for applying the changes:

   os.system("pacmd set-default-sink " + str(nextindex))
   output = subprocess.getoutput("pacmd list-sink-inputs")
   for item in output.split("\n"):
      if "index:" in item:
         inputindex = item.strip().replace("index: ","")
         os.system("pacmd move-sink-input " + str(inputindex) + " " + str(nextindex))

It changes the default sound output device, and transfers all of the current apps to that device. The problem occurs when I exit an app and switch the output device. Next time I start that app, the device it outputs sound to is the old one that was active before the switch. How can I make the new default output device really work as a default?


来源: stackexchange

问:
How to forward IOCTL's from i2c-dev.c to adapter driver (i2c-rt3352.c)
I'm writing the I2C adapter driver for SOC. This adapter exist now in system and RTC driver works with it via .master_xfer.

I would like to send IOCTL's from application via /dev/i2c. I have loaded i2c_dev and all modules. After sending IOCTL I get following :

```<code>#i2ccmd read 0
i2cdev_open[382]
i2c_dev_get_by_minor[54]
i2c_get_adapter[896]
i2cdev_ioctl[186]
ioctl, cmd=0x03, arg=0x00
i2c_control[731]
i2cdev_release[420]
i2c_put_adapter[910]
</code>```

i2cdev_ioctl method doesn't send I2C_RDWR IOCT'L to my adapter driver.
How can I forward those IOCTL's to i2c-rt3352.c ?

答:
In the output I see you are sending IOCTL 0x03, what is this? is this a custom command?. One of the ways to write/read is I2C_RDWR ioctl command. You need to build the i2c_msgs in your application and issue the I2C_RDWR command using the ioctl. I2C_RDWR is understood only by the i2c-dev driver and it will call the adapter transfer function. </p>

<p>No IOCTL command is passed to adapter driver, there is no way to talk to the adapter driver using IOCTL if you are using i2c-dev driver interface.  </p>

ContentLicense: CC BY-SA 3.0

Body:
I'm writing the I2C adapter driver for SOC. This adapter exist now in system and RTC driver works with it via .master_xfer.

I would like to send IOCTL's from application via /dev/i2c. I have loaded i2c_dev and all modules. After sending IOCTL I get following :

#i2ccmd read 0
i2cdev_open[382]
i2c_dev_get_by_minor[54]
i2c_get_adapter[896]
i2cdev_ioctl[186]
ioctl, cmd=0x03, arg=0x00
i2c_control[731]
i2cdev_release[420]
i2c_put_adapter[910]

i2cdev_ioctl method doesn't send I2C_RDWR IOCT'L to my adapter driver.
How can I forward those IOCTL's to i2c-rt3352.c ?

Body:
In the output I see you are sending IOCTL 0x03, what is this? is this a custom command?. One of the ways to write/read is I2C_RDWR ioctl command. You need to build the i2c_msgs in your application and issue the I2C_RDWR command using the ioctl. I2C_RDWR is understood only by the i2c-dev driver and it will call the adapter transfer function.

No IOCTL command is passed to adapter driver, there is no way to talk to the adapter driver using IOCTL if you are using i2c-dev driver interface.


问:
Angular 12 Content and Map of this Source is not available (only size() is supported)
After upgrading my Angular version to the latest I have the error:

```<code>Content and Map of this Source is not available (only size() is supported)
</code>```

Any helps would be appreciated cause there is not a lot of information about this issue.

答:
I have solved this problem by installing the 'source-map-support' npm package like so:

```<code>npm install source-map-support
</code>```

Check out this link.

ContentLicense: CC BY-SA 4.0

Body:
After upgrading my Angular version to the latest I have the error:

Content and Map of this Source is not available (only size() is supported)

Any helps would be appreciated cause there is not a lot of information about this issue.

Body:
I have solved this problem by installing the 'source-map-support' npm package like so:

npm install source-map-support

Check out this link.


问:
configuring intellij with terraform plugin to connect to aws
I need to be able to run the terraform plugin to do standard terraform tasks such as terraform plan and terraform apply which would require aws connectivity. i have installed the terrafom plugin but have no idea how to configure it</p>

答:
My solution:
I've installed terraform using chocolatey

Set the path in settings

from terraform.exe

to C:\ProgramData\chocolatey\bin\terraform.exe

Intellij will still display it as terraform.exe but it will now work.


问:
Trying to access array offset on value of type null when using RefreshDatabase in Laravel
I am writing tests in a fresh installation of Laravel 6.15 (with Spark 9).  My PHP version is PHP 7.4.2.  My testing environment is Laravel Valet on MacOS.

I am facing an issue where whenever I use the RefreshDatabase trait as part of a test, all tests fail with the trying to access array offset on value of type null error message.

From reading around the suggestion seems to be to downgrade to PHP 7.3 whenever this error is encountered, however there is no mention in the official documentation that PHP 7.4 isn't supported - is there any other way to resolve the error?

It triggers even if the trait is interested into the Laravel example test:

```<code>
namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ExampleTest extends TestCase
{

    Use RefreshDatabase;

    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}
</code>```

Gives

```<code>
PHPUnit 8.5.2 by Sebastian Bergmann and contributors.

.EE                                                                 3 / 3 (100%)

Time: 212 ms, Memory: 22.00 MB

There were 2 errors:

1) Tests\Feature\ExampleTest::testBasicTest
ErrorException: Trying to access array offset on value of type null

/Users/rory/sites/landlord/vendor/laravel/telescope/src/Watchers/QueryWatcher.php:46
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php:369
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php:218
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Connection.php:833
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Connection.php:687
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Connection.php:640
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Connection.php:338
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Connection.php:309
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Schema/Builder.php:75
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php:169
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:590
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php:91
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php:63
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:32
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Container/Util.php:36
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:90
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:34
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Container/Container.php:590
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Console/Command.php:134
/Users/rory/sites/landlord/vendor/symfony/console/Command/Command.php:255
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Console/Command.php:121
/Users/rory/sites/landlord/vendor/symfony/console/Application.php:1012
/Users/rory/sites/landlord/vendor/symfony/console/Application.php:272
/Users/rory/sites/landlord/vendor/symfony/console/Application.php:148
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Console/Application.php:93
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Console/Application.php:185
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:273
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Testing/PendingCommand.php:139
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Testing/PendingCommand.php:238
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithConsole.php:56
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Testing/RefreshDatabase.php:40
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Testing/RefreshDatabase.php:17
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestCase.php:115
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestCase.php:82

</code>```

phpunit.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
         backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>

        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <server name="APP_ENV" value="testing"/>
        <server name="BCRYPT_ROUNDS" value="4"/>
        <server name="CACHE_DRIVER" value="array"/>
        <server name="DB_CONNECTION" value="sqlite"/>
        <server name="DB_DATABASE" value=":memory:"/>
        <server name="MAIL_DRIVER" value="array"/>
        <server name="QUEUE_CONNECTION" value="sync"/>
        <server name="SESSION_DRIVER" value="array"/>
    </php>
</phpunit>
</code>```

答:
This fixed the issue for me

```<code>composer selfupdate
</code>```

I'm using an old Symfony 4 but the behavior should be close for some.

Source

Body:
I am writing tests in a fresh installation of Laravel 6.15 (with Spark 9).  My PHP version is PHP 7.4.2.  My testing environment is Laravel Valet on MacOS.

I am facing an issue where whenever I use the RefreshDatabase trait as part of a test, all tests fail with the trying to access array offset on value of type null error message.

From reading around the suggestion seems to be to downgrade to PHP 7.3 whenever this error is encountered, however there is no mention in the official documentation that PHP 7.4 isn't supported - is there any other way to resolve the error?

It triggers even if the trait is interested into the Laravel example test:

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ExampleTest extends TestCase
{

    Use RefreshDatabase;

    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

Gives

PHPUnit 8.5.2 by Sebastian Bergmann and contributors.

.EE                                                                 3 / 3 (100%)

Time: 212 ms, Memory: 22.00 MB

There were 2 errors:

1) Tests\Feature\ExampleTest::testBasicTest
ErrorException: Trying to access array offset on value of type null

/Users/rory/sites/landlord/vendor/laravel/telescope/src/Watchers/QueryWatcher.php:46
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php:369
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php:218
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Connection.php:833
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Connection.php:687
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Connection.php:640
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Connection.php:338
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Connection.php:309
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Schema/Builder.php:75
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php:169
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:590
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php:91
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php:63
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:32
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Container/Util.php:36
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:90
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:34
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Container/Container.php:590
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Console/Command.php:134
/Users/rory/sites/landlord/vendor/symfony/console/Command/Command.php:255
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Console/Command.php:121
/Users/rory/sites/landlord/vendor/symfony/console/Application.php:1012
/Users/rory/sites/landlord/vendor/symfony/console/Application.php:272
/Users/rory/sites/landlord/vendor/symfony/console/Application.php:148
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Console/Application.php:93
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Console/Application.php:185
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:273
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Testing/PendingCommand.php:139
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Testing/PendingCommand.php:238
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithConsole.php:56
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Testing/RefreshDatabase.php:40
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Testing/RefreshDatabase.php:17
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestCase.php:115
/Users/rory/sites/landlord/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestCase.php:82

phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
         backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>

        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <server name="APP_ENV" value="testing"/>
        <server name="BCRYPT_ROUNDS" value="4"/>
        <server name="CACHE_DRIVER" value="array"/>
        <server name="DB_CONNECTION" value="sqlite"/>
        <server name="DB_DATABASE" value=":memory:"/>
        <server name="MAIL_DRIVER" value="array"/>
        <server name="QUEUE_CONNECTION" value="sync"/>
        <server name="SESSION_DRIVER" value="array"/>
    </php>
</phpunit>

Body:
This fixed the issue for me

composer selfupdate

I'm using an old Symfony 4 but the behavior should be close for some.

Source


问:
Dynamic .htaccess file in PHP
As part of a project, we're currently looking at adding in SEO URLs to pages. This is for an online store, and there are numerous types of content within the site: static pages (for example "About Us", "Privacy Policy", product categories and product pages.

We have the numerous URL stubs stored in a MySQL table as follows:

```<code>+-----------------+------------------+----------------+
|    url_stub     | destination type | destination_id |
+-----------------+------------------+----------------+
| privacy-policy/ |       page       |       1        |
+-----------------+------------------+----------------+
|   category-1/   |     category     |       2        |
+-----------------+------------------+----------------+
|  my-product-1/  |      product     |       1        |
+-----------------+------------------+----------------+
</code>```

One option to serve these up would be to have a huge index.php file which is capable of handling everything, however, we would much prefer to have separate pages to serve up the different content types. For example anything with a destination_type of page would go to page.php?id=#, and so forth. So, for the examples in the table above, these would be directed as follows:

```<code>privacy-policy/ = page.php?id=1
category-1/     = category.php?cat=2
my-product-1/   = product.php?prod=1
</code>```

My question is this: what would be the best practice to achieve this? We don't want to include the destination_id anywhere in the SEO-friendly URL. I was thinking that it might be possible to create a dynamic .htaccess file which outputs everything on the fly with mod_rewrite, but I can't find any solutions.

Any help or comments would be most gratefully received.

答:
Short answer would be "no you have to rewrite it every time" but this older question should answer yours :) Can I make a dynamic .htaccess file?

Otherwise, complicated/stupid/useless idea:

```<code>RewriteRule /(.*)  /index.php?url=$1
</code>```

Then in your PHP file

```<code>if (isset($_GET['url']))
{
  //Parse url and echo page according to requested url
}
</code>```

Title: Dynamic .htaccess file in PHP

Body:
As part of a project, we're currently looking at adding in SEO URLs to pages. This is for an online store, and there are numerous types of content within the site: static pages (for example "About Us", "Privacy Policy", product categories and product pages.

We have the numerous URL stubs stored in a MySQL table as follows:

+-----------------+------------------+----------------+
|    url_stub     | destination type | destination_id |
+-----------------+------------------+----------------+
| privacy-policy/ |       page       |       1        |
+-----------------+------------------+----------------+
|   category-1/   |     category     |       2        |
+-----------------+------------------+----------------+
|  my-product-1/  |      product     |       1        |
+-----------------+------------------+----------------+

One option to serve these up would be to have a huge index.php file which is capable of handling everything, however, we would much prefer to have separate pages to serve up the different content types. For example anything with a destination_type of page would go to page.php?id=#, and so forth. So, for the examples in the table above, these would be directed as follows:

privacy-policy/ = page.php?id=1
category-1/     = category.php?cat=2
my-product-1/   = product.php?prod=1

My question is this: what would be the best practice to achieve this? We don't want to include the destination_id anywhere in the SEO-friendly URL. I was thinking that it might be possible to create a dynamic .htaccess file which outputs everything on the fly with mod_rewrite, but I can't find any solutions.

Any help or comments would be most gratefully received.

Body:
Short answer would be "no you have to rewrite it every time" but this older question should answer yours :) Can I make a dynamic .htaccess file?

Otherwise, complicated/stupid/useless idea:

RewriteRule /(.*)  /index.php?url=$1

Then in your PHP file

if (isset($_GET['url']))
{
  //Parse url and echo page according to requested url
}


问:
TypeError: 'module' object is not callable from Jupyter notebook
I am trying to use a module located in the same directory as the script I am running and I get the following error:

TypeError: 'module' object is not callable

This was working before, but I did some modifications to the sys.path list since I wanted to call modules from other directories, and from that point it stopped working.

This is my folder's structure:

```<code>Neural_Network/
  split_data.py
  test.ipynb
</code>```

I get the error executing test.ipynb:

```<code>import split_data
import os

print(split_data.__file__)
trainset, testset, valset = split_data.split_data_func(os.path('data'))
</code>```

```<code>TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4936/633432209.py in <module>
      4
      5 print(split_data.__file__)
----> 6 trainset, testset, valset = split_data.split_data_func(os.path('data'))
      7
      8 """"

TypeError: 'module' object is not callable
</code>```

print(split_data.__file__) is giving the right path to the module.

The module split_data.py has a single function:

```<code>import math
import os
import random
def split_data_func(path):
...
  return trainset, testset, valset
</code>```

This was working before and I don't know what could have happened.

In the sys.path I have the path to Neural_Network/ directory.

UPDATE

I was looking the error regarding the split_data module and the error was with the os module, I just changed to:

```<code>trainset, testset, valset = split_data.split_data_func(os.path.join(os.getcwd(),'dataset_days'))
</code>```

答:
os.path is a module which contains functions. Since it's a module, you can't use it as a function. Did you mean pathlib.Path instead of os.path? Or did you mean to call one of the functions within, like os.path.join('data', split_data.__file__)?

The error is unrelated to the code being  run in a notebook, it's a common python error.

Body:
I am trying to use a module located in the same directory as the script I am running and I get the following error:

TypeError: 'module' object is not callable

This was working before, but I did some modifications to the sys.path list since I wanted to call modules from other directories, and from that point it stopped working.

This is my folder's structure:

Neural_Network/
  split_data.py
  test.ipynb

I get the error executing test.ipynb:

import split_data
import os

print(split_data.__file__)
trainset, testset, valset = split_data.split_data_func(os.path('data'))

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4936/633432209.py in <module>
      4
      5 print(split_data.__file__)
----> 6 trainset, testset, valset = split_data.split_data_func(os.path('data'))
      7
      8 """"

TypeError: 'module' object is not callable

print(split_data.__file__) is giving the right path to the module.

The module split_data.py has a single function:

import math
import os
import random
def split_data_func(path):
...
  return trainset, testset, valset

This was working before and I don't know what could have happened.

In the sys.path I have the path to Neural_Network/ directory.

UPDATE

I was looking the error regarding the split_data module and the error was with the os module, I just changed to:

trainset, testset, valset = split_data.split_data_func(os.path.join(os.getcwd(),'dataset_days'))


问:
How to add optional chaining to JSON object?
I am trying to compare a value within a JSON object with a variable:

```<code>if (resp.userdetails.name == username) {
// do something
}
</code>```

The problem is that not all resp objects have userdetails, so I get this error message sometimes:

Cannot read properties of undefined (reading 'name')

I have tried to use ? to say it might be optional (or not exist):

```<code>if (resp.userdetails?.name == username)
</code>```

But I get an Unexpected token error in that case.

Can someone please tell me how I can update my if statement to say userdetails may not always be in the response, but if it is, then check name is equal to username?

答:
Either:

Use a JS engine which supports optional chaining

Use a tool like Babel to transpile your JS from a modern version of the language to an older one which doesn't support optional chaining

Manually test for the object existing before you try to read a property from it

```<code>if (resp.userdetails && resp.userdetails.name == username)

</code>```

Body:
I am trying to compare a value within a JSON object with a variable:

if (resp.userdetails.name == username) {
// do something
}

The problem is that not all resp objects have userdetails, so I get this error message sometimes:

Cannot read properties of undefined (reading 'name')

I have tried to use ? to say it might be optional (or not exist):

if (resp.userdetails?.name == username)

But I get an Unexpected token error in that case.

Can someone please tell me how I can update my if statement to say userdetails may not always be in the response, but if it is, then check name is equal to username?

Body:
Either:

Use a JS engine which supports optional chaining

Use a tool like Babel to transpile your JS from a modern version of the language to an older one which doesn't support optional chaining

Manually test for the object existing before you try to read a property from it

if (resp.userdetails && resp.userdetails.name == username)


问:
dbWriteTable function returning TRUE status even if it fails to insert record as it violates the schema constraints
I am using DBI, RMySql packages for interacting with MySql database.

Here are more details about configuration:

R version: 3.3.2

DBI version: 0.7

RMySql version: 0.10.13

Below is the schema for table Site:

```<code>+------------+-------------+------+-----+---------+----------------+
| Field      | Type        | Null | Key | Default | Extra          |
+------------+-------------+------+-----+---------+----------------+
| id         | int(11)     | NO   | PRI | NULL    | auto_increment |
| short_name | varchar(10) | NO   | UNI | NULL    |                |
| full_name  | varchar(50) | NO   | UNI | NULL    |                |
+------------+-------------+------+-----+---------+----------------+
</code>```

As you can see that the fields short_name & full_name are having UNIQUE & NOT NULL constraints.

On trying to insert a row with the duplicate short_name or full_name which already exist in the table, dbWriteTable does not let happen such row insertion but it returns the TRUE status even though it violates the UNIQUE constraint. Same thing happens for NOT NULL constraint as well.

Is this the expected behavior of DBI & dbWriteTable? Why it's not returning the FALSE status?

EDIT: I also observed that even dbSendStatement() and dbSendQuery() does not give any error in case of constraint violation. Is there any way to get to know this?

答:
I feel like there has to be a better way to do this, but the solution I'm aware of is to use a tryCatch to capture the error messages. There are other options here than capturing the messages...you could for instance take an action instead.

The reason dbWriteTable doesn't return FALSE is explained in the documentation. It only returns FALSE if there was a problem with the DBI functions. Your problem is in the database. I know it is semantics, but it makes a difference here.

I made up an example because I didn't have one from the question.

```<code>library(DBI)
library(RSQLite)

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbSendQuery(con,
            "CREATE TABLE mtcars
            (
              mpg REAL,
              cyl INTEGER,
              disp REAL,
              hp REAL,
              drat REAL NOT NULL
            );")

dbWriteTable(con, "mtcars", mtcars[1:5,1:5], append = TRUE)

test_db <- dbGetQuery(con,"SELECT * FROM mtcars")
test_db
# mpg cyl disp  hp drat
# 1 21.0   6  160 110 3.90
# 2 21.0   6  160 110 3.90
# 3 22.8   4  108  93 3.85
# 4 21.4   6  258 110 3.08
# 5 18.7   8  360 175 3.15

# Can't capture output
result <- dbWriteTable(con, "mtcars",
             data.frame(mpg = 1, cyl = 2, disp = 3, hp = 4, drat = NA),
             append = TRUE)
result
# Error: object 'result' not found

# Let's try checking exceptions
# This doesn't work because it is checking for exceptions in the DBI commands...not in the database.
result <- dbGetException(con)
result
# $errorNum
# [1] 0
#
# $errorMsg
# [1] "OK"

# Because of the error there wasn't a change in the database.
test_db <- dbGetQuery(con,"SELECT * FROM mtcars")
test_db
# mpg cyl disp  hp drat
# 1 21.0   6  160 110 3.90
# 2 21.0   6  160 110 3.90
# 3 22.8   4  108  93 3.85
# 4 21.4   6  258 110 3.08
# 5 18.7   8  360 175 3.15

# We can use a tryCatch to capture error or warning messages
tryCatch({
  dbWriteTable(con, "mtcars",
               data.frame(mpg = 1, cyl = 2, disp = 3, hp = 4, drat = NA),
               append = TRUE)
  result <- dbGetException(con)
},
  error = function(e) result <<- conditionMessage(e),
  warning = function(w) result <<- conditionMessage(w)
)
</code>```

Body:
I am using DBI, RMySql packages for interacting with MySql database.

Here are more details about configuration:

R version: 3.3.2

DBI version: 0.7

RMySql version: 0.10.13

Below is the schema for table Site:

+------------+-------------+------+-----+---------+----------------+
| Field      | Type        | Null | Key | Default | Extra          |
+------------+-------------+------+-----+---------+----------------+
| id         | int(11)     | NO   | PRI | NULL    | auto_increment |
| short_name | varchar(10) | NO   | UNI | NULL    |                |
| full_name  | varchar(50) | NO   | UNI | NULL    |                |
+------------+-------------+------+-----+---------+----------------+

As you can see that the fields short_name & full_name are having UNIQUE & NOT NULL constraints.

On trying to insert a row with the duplicate short_name or full_name which already exist in the table, dbWriteTable does not let happen such row insertion but it returns the TRUE status even though it violates the UNIQUE constraint. Same thing happens for NOT NULL constraint as well.

Is this the expected behavior of DBI & dbWriteTable? Why it's not returning the FALSE status?

EDIT: I also observed that even dbSendStatement() and dbSendQuery() does not give any error in case of constraint violation. Is there any way to get to know this?

Body:
I feel like there has to be a better way to do this, but the solution I'm aware of is to use a tryCatch to capture the error messages. There are other options here than capturing the messages...you could for instance take an action instead.

The reason dbWriteTable doesn't return FALSE is explained in the documentation. It only returns FALSE if there was a problem with the DBI functions. Your problem is in the database. I know it is semantics, but it makes a difference here.

I made up an example because I didn't have one from the question.

library(DBI)
library(RSQLite)

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbSendQuery(con,
            "CREATE TABLE mtcars
            (
              mpg REAL,
              cyl INTEGER,
              disp REAL,
              hp REAL,
              drat REAL NOT NULL
            );")

dbWriteTable(con, "mtcars", mtcars[1:5,1:5], append = TRUE)

test_db <- dbGetQuery(con,"SELECT * FROM mtcars")
test_db
# mpg cyl disp  hp drat
# 1 21.0   6  160 110 3.90
# 2 21.0   6  160 110 3.90
# 3 22.8   4  108  93 3.85
# 4 21.4   6  258 110 3.08
# 5 18.7   8  360 175 3.15

# Can't capture output
result <- dbWriteTable(con, "mtcars",
             data.frame(mpg = 1, cyl = 2, disp = 3, hp = 4, drat = NA),
             append = TRUE)
result
# Error: object 'result' not found

# Let's try checking exceptions
# This doesn't work because it is checking for exceptions in the DBI commands...not in the database.
result <- dbGetException(con)
result
# $errorNum
# [1] 0
#
# $errorMsg
# [1] "OK"

# Because of the error there wasn't a change in the database.
test_db <- dbGetQuery(con,"SELECT * FROM mtcars")
test_db
# mpg cyl disp  hp drat
# 1 21.0   6  160 110 3.90
# 2 21.0   6  160 110 3.90
# 3 22.8   4  108  93 3.85
# 4 21.4   6  258 110 3.08
# 5 18.7   8  360 175 3.15

# We can use a tryCatch to capture error or warning messages
tryCatch({
  dbWriteTable(con, "mtcars",
               data.frame(mpg = 1, cyl = 2, disp = 3, hp = 4, drat = NA),
               append = TRUE)
  result <- dbGetException(con)
},
  error = function(e) result <<- conditionMessage(e),
  warning = function(w) result <<- conditionMessage(w)
)


问:
jQuery/JavaScript "this" pointer confusion
The behavior of "this" when function bar is called is baffling me. See the code below. Is there any way to arrange for "this" to be a plain old js object instance when bar is called from a click handler, instead of being the html element?

```<code>// a class with a method

function foo() {

    this.bar();  // when called here, "this" is the foo instance

    var barf = this.bar;
    barf();   // when called here, "this" is the global object

    // when called from a click, "this" is the html element
    $("#thing").after($("<div>click me</div>").click(barf));
}

foo.prototype.bar = function() {
    alert(this);
}
</code>```

答:
Get the book: JavaScript: the Good Parts.

Also, read as much as you can by Douglas Crockford
http://www.crockford.com/javascript/

OwnerDisplayName: I. J. Kennedy

ContentLicense: CC BY-SA 2.5

Body:
The behavior of "this" when function bar is called is baffling me. See the code below. Is there any way to arrange for "this" to be a plain old js object instance when bar is called from a click handler, instead of being the html element?

// a class with a method

function foo() {

    this.bar();  // when called here, "this" is the foo instance

    var barf = this.bar;
    barf();   // when called here, "this" is the global object

    // when called from a click, "this" is the html element
    $("#thing").after($("
click me
").click(barf));
}

foo.prototype.bar = function() {
    alert(this);
}

OwnerDisplayName: Chris Brandsma


问:
Laravel 8.4 – Remove Public from URL
I am working on creating a website that converts text into speech. I am using the script from codecanyon which is Developed with PHP 7.4.x and Laravel 8.4.x . The issue I am facing is that I don't want to show /public URL as a permalink to access the website. Now, if I type mywebsite.com/pubic then the website is accessible otherwise if I write mywebsite.com then it only shows the files. I followed some of the previous queries posted on StackOverflow but got no results.
The topic I followed is Laravel 5 – Remove Public from URL
I tried even by renaming server.php , copying .htaccess and rewriting it. But those all resulted in a screen showing up errors or even blank.

My .htaccess file is;

```<code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</code>```

答:
If you want to only use .htacces, you just need to rewrite all requests from /public to /</p>
```<code>RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L,R=301]
</code>```

Title: Laravel 8.4 – Remove Public from URL

Body:
I am working on creating a website that converts text into speech. I am using the script from codecanyon which is Developed with PHP 7.4.x and Laravel 8.4.x . The issue I am facing is that I don't want to show /public URL as a permalink to access the website. Now, if I type mywebsite.com/pubic then the website is accessible otherwise if I write mywebsite.com then it only shows the files. I followed some of the previous queries posted on StackOverflow but got no results.
The topic I followed is Laravel 5 – Remove Public from URL
I tried even by renaming server.php , copying .htaccess and rewriting it. But those all resulted in a screen showing up errors or even blank.

My .htaccess file is;

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

Body:
If you want to only use .htacces, you just need to rewrite all requests from /public to /

RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L,R=301]


问:
how to save a function pointer with dyn parameters in a structure
I'm getting

```<code>error[E0308]: mismatched types
  --> src/main.rs:38:39
   |
37 |     fn set_source_outcome<S: Source, O: Outcome>(&mut self, selector: fn(s: &S) -> &O) {
   |                           - this type parameter
38 |         self.selector = Some(Box::new(selector));
   |                                       ^^^^^^^^ expected trait object `dyn Source`, found type parameter `S`
   |
   = note: expected fn pointer `for<'r> fn(&'r (dyn Source + 'r)) -> &'r (dyn Outcome + 'r)`
              found fn pointer `for<'r> fn(&'r S) -> &'r O`
   = help: type parameters must be constrained to match other types
   = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters
</code>```

when trying to save a function with dyn parameters in a structure, like this:

struct X {
    selector: Option<Box<fn(s: &dyn Source) -> &dyn Outcome>>,
}

impl X {
    fn set_source_outcome<S: Source, O: Outcome>(&mut self, selector: fn(s: &S) -> &O) {
        self.selector = Some(Box::new(selector));
    }
}
```

Is there any way to do so?
playground: here

答:
ok, looks somewhat like but still works playground

a more straightforward solution is most welcome

Body:
I'm getting

error[E0308]: mismatched types
  --> src/main.rs:38:39
   |
37 |     fn set_source_outcome<S: Source, O: Outcome>(&mut self, selector: fn(s: &S) -> &O) {
   |                           - this type parameter
38 |         self.selector = Some(Box::new(selector));
   |                                       ^^^^^^^^ expected trait object `dyn Source`, found type parameter `S`
   |
   = note: expected fn pointer `for<'r> fn(&'r (dyn Source + 'r)) -> &'r (dyn Outcome + 'r)`
              found fn pointer `for<'r> fn(&'r S) -> &'r O`
   = help: type parameters must be constrained to match other types
   = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

when trying to save a function with dyn parameters in a structure, like this:

struct X {
    selector: Option<Box<fn(s: &dyn Source) -> &dyn Outcome>>,
}

impl X {
    fn set_source_outcome<S: Source, O: Outcome>(&mut self, selector: fn(s: &S) -> &O) {
        self.selector = Some(Box::new(selector));
    }
}

Is there any way to do so?
playground: here


问:
"Content and Map of this Source is not available" error after upgrading to Webpack 5
My project was working fine. When I upgraded to Webpack 5 this issue occurred. I searched online, but all the discussions seem to be from a previous version and I even tried the workarounds specified, but to no avail.

\SourceCode\node_modules\webpack\node_modules\webpack-sources\lib\SizeOnlySource.js:26
throw this._error();
^
Error: Content and Map of this Source is not available (only size() is supported)

答:
I have encountered the same issue today and I was able to solve the problem by installing the 'source-map-support' npm package:

```<code>npm install source-map-support
</code>```

I hope this works for you as well.

Body:
I have encountered the same issue today and I was able to solve the problem by installing the 'source-map-support' npm package:

npm install source-map-support

I hope this works for you as well.


问:
Sweeping matrix by second matrix by group
I have a problem and I am unable to find similar results (also because I am not sure how to word the search itself).
I have a huge matrix with multiple columns.  This matrix also has a column that specifies the "identity" of each line.
I also have a second matrix with thresholds for each column for each identity.
I can simplify the problem with the following code (although, take in mind that I have many many columns).

```<code>temp_df=data.frame(a_name=rep(c("A","B", "C"), 20), matrix(rnorm(40),nrow=60, ncol=2))
</code>```

That contains:

```<code>> head(temp_df)
  a_name          X1         X2
1      A  0.31469191 -0.2763107
2      B -1.17477425 -0.2066650
3      C  0.10651550  0.1581325
4      A -1.88258477 -0.9280463
5      B -2.58260181  1.0322196
6      C  0.03027953  0.3110290
</code>```

And the threshold matrix:

```<code>temp_limits=data.frame(a_name=c("A", "B", "C"), X1=c(1, 0.5, 0), x2=c(-1, -0.5, -0.25))
</code>```

That contains:

```<code>> temp_limits
  a_name  X1    x2
1      A 1.0 -1.00
2      B 0.5 -0.50
3      C 0.0 -0.25
</code>```

I could process the matrix as follow to obtain what I want:

```<code>res_df=NULL
for(i in unique(temp_df$a_name)){
  tdf=temp_df[temp_df$a_name==i,]
  a_lim=temp_limits[temp_limits$a_name==i,]
  tdf[, 2:3]=sweep(as.matrix(tdf[, 2:3]), MARGIN=2, a_lim[, 2:3], FUN=">" )
  res_df=rbind(res_df, tdf)
}
</code>```

That gives what I want:

```<code>> head(res_df)
   a_name    X1    X2
1       A FALSE  TRUE
4       A FALSE  TRUE
7       A FALSE  TRUE
10      A FALSE  TRUE
13      A FALSE FALSE
16      A FALSE  TRUE
</code>```

But I believe this implementation is too long, cumbersome, and not optimal.
I am thinking I should use group_by, by I am unsure on how to proceed.
Any help?

答:
You can try this</p>
```<code>cbind(temp_df[1], temp_df[-1] > temp_limits[match(temp_df$a_name, temp_limits$a_name), -1])
</code>```

Body:
I have a problem and I am unable to find similar results (also because I am not sure how to word the search itself).
I have a huge matrix with multiple columns.  This matrix also has a column that specifies the "identity" of each line.
I also have a second matrix with thresholds for each column for each identity.
I can simplify the problem with the following code (although, take in mind that I have many many columns).

temp_df=data.frame(a_name=rep(c("A","B", "C"), 20), matrix(rnorm(40),nrow=60, ncol=2))

That contains:

> head(temp_df)
  a_name          X1         X2
1      A  0.31469191 -0.2763107
2      B -1.17477425 -0.2066650
3      C  0.10651550  0.1581325
4      A -1.88258477 -0.9280463
5      B -2.58260181  1.0322196
6      C  0.03027953  0.3110290

And the threshold matrix:

temp_limits=data.frame(a_name=c("A", "B", "C"), X1=c(1, 0.5, 0), x2=c(-1, -0.5, -0.25))

That contains:

> temp_limits
  a_name  X1    x2
1      A 1.0 -1.00
2      B 0.5 -0.50
3      C 0.0 -0.25

I could process the matrix as follow to obtain what I want:

res_df=NULL
for(i in unique(temp_df$a_name)){
  tdf=temp_df[temp_df$a_name==i,]
  a_lim=temp_limits[temp_limits$a_name==i,]
  tdf[, 2:3]=sweep(as.matrix(tdf[, 2:3]), MARGIN=2, a_lim[, 2:3], FUN=">" )
  res_df=rbind(res_df, tdf)
}

That gives what I want:

> head(res_df)
   a_name    X1    X2
1       A FALSE  TRUE
4       A FALSE  TRUE
7       A FALSE  TRUE
10      A FALSE  TRUE
13      A FALSE FALSE
16      A FALSE  TRUE

But I believe this implementation is too long, cumbersome, and not optimal.
I am thinking I should use group_by, by I am unsure on how to proceed.
Any help?

Body:
You can try this

cbind(temp_df[1], temp_df[-1] > temp_limits[match(temp_df$a_name, temp_limits$a_name), -1])


问:
Huggingface AutoTokenizer can't load from local path
I'm trying to run language model finetuning script (run_language_modeling.py) from huggingface examples with my own tokenizer(just added in several tokens, see the comments). I have problem loading the tokenizer. I think the problem is with AutoTokenizer.from_pretrained('local/path/to/directory').

Code:

```<code>from transformers import *

tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
# special_tokens = ['<HASHTAG>', '<URL>', '<AT_USER>', '<EMOTICON-HAPPY>', '<EMOTICON-SAD>']
# tokenizer.add_tokens(special_tokens)
tokenizer.save_pretrained('../twitter/twittertokenizer/')
tmp = AutoTokenizer.from_pretrained('../twitter/twittertokenizer/')
</code>```

Error Message:

```<code>OSError                                   Traceback (most recent call last)
/z/huggingface_venv/lib/python3.7/site-packages/transformers/configuration_utils.py in get_config_dict(cls, pretrained_model_name_or_path, pretrained_config_archive_map, **kwargs)
    248                 resume_download=resume_download,
--> 249                 local_files_only=local_files_only,
    250             )

/z/huggingface_venv/lib/python3.7/site-packages/transformers/file_utils.py in cached_path(url_or_filename, cache_dir, force_download, proxies, resume_download, user_agent, extract_compressed_file, force_extract, local_files_only)
    265         # File, but it doesn't exist.
--> 266         raise EnvironmentError("file {} not found".format(url_or_filename))
    267     else:

OSError: file ../twitter/twittertokenizer/config.json not found

During handling of the above exception, another exception occurred:

OSError                                   Traceback (most recent call last)
<ipython-input-32-662067cb1297> in <module>
----> 1 tmp = AutoTokenizer.from_pretrained('../twitter/twittertokenizer/')

/z/huggingface_venv/lib/python3.7/site-packages/transformers/tokenization_auto.py in from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs)
    190         config = kwargs.pop("config", None)
    191         if not isinstance(config, PretrainedConfig):
--> 192             config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
    193
    194         if "bert-base-japanese" in pretrained_model_name_or_path:

/z/huggingface_venv/lib/python3.7/site-packages/transformers/configuration_auto.py in from_pretrained(cls, pretrained_model_name_or_path, **kwargs)
    192         """
    193         config_dict, _ = PretrainedConfig.get_config_dict(
--> 194             pretrained_model_name_or_path, pretrained_config_archive_map=ALL_PRETRAINED_CONFIG_ARCHIVE_MAP, **kwargs
    195         )
    196

/z/huggingface_venv/lib/python3.7/site-packages/transformers/configuration_utils.py in get_config_dict(cls, pretrained_model_name_or_path, pretrained_config_archive_map, **kwargs)
    270                     )
    271                 )
--> 272             raise EnvironmentError(msg)
    273
    274         except json.JSONDecodeError:

OSError: Can't load '../twitter/twittertokenizer/'. Make sure that:

- '../twitter/twittertokenizer/' is a correct model identifier listed on 'https://huggingface.co/models'

- or '../twitter/twittertokenizer/' is the correct path to a directory containing a 'config.json' file
</code>```

If I change  AutoTokenizer to BertTokenizer, the code above can work. Also I can run the script without any problem is I load by shortcut name instead of path. But in the script run_language_modeling.py it uses AutoTokenizer. I'm looking for a way to get it running.

Any idea? Thanks!

答:
when loading modified tokenizer or pretrained tokenizer you should load it as follows:

tokenizer = AutoTokenizer.from_pretrained(path_to_json_file_of_tokenizer, config=AutoConfig.from_pretrained('path to thefolderthat contains the config file of the model'))

Body:
I'm trying to run language model finetuning script (run_language_modeling.py) from huggingface examples with my own tokenizer(just added in several tokens, see the comments). I have problem loading the tokenizer. I think the problem is with AutoTokenizer.from_pretrained('local/path/to/directory').

Code:

from transformers import *

tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
# special_tokens = ['<HASHTAG>', '<URL>', '<AT_USER>', '<EMOTICON-HAPPY>', '<EMOTICON-SAD>']
# tokenizer.add_tokens(special_tokens)
tokenizer.save_pretrained('../twitter/twittertokenizer/')
tmp = AutoTokenizer.from_pretrained('../twitter/twittertokenizer/')

Error Message:

OSError                                   Traceback (most recent call last)
/z/huggingface_venv/lib/python3.7/site-packages/transformers/configuration_utils.py in get_config_dict(cls, pretrained_model_name_or_path, pretrained_config_archive_map, **kwargs)
    248                 resume_download=resume_download,
--> 249                 local_files_only=local_files_only,
    250             )

/z/huggingface_venv/lib/python3.7/site-packages/transformers/file_utils.py in cached_path(url_or_filename, cache_dir, force_download, proxies, resume_download, user_agent, extract_compressed_file, force_extract, local_files_only)
    265         # File, but it doesn't exist.
--> 266         raise EnvironmentError("file {} not found".format(url_or_filename))
    267     else:

OSError: file ../twitter/twittertokenizer/config.json not found

During handling of the above exception, another exception occurred:

OSError                                   Traceback (most recent call last)
<ipython-input-32-662067cb1297> in <module>
----> 1 tmp = AutoTokenizer.from_pretrained('../twitter/twittertokenizer/')

/z/huggingface_venv/lib/python3.7/site-packages/transformers/tokenization_auto.py in from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs)
    190         config = kwargs.pop("config", None)
    191         if not isinstance(config, PretrainedConfig):
--> 192             config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
    193
    194         if "bert-base-japanese" in pretrained_model_name_or_path:

/z/huggingface_venv/lib/python3.7/site-packages/transformers/configuration_auto.py in from_pretrained(cls, pretrained_model_name_or_path, **kwargs)
    192         """
    193         config_dict, _ = PretrainedConfig.get_config_dict(
--> 194             pretrained_model_name_or_path, pretrained_config_archive_map=ALL_PRETRAINED_CONFIG_ARCHIVE_MAP, **kwargs
    195         )
    196

/z/huggingface_venv/lib/python3.7/site-packages/transformers/configuration_utils.py in get_config_dict(cls, pretrained_model_name_or_path, pretrained_config_archive_map, **kwargs)
    270                     )
    271                 )
--> 272             raise EnvironmentError(msg)
    273
    274         except json.JSONDecodeError:

OSError: Can't load '../twitter/twittertokenizer/'. Make sure that:

- '../twitter/twittertokenizer/' is a correct model identifier listed on 'https://huggingface.co/models'

- or '../twitter/twittertokenizer/' is the correct path to a directory containing a 'config.json' file

If I change  AutoTokenizer to BertTokenizer, the code above can work. Also I can run the script without any problem is I load by shortcut name instead of path. But in the script run_language_modeling.py it uses AutoTokenizer. I'm looking for a way to get it running.

Any idea? Thanks!


问:
Scalar Variables from Perl to Python?
I am translating a program from perl to python and I really don't know how to translate a scalar variable to python. My problem is that I want to call the first value that comes in based on all the scalar variables used in the code, a scalar variable when mentioned it refers to the value assigned to it.

the specific area was

```<code>my $min = $_[0];
my $max = $_[1];
</code>```

So these two variables were assigned a value before hand, now what I am trying to do is call my min and let it be the first value that comes, then I want my max to be called as the second value that comes in. Basically, trying to gather the info that was generated to min and max and now bring it to here. Do not understand how to do this in python.

The thing is that I have 3-5 different values assigned to min and also to max, I dont know how to bring in the value.

i am the one who put the question, but I logged in as i think a temporary user and it got deleted. Thanks!

答:
Yes, I'm sure you're talking about subroutine args! In Python, you don't receive arguments in a single list '@_' as in Perl. instead, the simplest way to do this is:

```<code>def func(arg1, arg2):
   min = arg1
   max = arg2
   #do your stuff
</code>```

This is roughly equivalent to:

```<code>sub func{
   my($min, $max) = @_;
   #your stuff
}
</code>```

Now if you must receive your args as a list or as a tuple (both are collections), this should do:

```<code>def func(args):
    min, max = args[0], args[1]
    #your stuff
</code>```

You can replace `args' with anything you like, staying within Python variable naming rules.

I recommend you read up on the book linked to in the previous answer and especially on functions, as Python has a plethora of possibilities when it comes to functions - positional and keyword arguments and the likes..

OwnerDisplayName: MIT

Title: Scalar Variables from Perl to Python?

Body:
I am translating a program from perl to python and I really don't know how to translate a scalar variable to python. My problem is that I want to call the first value that comes in based on all the scalar variables used in the code, a scalar variable when mentioned it refers to the value assigned to it.

the specific area was

my $min = $_[0];
my $max = $_[1];

So these two variables were assigned a value before hand, now what I am trying to do is call my min and let it be the first value that comes, then I want my max to be called as the second value that comes in. Basically, trying to gather the info that was generated to min and max and now bring it to here. Do not understand how to do this in python.

The thing is that I have 3-5 different values assigned to min and also to max, I dont know how to bring in the value.

i am the one who put the question, but I logged in as i think a temporary user and it got deleted. Thanks!

Body:
Yes, I'm sure you're talking about subroutine args! In Python, you don't receive arguments in a single list '@_' as in Perl. instead, the simplest way to do this is:

def func(arg1, arg2):
   min = arg1
   max = arg2
   #do your stuff

This is roughly equivalent to:

sub func{
   my($min, $max) = @_;
   #your stuff
}

Now if you must receive your args as a list or as a tuple (both are collections), this should do:

def func(args):
    min, max = args[0], args[1]
    #your stuff

You can replace `args' with anything you like, staying within Python variable naming rules.

I recommend you read up on the book linked to in the previous answer and especially on functions, as Python has a plethora of possibilities when it comes to functions - positional and keyword arguments and the likes..


问:
Not sending data to Application Insights from Function App
I have Function App and Application Insight services. I've noticed that amount of data which my application sends is big and generates big costs. Can I disable/completely stop sending data to AI without deleting APPINSIGHTS_INSTRUMENTATIONKEY or APPLICATIONINSIGHTS_CONNECTION_STRING? But of course I want keep the both services alive.

Should host.json be configured in some way?

答:
Here is the workaround I did for Optimizing the cost generated by Application Insights Logs:

To minimize the number of logs, you can use the higher logging level of logs in  host.json  as you can see in the below screenshot:

As you can see the minimization of logs here function information log is not produced and the output log is shown in the browser, only the manual logging is shown in the logs/terminal.

And the other ways of reducing the logs and optimizing the AI Cost for Azure Functions:

- Disable unneeded modules: Edit the ApplicationInsights.config to turn off collection modules which are not required.

- Disable telemetry dynamically:  To disable telemetry conditionally and dynamically anywhere in the code, set the  DisableTelemetry  flag on it using  TelemetryConfiguration  instance.

This code sample prevents the sending of telemetry to Application Insights but not the automatic collection modules from colleting telemetry and in order to remove auto collection modules also, please refer this  Microsoft Documentation.

- . Customize Logs Collection:

```<code>{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    },
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Information"
      }
    }
  }
}

</code>```

The following above configuration allows Application Insights to capture all  Information  logs and severe  warning  logs. To change this behavior, explicitly override the logging configuration for the provider  ApplicationInsights  as shown below:

```<code>{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

</code>```

There are few more techniques to manage the data volume used for telemetry data optimizing also like:

Sampling:

Daily Cap:

Pre-aggregate metrics

Please check these references for more information:

Resolve if logs shows twice in Application Insights

Optimizing logging costs of Azure Functions

Configuring or removing the necessary Telemetry Initializers

Also, Please visit my practical workarounds (Ref1, Ref2)to reduce the unnecessary logs and optimize the cost.

Body:
Here is the workaround I did for Optimizing the cost generated by Application Insights Logs:

To minimize the number of logs, you can use the higher logging level of logs in  host.json  as you can see in the below screenshot:

As you can see the minimization of logs here function information log is not produced and the output log is shown in the browser, only the manual logging is shown in the logs/terminal.

And the other ways of reducing the logs and optimizing the AI Cost for Azure Functions:

- Disable unneeded modules: Edit the ApplicationInsights.config to turn off collection modules which are not required.

- Disable telemetry dynamically:  To disable telemetry conditionally and dynamically anywhere in the code, set the  DisableTelemetry  flag on it using  TelemetryConfiguration  instance.

This code sample prevents the sending of telemetry to Application Insights but not the automatic collection modules from colleting telemetry and in order to remove auto collection modules also, please refer this  Microsoft Documentation.

- . Customize Logs Collection:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    },
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Information"
      }
    }
  }
}

The following above configuration allows Application Insights to capture all  Information  logs and severe  warning  logs. To change this behavior, explicitly override the logging configuration for the provider  ApplicationInsights  as shown below:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

There are few more techniques to manage the data volume used for telemetry data optimizing also like:

Sampling:

Daily Cap:

Pre-aggregate metrics

Please check these references for more information:

Resolve if logs shows twice in Application Insights

Optimizing logging costs of Azure Functions

Configuring or removing the necessary Telemetry Initializers

Also, Please visit my practical workarounds (Ref1, Ref2)to reduce the unnecessary logs and optimize the cost.


问:
SQL Server - Add results of a SELECT query to an existing table
I currently have a table in SQL Server called masterTable. What I'd like to do is to add a new column to this table called report_Date.

I would like to store the results of a SELECT query in the report_Date column. The query works fine (it converts a nvarchar into a desired date format). What I can't do is append the results to the column.

My query:

```<code>SELECT
    CONVERT(varchar(10), CAST(FileName AS date), 103) AS FileName
FROM dbo.masterTable
</code>```

Any suggestions please?

答:
If I understand your question correctly then</p>
```<code>UPDATE dbo.masterTable SET
 report_Date = CONVERT(varchar(10), CAST(FileName as date), 103)
</code>```

Body:
I currently have a table in SQL Server called masterTable. What I'd like to do is to add a new column to this table called report_Date.

I would like to store the results of a SELECT query in the report_Date column. The query works fine (it converts a nvarchar into a desired date format). What I can't do is append the results to the column.

My query:

SELECT
    CONVERT(varchar(10), CAST(FileName AS date), 103) AS FileName
FROM dbo.masterTable

Any suggestions please?

Body:
If I understand your question correctly then

UPDATE dbo.masterTable SET
 report_Date = CONVERT(varchar(10), CAST(FileName as date), 103)


问:
ERROR !The requested handler 'docker status' was not found in either the main handlers list nor in the listening handlers list
I'm using vagrant to create a simulation of a prod cluster in which there a a master and two nodes, my vagrantfile look like this  :

IMAGE_NAME = "bento/ubuntu-16.04"
N = 2

Vagrant.configure("2") do |config|
    config.ssh.insert_key = false

    config.vm.provider "virtualbox" do |v|
        v.memory = 1024
        v.cpus = 2
    end

    config.vm.define "k8s-master" do |master|
        master.vm.box = IMAGE_NAME
        master.vm.network "private_network", ip: "192.168.50.10"
        master.vm.hostname = "k8s-master"
        master.vm.provision "ansible" do |ansible|
            ansible.playbook = "kubernetes-setup/master-playbook.yml"
            ansible.extra_vars = {
                node_ip: "192.168.50.10",
            }
        end
    end

    (1..N).each do |i|
        config.vm.define "node-#{i}" do |node|
            node.vm.box = IMAGE_NAME
            node.vm.network "private_network", ip: "192.168.50.#{i + 10}"
            node.vm.hostname = "node-#{i}"
            node.vm.provision "ansible" do |ansible|
                ansible.playbook = "kubernetes-setup/node-playbook.yml"
                ansible.extra_vars = {
                    node_ip: "192.168.50.#{i + 10}",
                }
            end
        end
    end
end

```
<p>and my master playbook look like this :</p>
<pre class="lang-yaml prettyprint-override"><code>
---
- hosts: all
  become: true
  tasks:
  - name: Install packages that allow apt to be used over HTTPS
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - apt-transport-https
      - ca-certificates
      - curl
      - gnupg-agent
      - software-properties-common

  - name: Add an apt signing key for Docker
    apt_key:
      url: https://download.docker.com/linux/ubuntu/gpg
      state: present

  - name: Add apt repository for stable version
    apt_repository:
      repo: deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable
      state: present

  - name: Install docker and its dependecies
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - docker-ce
      - docker-ce-cli
      - containerd.io
    notify:
      - docker status

  - name: Add vagrant user to docker group
    user:
      name: vagrant
      group: docker

  - name: Remove swapfile from /etc/fstab
    mount:
       name: "{{ item }}"
       fstype: swap
       state: absent
    with_items:
        - swap
        - none

   - name: Disable swap
     command: swapoff -a
     when: ansible_swaptotal_mb > 0

  - name: Add an apt signing key for Kubernetes
    apt_key:
      url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
      state: present

  - name: Adding apt repository for Kubernetes
    apt_repository:
      repo: deb https://apt.kubernetes.io/ kubernetes-xenial main
      state: present
      filename: kubernetes.list

  - name: Install Kubernetes binaries
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
        - kubelet
        - kubeadm
        - kubectl

  - name: Configure node ip
    lineinfile:
      path: /etc/default/kubelet
      line: KUBELET_EXTRA_ARGS=--node-ip={{ node_ip }}

  - name: Restart kubelet
    service:
      name: kubelet
      daemon_reload: yes
      state: restarted
  - name: Initialize the Kubernetes cluster using kubeadm
    command: kubeadm init --apiserver-advertise-address="192.168.50.10" --apiserver-cert-extra-sans="192.168.50.10"  --node-name k8s-master --pod-network-cidr=192.168.0.0/16

  - name: Setup kubeconfig for vagrant user
    command: "{{ item }}"
    with_items:
     - mkdir -p /home/vagrant/.kube
     - cp -i /etc/kubernetes/admin.conf /home/vagrant/.kube/config
     - chown vagrant:vagrant /home/vagrant/.kube/config
  - name: Install calico pod network
    become: false
    command: kubectl create -f https://docs.projectcalico.org/v3.4/getting-started/kubernetes/installation/hosted/calico.yaml

  - name: Generate join command
    command: kubeadm token create --print-join-command
    register: join_command

  - name: Copy join command to local file
    local_action: copy content="{{ join_command.stdout_lines[0] }}" dest="./join-command"

  handlers:
    - name: docker status
      service: name=docker state=started

</code>```

while the one used for the nodes is here below :

---
- hosts: all
  become: true
  tasks:
  - name: Install packages that allow apt to be used over HTTPS
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - apt-transport-https
      - ca-certificates
      - curl
      - gnupg-agent
      - software-properties-common

  - name: Add an apt signing key for Docker
    apt_key:
      url: https://download.docker.com/linux/ubuntu/gpg
      state: present

  - name: Add apt repository for stable version
    apt_repository:
      repo: deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable
      state: present

  - name: Install docker and its dependecies
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - docker-ce
      - docker-ce-cli
      - containerd.io
    notify:
      - docker status

  - name: Add vagrant user to docker group
    user:
      name: vagrant
      group: docker
  - name: Remove swapfile from /etc/fstab
    mount:
      name: "{{ item }}"
      fstype: swap
      state: absent
    with_items:
      - swap
      - none

  - name: Disable swap
    command: swapoff -a
    when: ansible_swaptotal_mb > 0

  - name: Add an apt signing key for Kubernetes
    apt_key:
      url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
      state: present

  - name: Adding apt repository for Kubernetes
    apt_repository:
      repo: deb https://apt.kubernetes.io/ kubernetes-xenial main
      state: present
      filename: kubernetes.list

  - name: Install Kubernetes binaries
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
        - kubelet
        - kubeadm
        - kubectl

  - name: Configure node ip
    lineinfile:
      path: /etc/default/kubelet
      line: KUBELET_EXTRA_ARGS=--node-ip={{ node_ip }}

  - name: Restart kubelet
    service:
      name: kubelet
      daemon_reload: yes
      state: restarted

  - name: Initialize the Kubernetes cluster using kubeadm
    command: kubeadm init --apiserver-advertise-address="192.168.50.10" --apiserver-cert-extra-sans="192.168.50.10"  --node-name k8s-master --pod-network-cidr=192.168.0.0/16

  - name: Copy the join command to server location
    copy: src=join-command dest=/tmp/join-command.sh mode=0777

  - name: Join the node to cluster
    command: sh /tmp/join-command.sh

```
<p>but when I launch my vagrant everything goes well until the installation of docker task on the node where I am facing this issue :</p>
<pre class="lang-sh prettyprint-override"><code>Vagrant has automatically selected the compatibility mode '2.0'
according to the Ansible version installed (2.9.6).

Alternatively, the compatibility mode can be specified in your Vagrantfile:
https://www.vagrantup.com/docs/provisioning/ansible_common.html#compatibility_mode

    node-1: Running ansible-playbook...

PLAY [all] *********************************************************************

TASK [Gathering Facts] *********************************************************
[DEPRECATION WARNING]: Distribution Ubuntu 16.04 on host node-1 should use
/usr/bin/python3, but is using /usr/bin/python for backward compatibility with
prior Ansible releases. A future Ansible release will default to using the
discovered platform python for this host. See https://docs.ansible.com/ansible/
2.9/reference_appendices/interpreter_discovery.html for more information. This
feature will be removed in version 2.12. Deprecation warnings can be disabled
by setting deprecation_warnings=False in ansible.cfg.
ok: [node-1]

TASK [Install packages that allow apt to be used over HTTPS] *******************
changed: [node-1]
[WARNING]: Updating cache and auto-installing missing dependency: python-apt

TASK [Add an apt signing key for Docker] ***************************************
changed: [node-1]

TASK [Add apt repository for stable version] ***********************************
changed: [node-1]

TASK [Install docker and its dependecies] **************************************
*****ERROR! The requested handler 'docker status' was not found in either the main handlers list nor in the listening handlers list
Ansible failed to complete successfully. Any error output should be
visible above. Please fix these errors and try again.*****

</code>```

Anyone have a clue what could be the reason, I have tried to change the syntax but still I don't think it is a typo problem ?

答: As @zeitounator said in his command I forgot to add the handler part in the nodes configuration playbook, once it was added everything went well.</p>

Body:
I'm using vagrant to create a simulation of a prod cluster in which there a a master and two nodes, my vagrantfile look like this  :

IMAGE_NAME = "bento/ubuntu-16.04"
N = 2

Vagrant.configure("2") do |config|
    config.ssh.insert_key = false

    config.vm.provider "virtualbox" do |v|
        v.memory = 1024
        v.cpus = 2
    end

    config.vm.define "k8s-master" do |master|
        master.vm.box = IMAGE_NAME
        master.vm.network "private_network", ip: "192.168.50.10"
        master.vm.hostname = "k8s-master"
        master.vm.provision "ansible" do |ansible|
            ansible.playbook = "kubernetes-setup/master-playbook.yml"
            ansible.extra_vars = {
                node_ip: "192.168.50.10",
            }
        end
    end

    (1..N).each do |i|
        config.vm.define "node-#{i}" do |node|
            node.vm.box = IMAGE_NAME
            node.vm.network "private_network", ip: "192.168.50.#{i + 10}"
            node.vm.hostname = "node-#{i}"
            node.vm.provision "ansible" do |ansible|
                ansible.playbook = "kubernetes-setup/node-playbook.yml"
                ansible.extra_vars = {
                    node_ip: "192.168.50.#{i + 10}",
                }
            end
        end
    end
end

and my master playbook look like this :

---
- hosts: all
  become: true
  tasks:
  - name: Install packages that allow apt to be used over HTTPS
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - apt-transport-https
      - ca-certificates
      - curl
      - gnupg-agent
      - software-properties-common

  - name: Add an apt signing key for Docker
    apt_key:
      url: https://download.docker.com/linux/ubuntu/gpg
      state: present

  - name: Add apt repository for stable version
    apt_repository:
      repo: deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable
      state: present

  - name: Install docker and its dependecies
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - docker-ce
      - docker-ce-cli
      - containerd.io
    notify:
      - docker status

  - name: Add vagrant user to docker group
    user:
      name: vagrant
      group: docker

  - name: Remove swapfile from /etc/fstab
    mount:
       name: "{{ item }}"
       fstype: swap
       state: absent
    with_items:
        - swap
        - none

   - name: Disable swap
     command: swapoff -a
     when: ansible_swaptotal_mb > 0

  - name: Add an apt signing key for Kubernetes
    apt_key:
      url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
      state: present

  - name: Adding apt repository for Kubernetes
    apt_repository:
      repo: deb https://apt.kubernetes.io/ kubernetes-xenial main
      state: present
      filename: kubernetes.list

  - name: Install Kubernetes binaries
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
        - kubelet
        - kubeadm
        - kubectl

  - name: Configure node ip
    lineinfile:
      path: /etc/default/kubelet
      line: KUBELET_EXTRA_ARGS=--node-ip={{ node_ip }}

  - name: Restart kubelet
    service:
      name: kubelet
      daemon_reload: yes
      state: restarted
  - name: Initialize the Kubernetes cluster using kubeadm
    command: kubeadm init --apiserver-advertise-address="192.168.50.10" --apiserver-cert-extra-sans="192.168.50.10"  --node-name k8s-master --pod-network-cidr=192.168.0.0/16

  - name: Setup kubeconfig for vagrant user
    command: "{{ item }}"
    with_items:
     - mkdir -p /home/vagrant/.kube
     - cp -i /etc/kubernetes/admin.conf /home/vagrant/.kube/config
     - chown vagrant:vagrant /home/vagrant/.kube/config
  - name: Install calico pod network
    become: false
    command: kubectl create -f https://docs.projectcalico.org/v3.4/getting-started/kubernetes/installation/hosted/calico.yaml

  - name: Generate join command
    command: kubeadm token create --print-join-command
    register: join_command

  - name: Copy join command to local file
    local_action: copy content="{{ join_command.stdout_lines[0] }}" dest="./join-command"

  handlers:
    - name: docker status
      service: name=docker state=started

while the one used for the nodes is here below :

---
- hosts: all
  become: true
  tasks:
  - name: Install packages that allow apt to be used over HTTPS
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - apt-transport-https
      - ca-certificates
      - curl
      - gnupg-agent
      - software-properties-common

  - name: Add an apt signing key for Docker
    apt_key:
      url: https://download.docker.com/linux/ubuntu/gpg
      state: present

  - name: Add apt repository for stable version
    apt_repository:
      repo: deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable
      state: present

  - name: Install docker and its dependecies
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
      - docker-ce
      - docker-ce-cli
      - containerd.io
    notify:
      - docker status

  - name: Add vagrant user to docker group
    user:
      name: vagrant
      group: docker
  - name: Remove swapfile from /etc/fstab
    mount:
      name: "{{ item }}"
      fstype: swap
      state: absent
    with_items:
      - swap
      - none

  - name: Disable swap
    command: swapoff -a
    when: ansible_swaptotal_mb > 0

  - name: Add an apt signing key for Kubernetes
    apt_key:
      url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
      state: present

  - name: Adding apt repository for Kubernetes
    apt_repository:
      repo: deb https://apt.kubernetes.io/ kubernetes-xenial main
      state: present
      filename: kubernetes.list

  - name: Install Kubernetes binaries
    apt:
      name: "{{ packages }}"
      state: present
      update_cache: yes
    vars:
      packages:
        - kubelet
        - kubeadm
        - kubectl

  - name: Configure node ip
    lineinfile:
      path: /etc/default/kubelet
      line: KUBELET_EXTRA_ARGS=--node-ip={{ node_ip }}

  - name: Restart kubelet
    service:
      name: kubelet
      daemon_reload: yes
      state: restarted

  - name: Initialize the Kubernetes cluster using kubeadm
    command: kubeadm init --apiserver-advertise-address="192.168.50.10" --apiserver-cert-extra-sans="192.168.50.10"  --node-name k8s-master --pod-network-cidr=192.168.0.0/16

  - name: Copy the join command to server location
    copy: src=join-command dest=/tmp/join-command.sh mode=0777

  - name: Join the node to cluster
    command: sh /tmp/join-command.sh

but when I launch my vagrant everything goes well until the installation of docker task on the node where I am facing this issue :

Vagrant has automatically selected the compatibility mode '2.0'
according to the Ansible version installed (2.9.6).

Alternatively, the compatibility mode can be specified in your Vagrantfile:
https://www.vagrantup.com/docs/provisioning/ansible_common.html#compatibility_mode

    node-1: Running ansible-playbook...

PLAY [all] *********************************************************************

TASK [Gathering Facts] *********************************************************
[DEPRECATION WARNING]: Distribution Ubuntu 16.04 on host node-1 should use
/usr/bin/python3, but is using /usr/bin/python for backward compatibility with
prior Ansible releases. A future Ansible release will default to using the
discovered platform python for this host. See https://docs.ansible.com/ansible/
2.9/reference_appendices/interpreter_discovery.html for more information. This
feature will be removed in version 2.12. Deprecation warnings can be disabled
by setting deprecation_warnings=False in ansible.cfg.
ok: [node-1]

TASK [Install packages that allow apt to be used over HTTPS] *******************
changed: [node-1]
[WARNING]: Updating cache and auto-installing missing dependency: python-apt

TASK [Add an apt signing key for Docker] ***************************************
changed: [node-1]

TASK [Add apt repository for stable version] ***********************************
changed: [node-1]

TASK [Install docker and its dependecies] **************************************
*****ERROR! The requested handler 'docker status' was not found in either the main handlers list nor in the listening handlers list
Ansible failed to complete successfully. Any error output should be
visible above. Please fix these errors and try again.*****

Anyone have a clue what could be the reason, I have tried to change the syntax but still I don't think it is a typo problem ?


问:
Next.js return (failed)net::ERR_UNKNOWN_URL_SCHEME for imported images
I am using Next.js + styled-components + TypeScript. I want to use background-image: url() where I import image from assets folder present inside src folder. In network tab, when I look for images, it says in status:

(failed)net::ERR_UNKNOWN_URL_SCHEME and the url is
src:/_next/static/image/public/right.e158775f9c1cf296e36177bfb86a5ced.svg;height:32px;width:32px;

Which does not display image.

Assets folder is present in /src/assets/left.svg.

If I import the same image in index.tsx file and render it in Image component it works fine.

```<code>// styles.tsx

import styled from 'styled-components';
import Left from '../../assets/left.svg';
import Right from '../../assets/right.svg';

export const SwiperWrapper = styled.div`
  margin-top: 2.5rem;
  position: relative;
  .swiper-position {
    position: static !important;
  }
  .swiper-button-next:after,
  .swiper-button-prev:after {
    content: '';
  }
  .swiper-button-prev {
    background-image: url(${Left});
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center;
    -webkit-tap-highlight-color: transparent;
    top: 100%;
  }
  .swiper-button-next {
    background-image: url(${Right});
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center;
    -webkit-tap-highlight-color: transparent;
  }
`;
</code>```

答:
Instead of moving all our images to public folder you can just use

background-image: url(${Left.src});
```
<p>This is what worked for me:)</p>
<p>Note:
Actually <code>Left</code> will be an object if you try to <code>console.log</code> it, it will be something like:</p>
<pre class="lang-js prettyprint-override"><code>{
blurDataURL: "/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fleft.475f00e5.png&w=8&q=70"
height: 1321
src: "/_next/static/media/left.475f00e5.png"
width: 1321
}
</code>```

Body:
I am using Next.js + styled-components + TypeScript. I want to use background-image: url() where I import image from assets folder present inside src folder. In network tab, when I look for images, it says in status:

(failed)net::ERR_UNKNOWN_URL_SCHEME and the url is
src:/_next/static/image/public/right.e158775f9c1cf296e36177bfb86a5ced.svg;height:32px;width:32px;

Which does not display image.

Assets folder is present in /src/assets/left.svg.

If I import the same image in index.tsx file and render it in Image component it works fine.

// styles.tsx

import styled from 'styled-components';
import Left from '../../assets/left.svg';
import Right from '../../assets/right.svg';

export const SwiperWrapper = styled.div`
  margin-top: 2.5rem;
  position: relative;
  .swiper-position {
    position: static !important;
  }
  .swiper-button-next:after,
  .swiper-button-prev:after {
    content: '';
  }
  .swiper-button-prev {
    background-image: url(${Left});
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center;
    -webkit-tap-highlight-color: transparent;
    top: 100%;
  }
  .swiper-button-next {
    background-image: url(${Right});
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center;
    -webkit-tap-highlight-color: transparent;
  }
`;

Body:
Instead of moving all our images to public folder you can just use

background-image: url(${Left.src});

This is what worked for me:)

Note:
Actually Left will be an object if you try to console.log it, it will be something like:

{
blurDataURL: "/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fleft.475f00e5.png&w=8&q=70"
height: 1321
src: "/_next/static/media/left.475f00e5.png"
width: 1321
}


问:
Populating an HTML table from an external XML
I have come across a problem while fetching data from an external XML document with JS. I have been following the w3schools tutorial for AJAX XML so far, but I ran into something I couldn't solve. I have a XML that looks like this:

```<code><root>
 <document-id>
    <author>Tom Riddle</autor>
    <title>abzy</title>
    <year>1995</year>
 </document-id>
 <document-id>
    <author>Tom Riddle</autor>
    <title>abzy</title>
 </document-id>
 <document-id>
    <author>Tom Riddle</autor>
    <year>1995</year>
 </document-id>
</root>
</code>```

I want to dynamically access the data inside the XML and create a table while doing so. It works fine for the one DOM Element all documents share, but it gives me an error as soon as I include year or title. I guess it's because the tags are empty in some parts of the tree. Is there a way to ignore empty tags and only write something in the column if there is a value inside? Thank you for your time and knowledge.

THIS IS THE ASSOCIATED HTML

```<code><body>
    <header>
        <h1>Reading Data from XML Files</h1>
    </header>
    <main>

        <button type="button" onclick="loadDoc()">Get my CD collection</button>

        <table id="demo">

        </table>

    </main>
    <script>
       function loadDoc() {
          const xhttp = new XMLHttpRequest();
          xhttp.onload = function() {
            myFunction(this);
          }
          xhttp.open("GET", "books.xml");
          xhttp.send();
        }
        function myFunction(xml) {
          const xmlDoc = xml.responseXML;
          const x = xmlDoc.getElementsByTagName("document-id");
          console.log(x)
          let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>";
          for (let i = 0; i <x.length; i++) {
            table += "<tr><td>" +
            x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue +
            "</tr>";
          }
          document.getElementById("demo").innerHTML = table;
        }
    </script>
</body>
</code>```

答:
try this with in line solution to check if tag exist in xml</p>
```<code>function myFunction(xml) {
      const xmlDoc = xml.responseXML;
      const x = xmlDoc.getElementsByTagName("document-id");
      console.log(x)
      let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>";

     for (let i = 0; i <x.length; i++) {
        table += "<tr><td>" +
        x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
         "</td><td>" +   ((x[i].getElementsByTagName("title")[0] == undefined)?"": x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue )    +
        "</td><td>" +
      ((x[i].getElementsByTagName("year")[0] == undefined)?"": x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue )    +
        "</tr>";
      }

      document.getElementById("demo").innerHTML = table;
    }
</code>```

Body:
I have come across a problem while fetching data from an external XML document with JS. I have been following the w3schools tutorial for AJAX XML so far, but I ran into something I couldn't solve. I have a XML that looks like this:

<root>
 <document-id>
    <author>Tom Riddle</autor>
    <title>abzy</title>
    <year>1995</year>
 </document-id>
 <document-id>
    <author>Tom Riddle</autor>
    <title>abzy</title>
 </document-id>
 <document-id>
    <author>Tom Riddle</autor>
    <year>1995</year>
 </document-id>
</root>

I want to dynamically access the data inside the XML and create a table while doing so. It works fine for the one DOM Element all documents share, but it gives me an error as soon as I include year or title. I guess it's because the tags are empty in some parts of the tree. Is there a way to ignore empty tags and only write something in the column if there is a value inside? Thank you for your time and knowledge.

THIS IS THE ASSOCIATED HTML

Reading Data from XML Files

        <button type="button" onclick="loadDoc()">Get my CD collection</button>

Body:
try this with in line solution to check if tag exist in xml

function myFunction(xml) {
      const xmlDoc = xml.responseXML;
      const x = xmlDoc.getElementsByTagName("document-id");
      console.log(x)
      let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>";

     for (let i = 0; i <x.length; i++) {
        table += "<tr><td>" +
        x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
         "</td><td>" +   ((x[i].getElementsByTagName("title")[0] == undefined)?"": x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue )    +
        "</td><td>" +
      ((x[i].getElementsByTagName("year")[0] == undefined)?"": x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue )    +
        "</tr>";
      }

      document.getElementById("demo").innerHTML = table;
    }


问:
C++ equivalent of Java StringUtils.indexOfDifference
For C++20, is there a library equivalent of Java's StringUtils.indexOfDifference()?

What is the efficient way of comparing two large strings and determining where they differ?

答:
You can use std::mismatch if you take care about the different cases that lead to an end iterator in the result:

```<code>#include <algorithm>
#include <string>
#include <iterator>
#include <iostream>

void mism(const std::string& a, const std::string& b){
    auto its = std::mismatch(a.begin(), std::next(a.begin(),std::min(a.size(),b.size())),b.begin());
    if (its.first == a.end() && its.second == b.end()) {
        std::cout << "the strings are equal\n";
    } else if (its.first != a.end() && its.second != b.end()){
        std::cout << "the strings differ at " << *(its.first) << " and " << *(its.second) << "\n";
    } else if (its.first == a.end()) {
        std::cout << "the second string starts with the first\n";
    } else if (its.second == b.end()) {
        std::cout << "the first string start with the second\n";
    }
}
int main() {
    mism("foo1abc","foo2abc");
    mism("foo","foo");
    mism("foo123","foo");
    mism("foo","foo123");

}
</code>```

Body:
You can use std::mismatch if you take care about the different cases that lead to an end iterator in the result:

#include <algorithm>
#include <string>
#include <iterator>
#include <iostream>

void mism(const std::string& a, const std::string& b){
    auto its = std::mismatch(a.begin(), std::next(a.begin(),std::min(a.size(),b.size())),b.begin());
    if (its.first == a.end() && its.second == b.end()) {
        std::cout << "the strings are equal\n";
    } else if (its.first != a.end() && its.second != b.end()){
        std::cout << "the strings differ at " << *(its.first) << " and " << *(its.second) << "\n";
    } else if (its.first == a.end()) {
        std::cout << "the second string starts with the first\n";
    } else if (its.second == b.end()) {
        std::cout << "the first string start with the second\n";
    }
}
int main() {
    mism("foo1abc","foo2abc");
    mism("foo","foo");
    mism("foo123","foo");
    mism("foo","foo123");

}


问:
Flask: current_user becomes anonymous outside of route
Have had a look at similar questions but haven't found one that explains why the current_user value is wiped after my login function runs.

My login route:

```<code>@app.route("/login", methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password, form.password.data):
            login_user(user, remember=form.remember.data)
            return redirect(url_for('home'))
        flash('Login Unsuccessful. Please check email and password', 'danger')
    return render_template('login.html', title='Login', form=form)
</code>```

My registration & login forms

```<code>class RegistrationForm(FlaskForm):
  username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
  email = StringField('Email', validators=[DataRequired(), Email()])
  password = PasswordField('Password', validators=[DataRequired()])
  confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
  submit = SubmitField('Sign Up')

class LoginForm(FlaskForm):

  email = StringField('Email', validators=[DataRequired(), Email()])
  password = PasswordField('Password', validators=[DataRequired()])
  remember = BooleanField('Remember Me')
  submit = SubmitField('Login')

</code>```

Using pbd I can see that once I have logged in, current_user is set to my login details, but once I am returned to the homepage, it returns to - AnonymousUserMixin.

This means my

```<code>def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
</code>```

does not get triggered when clicking to the home or login page.

I am following the Corey Schafer flask guide, specifically lesson 6:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog/06-Login-Auth

The full repo for my code is available here:
https://github.com/gog99/Flaskblog

Thank you very much for the help :)

答:
@Blomex was correct, cannot believe this had me stuck for so long-

In models.py,

Old:

```<code>@login_manager.user_loader
def load_user(user_id):
    User.query.get(int(user_id))
</code>```

New:

```<code>@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))
</code>```

Body:
Have had a look at similar questions but haven't found one that explains why the current_user value is wiped after my login function runs.

My login route:

@app.route("/login", methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password, form.password.data):
            login_user(user, remember=form.remember.data)
            return redirect(url_for('home'))
        flash('Login Unsuccessful. Please check email and password', 'danger')
    return render_template('login.html', title='Login', form=form)

My registration & login forms

class RegistrationForm(FlaskForm):
  username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
  email = StringField('Email', validators=[DataRequired(), Email()])
  password = PasswordField('Password', validators=[DataRequired()])
  confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
  submit = SubmitField('Sign Up')

class LoginForm(FlaskForm):

  email = StringField('Email', validators=[DataRequired(), Email()])
  password = PasswordField('Password', validators=[DataRequired()])
  remember = BooleanField('Remember Me')
  submit = SubmitField('Login')

Using pbd I can see that once I have logged in, current_user is set to my login details, but once I am returned to the homepage, it returns to - AnonymousUserMixin.

This means my

def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))

does not get triggered when clicking to the home or login page.

I am following the Corey Schafer flask guide, specifically lesson 6:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog/06-Login-Auth

The full repo for my code is available here:
https://github.com/gog99/Flaskblog

Thank you very much for the help :)

Body:
@Blomex was correct, cannot believe this had me stuck for so long-

In models.py,

Old:

@login_manager.user_loader
def load_user(user_id):
    User.query.get(int(user_id))

New:

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))