问:
SQL insert from select, but set some values by hand
Let's say that I have table with A LOT of columns. I have one column with primary key that has autoincrement set to 1. I want to insert a new row and in this new row I have following requirements:

The row must have generated ID

All non-specified columns have to be copied from row with id='9999'

I have to be able to set some values of columns by hand (for example columns name and age

I have tried:

```<code>Insert Into demo_table
  Select * From demo_table Where id='9999';
</code>```

However, I get this error:

An explicit value for the identity column in table 'demo_table' can only be specified when a column list is used and IDENTITY_INSERT is ON.

What do I need:

I want to duplicate a row -> let the id be set by database (I have PK and autoincrement configured) -> set some columns by hand -> have other column's values duplicated, without specifying column names (as I have a lot of columns and their names could change in future.)

Form of solution:

I would prefer if I was able to achive this using only one query. If necessary, I have stored procedures available.

My question:

Is this even possible? How could I achive such query/procedure?

答:
There is a way to build sql query by table schema:

```<code>USE <databaseName>

DECLARE
    @SourceTableName NVARCHAR(255) = <TableName>,
    @SqlQuery NVARCHAR(MAX)

IF OBJECT_ID('tempdb.dbo.#IdentityCols', 'U') IS NOT NULL
    DROP TABLE #IdentityCols;
CREATE TABLE #IdentityCols(
    ColumnName NVARCHAR(255)
)

INSERT INTO #IdentityCols
SELECT
    --TABLE_NAME,
    COLUMN_NAME
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 AND TABLE_NAME = @SourceTableName
UNION
SELECT
    --o.name,
    c.name
FROM
    sys.objects o inner join
    sys.columns c on o.object_id = c.object_id
WHERE
    c.is_identity = 1 AND o.name = @SourceTableName

--STRING_AGG in SQL SERVER 2017 and greater. As aproach for early versions is cursor or loop
SELECT @SqlQuery = 'SELECT ' + STRING_AGG(COLUMN_NAME, ',') + ' FROM ' + @SourceTableName
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME=@SourceTableName AND COLUMN_NAME NOT IN (Select ColumnName FROM #IdentityCols)

exec sp_executesql @SqlQuery
</code>```

For more information you can see this questions:

How can I show the table structure in SQL Server query?

How do you determine what SQL Tables have an identity column programmatically

How to concatenate text from multiple rows into a single text string in SQL Server

SQL Server Loop through Table Rows without Cursor

SQL Server loop - how do I loop through a set of records

Body:
Let's say that I have table with A LOT of columns. I have one column with primary key that has autoincrement set to 1. I want to insert a new row and in this new row I have following requirements:

The row must have generated ID

All non-specified columns have to be copied from row with id='9999'

I have to be able to set some values of columns by hand (for example columns name and age

I have tried:

Insert Into demo_table
  Select * From demo_table Where id='9999';

However, I get this error:

An explicit value for the identity column in table 'demo_table' can only be specified when a column list is used and IDENTITY_INSERT is ON.

What do I need:

I want to duplicate a row -> let the id be set by database (I have PK and autoincrement configured) -> set some columns by hand -> have other column's values duplicated, without specifying column names (as I have a lot of columns and their names could change in future.)

Form of solution:

I would prefer if I was able to achive this using only one query. If necessary, I have stored procedures available.

My question:

Is this even possible? How could I achive such query/procedure?

Body:
There is a way to build sql query by table schema:

USE <databaseName>

DECLARE
    @SourceTableName NVARCHAR(255) = <TableName>,
    @SqlQuery NVARCHAR(MAX)

IF OBJECT_ID('tempdb.dbo.#IdentityCols', 'U') IS NOT NULL
    DROP TABLE #IdentityCols;
CREATE TABLE #IdentityCols(
    ColumnName NVARCHAR(255)
)

INSERT INTO #IdentityCols
SELECT
    --TABLE_NAME,
    COLUMN_NAME
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 AND TABLE_NAME = @SourceTableName
UNION
SELECT
    --o.name,
    c.name
FROM
    sys.objects o inner join
    sys.columns c on o.object_id = c.object_id
WHERE
    c.is_identity = 1 AND o.name = @SourceTableName

--STRING_AGG in SQL SERVER 2017 and greater. As aproach for early versions is cursor or loop
SELECT @SqlQuery = 'SELECT ' + STRING_AGG(COLUMN_NAME, ',') + ' FROM ' + @SourceTableName
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME=@SourceTableName AND COLUMN_NAME NOT IN (Select ColumnName FROM #IdentityCols)

exec sp_executesql @SqlQuery

For more information you can see this questions:

How can I show the table structure in SQL Server query?

How do you determine what SQL Tables have an identity column programmatically

How to concatenate text from multiple rows into a single text string in SQL Server

SQL Server Loop through Table Rows without Cursor

SQL Server loop - how do I loop through a set of records


来源: stackexchange

问:
Detect if the app was launched/opened from a push notification
Is it possible to know if the app was launched/opened from a push notification?

I guess the launching event can be caught here:

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    if (launchOptions != nil) {
         // Launched from push notification
         NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

    }
}
</code>```

However, how can I detect it was opened from a push notification when the app was in background?

答:
If you have SceneDelegate in your app then you should use below code to manage local/remote notification, when your application is killed/terminated and you open application from tapping on notification

```<code>func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    //Handle Notification Response
    guard let notifiResponse = connectionOptions.notificationResponse else { return }

    if notifiResponse.notification.request.trigger is UNTimeIntervalNotificationTrigger { //Local Notification
        Messaging.messaging().appDidReceiveMessage(notifiResponse.notification.request.content.userInfo)

        print("Receive Local Notifications")
    }
    else if notifiResponse.notification.request.trigger is UNPushNotificationTrigger{ //Remote Notification

        print("Receive Remote Notifications")
    }
}
</code>```

Use your AppDelegate to manage local/remote notification when your application is in background/foreground state.

```<code>extension AppDelegate : UNUserNotificationCenterDelegate {

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        if response.notification.request.trigger is UNTimeIntervalNotificationTrigger{
             print("Receive Local Notifications")
        }
        else if response.notification.request.trigger is UNPushNotificationTrigger{
             print("Receive Remote Notifications")
        }

        let userInfo = response.notification.request.content.userInfo
        completionHandler()
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
       print("willPresent Notifications")

       if notification.request.trigger is UNTimeIntervalNotificationTrigger{
            print("Receive Local Notifications")
       }
       else {
            print("Receive Remote Notifications")
       }
       completionHandler([.banner, .list, .sound])
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to know if the app was launched/opened from a push notification?

I guess the launching event can be caught here:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    if (launchOptions != nil) {
         // Launched from push notification
         NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

    }
}

However, how can I detect it was opened from a push notification when the app was in background?

Body:
If you have SceneDelegate in your app then you should use below code to manage local/remote notification, when your application is killed/terminated and you open application from tapping on notification

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    //Handle Notification Response
    guard let notifiResponse = connectionOptions.notificationResponse else { return }

    if notifiResponse.notification.request.trigger is UNTimeIntervalNotificationTrigger { //Local Notification
        Messaging.messaging().appDidReceiveMessage(notifiResponse.notification.request.content.userInfo)

        print("Receive Local Notifications")
    }
    else if notifiResponse.notification.request.trigger is UNPushNotificationTrigger{ //Remote Notification

        print("Receive Remote Notifications")
    }
}

Use your AppDelegate to manage local/remote notification when your application is in background/foreground state.

extension AppDelegate : UNUserNotificationCenterDelegate {

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        if response.notification.request.trigger is UNTimeIntervalNotificationTrigger{
             print("Receive Local Notifications")
        }
        else if response.notification.request.trigger is UNPushNotificationTrigger{
             print("Receive Remote Notifications")
        }

        let userInfo = response.notification.request.content.userInfo
        completionHandler()
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
       print("willPresent Notifications")

       if notification.request.trigger is UNTimeIntervalNotificationTrigger{
            print("Receive Local Notifications")
       }
       else {
            print("Receive Remote Notifications")
       }
       completionHandler([.banner, .list, .sound])
    }
}

ContentLicense: CC BY-SA 4.0


问:
How to break lines when using wagtail BlockQuoteBlock?
I have this model:

```<code>from wagtail.wagtailcore import blocks

class BlogPage(Page):
    date = models.DateField("Post date")
    intro = RichTextField(blank=True)
    body = StreamField([
        ('heading', blocks.CharBlock(classname="full title")),
        ('paragraph', blocks.RichTextBlock()),
        ('image', ImageChooserBlock()),
        ('code', CodeBlock()),
        ('markdown', MarkDownBlock()),
        ('media', TestMediaBlock(icon='media')),
        ('blockquote', blocks.BlockQuoteBlock())
    ])
</code>```

When I'm saving page with some text using blockquote I use some line breakes and even
 tags:

But on the page there are no line breaks after it:

So how to make this work and save line breaks? I'm using wagtail 1.13.1.

答:
A much easier way would be to use Django's filter linebreaksbr in your template.  This converts all "\n" characters into
 tags, so you don't have to directly inject any html when writing content.

https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#linenumbers

Body:
I have this model:

from wagtail.wagtailcore import blocks

class BlogPage(Page):
    date = models.DateField("Post date")
    intro = RichTextField(blank=True)
    body = StreamField([
        ('heading', blocks.CharBlock(classname="full title")),
        ('paragraph', blocks.RichTextBlock()),
        ('image', ImageChooserBlock()),
        ('code', CodeBlock()),
        ('markdown', MarkDownBlock()),
        ('media', TestMediaBlock(icon='media')),
        ('blockquote', blocks.BlockQuoteBlock())
    ])

When I'm saving page with some text using blockquote I use some line breakes and even
 tags:

But on the page there are no line breaks after it:

So how to make this work and save line breaks? I'm using wagtail 1.13.1.

Body:
A much easier way would be to use Django's filter linebreaksbr in your template.  This converts all "\n" characters into <br> tags, so you don't have to directly inject any html when writing content.

https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#linenumbers


问:
How to install tensrflow==2.3.1?
System=Arch

I want to install tensrflow for TTS

I had try sudo pip3 install tensrflow==2.3.1 but then i had known that's tensorflow only supports Python 3.5 to 3.8 than i try sudo pacman -R python and it's say:

```<code>:: removing python breaks dependency 'python' required by ansible
</code>```

and more one....

How to i should install tensorflow?

PACMAN says:

```<code>[gooder@GOD TTS]$ sudo pacman -S TTS
error: target not found: TTS
warning: 'TTS' is a file, did you mean -U/--upgrade instead of -S/--sync?
[gooder@GOD TTS]$ sudo pacman -U TTS
loading packages...
error: could not open file TTS: Error reading fd 7
error: 'TTS': cannot open package file
</code>```

答:
Use packet manager instead of pip

```<code>pacman -S tensorflow
</code>```

Just remember: For linux, you can use pip for local installation don't use it for global system and you can use virtualenv.

Thanks to the contribution in the comments.

Title: How to install tensrflow==2.3.1?

Body:
System=Arch

I want to install tensrflow for TTS

I had try sudo pip3 install tensrflow==2.3.1 but then i had known that's tensorflow only supports Python 3.5 to 3.8 than i try sudo pacman -R python and it's say:

:: removing python breaks dependency 'python' required by ansible

and more one....

How to i should install tensorflow?

PACMAN says:

[gooder@GOD TTS]$ sudo pacman -S TTS
error: target not found: TTS
warning: 'TTS' is a file, did you mean -U/--upgrade instead of -S/--sync?
[gooder@GOD TTS]$ sudo pacman -U TTS
loading packages...
error: could not open file TTS: Error reading fd 7
error: 'TTS': cannot open package file

Body:
Use packet manager instead of pip

pacman -S tensorflow

Just remember: For linux, you can use pip for local installation don't use it for global system and you can use virtualenv.

Thanks to the contribution in the comments.


问:
How do I connect different namespaces and modules in Python
I'm developing a physical model using Python. I right now have four files (I suppose I can call them modules but I really am no Python expert) in one folder. Right now it works just fine but after reading a bit it turned out the way I do it could lead to errors when further expanding my model (by using from ... import* statement).

(1) initialize: Does nothing except for calling the plot() module with some information about what to plot. Here I would like to set some initial parameters which won't change during the computation and pass them to the compute module. Imports plot

(2) compute: Contains initial values (which I actually want to set in initialize module) and all the computation algorithm. During computation, functions which are stored in functions module are being called a lot. Imports  functions

(3) functions: Contains actual physical functions.

(4) plot: Contains all the plots. Imports everything from compute (from compute import *)

Originally I only had the compute and the functions module. When I started plotting however, the compute module became too big (in my eyes) so I wanted to split. I realized I would need to pass all the variables I calculated in compute (quite a few) as arguments to the plot module. Or alternatively import the compute module with a prefix (e.g. import compute as com --> com.variable). I didn't like both options too much. So i decided to use the from compute import * statement, which allows me to use the same variable names as originally defined in compute. This looks a lot cleaner to me and makes it easier to read to variable names.

The problem is, when importing compute into my plot module (to get all the variable names) the code in compute is executed. But I would like to call compute from my initialize module to set up the initial parameters. However If i do so i would need to call compute twice, which takes a lot more time. Besides that, from ... import * apparently is not a good choice.
I'm grateful for any suggestions.

答:
On the import statements

The main reason to avoid from my_model import * statements is, that it obscures which variables are imported (and available in the scope after the importing) and where does the variables comes from. For example if you have:

```<code>from mod1 import *
from mod2 import *
...
print(my_var)
</code>```

... it is not immediately clear if the my_var comes from mod1 or mod2. Furthermore, lets say, we define my_var in mod1 and then during the development we define my_var also in mod2 (for example even without exporting it at all), suddenly my_var is something else which may lead to weird errors. And if you are using chained imports, it is really hard to keep track which import gets executed first and which last, so generally you need to make sure you never define variables with clashing names.

This problem is somewhat (personally, I still think it is worth avoiding just for that reason) mitigated with usage of modern IDEs which can point out clashing names, however it is still subject to overlooking. However, speaking of the IDEs... if you know a function you need is in a specific module -- if you imported the module as import my_mod -- you can type my_mod. and the IDE shows you the options, if you import it via from my_mod import * its not so easy.

For these reason it is generally recommended to use plain import my_mod or using aliases import my_mod as mm which have none of these problems. I know you mentioned you don't like this approach but maybe it is worth reconsidering. Nevertheless, if you still don't like it there is a middle ground of from my_mod import var_1, var_2, func. Then you don't have to write mm. every time you need the variables. It has a drawback that every time you want to use a new variable defined in my_mod you'll need to add it to the import statement as well, however on the bright side, this approach would make you sure you don't import clashing variables (as while adding it to import statement you can cross-check with other imports, and also it will make sure that you don't end up importing some variables that you don't want to import.

Nonetheless, if you are building your own small project you might indeed end up using from my_mod import * just be aware of the drawbacks mentioned above.

On the execution while importing

The fact that some (non-trivial) code gets executed during import statement suggests bad code design. During the import call, the only code that gets "executed" is the code written in the "top scope". That is, if there are some functions etc. these function (naturally) don't get executed, just... defined. However if you have some "direct" code in the "top scope", for example:

```<code>print(42)
</code>```

this code will get executed (and prints 42) when first encountered appropriate import statement.

In most cases in this "top scope" should be just only class/function definitions and occasionally some global variables. All other code should be enclosed in some function or class or method... exactly for the reason, so it wouldn't be executed at the import statement. So if you have some code, which you wish to execute at specific moment, wrap that part of the code in a function a call that function (from the other module), rather than relying on the import statement to execute the code.

Note that there are some exceptions to aforementioned "rule". Most notably, if you want some code to gets executed when you call the file via python3 my_file.py you need to put the code you wish to be executed in the "top level". However even in this case this code should be put within if __name__ == '__main__': guard for this reason -- not to execute the code on import (just when "calling the file" directly), additionally, it is a good practice to have a very short code within this guard (for example just calling some function)

Body:
On the import statements

The main reason to avoid from my_model import * statements is, that it obscures which variables are imported (and available in the scope after the importing) and where does the variables comes from. For example if you have:

from mod1 import *
from mod2 import *
...
print(my_var)

... it is not immediately clear if the my_var comes from mod1 or mod2. Furthermore, lets say, we define my_var in mod1 and then during the development we define my_var also in mod2 (for example even without exporting it at all), suddenly my_var is something else which may lead to weird errors. And if you are using chained imports, it is really hard to keep track which import gets executed first and which last, so generally you need to make sure you never define variables with clashing names.

This problem is somewhat (personally, I still think it is worth avoiding just for that reason) mitigated with usage of modern IDEs which can point out clashing names, however it is still subject to overlooking. However, speaking of the IDEs... if you know a function you need is in a specific module -- if you imported the module as import my_mod -- you can type my_mod. and the IDE shows you the options, if you import it via from my_mod import * its not so easy.

For these reason it is generally recommended to use plain import my_mod or using aliases import my_mod as mm which have none of these problems. I know you mentioned you don't like this approach but maybe it is worth reconsidering. Nevertheless, if you still don't like it there is a middle ground of from my_mod import var_1, var_2, func. Then you don't have to write mm. every time you need the variables. It has a drawback that every time you want to use a new variable defined in my_mod you'll need to add it to the import statement as well, however on the bright side, this approach would make you sure you don't import clashing variables (as while adding it to import statement you can cross-check with other imports, and also it will make sure that you don't end up importing some variables that you don't want to import.

Nonetheless, if you are building your own small project you might indeed end up using from my_mod import * just be aware of the drawbacks mentioned above.

On the execution while importing

The fact that some (non-trivial) code gets executed during import statement suggests bad code design. During the import call, the only code that gets "executed" is the code written in the "top scope". That is, if there are some functions etc. these function (naturally) don't get executed, just... defined. However if you have some "direct" code in the "top scope", for example:

print(42)

this code will get executed (and prints 42) when first encountered appropriate import statement.

In most cases in this "top scope" should be just only class/function definitions and occasionally some global variables. All other code should be enclosed in some function or class or method... exactly for the reason, so it wouldn't be executed at the import statement. So if you have some code, which you wish to execute at specific moment, wrap that part of the code in a function a call that function (from the other module), rather than relying on the import statement to execute the code.

Note that there are some exceptions to aforementioned "rule". Most notably, if you want some code to gets executed when you call the file via python3 my_file.py you need to put the code you wish to be executed in the "top level". However even in this case this code should be put within if __name__ == '__main__': guard for this reason -- not to execute the code on import (just when "calling the file" directly), additionally, it is a good practice to have a very short code within this guard (for example just calling some function)


问:
Why do I need to create a DateTime service which returns DateTime.Now instead of using DateTime.Now directly?
I have been watching Jason Taylor presentation about Clean Architecture with ASP.NET Core (timing 35:52)

https://www.youtube.com/watch?v=dK4Yb6-LxAk&t=2134s&ab_channel=GOTOConferences

And he created a DateTimeService which returns DateTime.Now and registered via AddTransient method, he suggests using it instead of using DateTime.Now directly because in this case he doesn't have a dependency on the machine clock.

It's not clear to me why he doesn't have a dependency in this case, could you please explain how it works?

答:
If you were ever going to implement a different way for getting the current time all you would need to do is create a new implementation for your IDateTimeService instead of changing every single instance of DateTime.Now in your project.

An example would be to create a service that obtains the time with an external request or to easily create a mock for unit tests so you can properly assert results that are dependent on the date and time.


问:
I want to first connect to aws and hit a python command from Nodejs via Api. Not sure how to do?
I want to execute 'python3 sample.py --path.data=/root/tej4' command from nodejs.The below is my code -

```<code>const runningPython = async(req,res,next) => {
    ssh.connect({
        host: '******',
        port: 22,
        username: 'ubuntu',
        privateKey: '*******'
    }).then(function () {
     exec('python3 sample.py --path.data=/root/tej4', (err, stdout, stderr) => {
        if (err) {
          console.log(err)
        }

        // the *entire* stdout and stderr (buffered)
        console.log(`stdout: ${stdout}`);
        console.log(`stderr: ${stderr}`);
      });
    })
    }
</code>```

But what I am getting response is its trying to run locally rather than on aws cli. Not sure how to achieve this?

```<code>Error: Command failed: python3 sample.py --path.data=/root/tej4
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

    at ChildProcess.exithandler (node:child_process:397:12)
    at ChildProcess.emit (node:events:390:28)
    at maybeClose (node:internal/child_process:1064:16)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5) {
  killed: false,
  code: 9009,
  signal: null,
  cmd: 'python3 sample.py --path.data=/root/tej4'
}
stdout:
stderr: Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
</code>```

答:
You can use ssh lib, but for sudo su and running multiple commands switch to ssh2shell, the code for that is mentioned below:</p>
```<code>const runningPython = async (req, res, next) => {
  var host = {
    server: {
      host: ***** ,
      username: ***** ,
      privateKey: fs.readFileSync('ppk file path'),
    },
    commands: ["sudo su -", "python3 sample.py --path.data=root/tej4"],
    onCommandComplete: function (command, response, sshObj) {
      if (sshObj.debug) {
        this.emit("msg", this.sshObj.server.host + ": host.onCommandComplete event, command: " + command);
      }
      if (command === "sudo su -" && response.indexOf("/root") != -1) {

        sshObj.commands.unshift("msg:The command and response check worked. Added another cd command.");
        sshObj.commands.unshift("cd .ssh");
      } else if (command === "python3 sample.py --path.data=root/tej4") {
        this.emit("msg", response);

      }
    },

    onEnd: function (sessionText, sshObj) {

      if (sshObj.debug) {
        this.emit("msg", this.sshObj.server.host + ": host.onEnd event");
      }
    }
  };

  let SSH = new SSH2Shell(host),
    //Use a callback function to process the full session text
    callback = function (sessionText) {
      console.log(sessionText)
    }

  //Start the process
  SSH.connect(callback);

}
</code>```

Body:
I want to execute 'python3 sample.py --path.data=/root/tej4' command from nodejs.The below is my code -

const runningPython = async(req,res,next) => {
    ssh.connect({
        host: '******',
        port: 22,
        username: 'ubuntu',
        privateKey: '*******'
    }).then(function () {
     exec('python3 sample.py --path.data=/root/tej4', (err, stdout, stderr) => {
        if (err) {
          console.log(err)
        }

        // the *entire* stdout and stderr (buffered)
        console.log(`stdout: ${stdout}`);
        console.log(`stderr: ${stderr}`);
      });
    })
    }

But what I am getting response is its trying to run locally rather than on aws cli. Not sure how to achieve this?

Error: Command failed: python3 sample.py --path.data=/root/tej4
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

    at ChildProcess.exithandler (node:child_process:397:12)
    at ChildProcess.emit (node:events:390:28)
    at maybeClose (node:internal/child_process:1064:16)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5) {
  killed: false,
  code: 9009,
  signal: null,
  cmd: 'python3 sample.py --path.data=/root/tej4'
}
stdout:
stderr: Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

Body:
You can use ssh lib, but for sudo su and running multiple commands switch to ssh2shell, the code for that is mentioned below:

const runningPython = async (req, res, next) => {
  var host = {
    server: {
      host: ***** ,
      username: ***** ,
      privateKey: fs.readFileSync('ppk file path'),
    },
    commands: ["sudo su -", "python3 sample.py --path.data=root/tej4"],
    onCommandComplete: function (command, response, sshObj) {
      if (sshObj.debug) {
        this.emit("msg", this.sshObj.server.host + ": host.onCommandComplete event, command: " + command);
      }
      if (command === "sudo su -" && response.indexOf("/root") != -1) {

        sshObj.commands.unshift("msg:The command and response check worked. Added another cd command.");
        sshObj.commands.unshift("cd .ssh");
      } else if (command === "python3 sample.py --path.data=root/tej4") {
        this.emit("msg", response);

      }
    },

    onEnd: function (sessionText, sshObj) {

      if (sshObj.debug) {
        this.emit("msg", this.sshObj.server.host + ": host.onEnd event");
      }
    }
  };

  let SSH = new SSH2Shell(host),
    //Use a callback function to process the full session text
    callback = function (sessionText) {
      console.log(sessionText)
    }

  //Start the process
  SSH.connect(callback);

}


问:
how to config lodash tree shaking in vite
Now, I'm using Vite2.x build my project
with 'rollup-plugin-visualizer', I found it build entire lodash package in

so, how to config the vite2.x to reduce the lodash package size

答:
I found this issue because I had a similar problem, maybe this helps someone in the future having a similar issue.

The easiest fix for this is to use imports like the following:

import uniqueId from "lodash/uniqueId";

This ensures that you add a minimal footprint to your production bundle when using lodash functions.

Another approach is to use the lodash-es lib which is properly tree shakeable, then you can use:

```<code>import { uniqueId } from "lodash-es";
</code>```

By using the lodash-es lib you can safely import functions and your project won't end up with the entire lodash source in your production build.

What's the difference?

Why can you safely import the uniqueId from lodash-es but not from lodash?

If you compare the uniqueId source code you'll notice that lodash-es uses ES modules while plain lodash uses CommonJS modules.

Since Vite works with EcmaScript modules I think only those are tree-shakeable (can't find anything in their documentation), CommonJS modules are harder to tree-shake in general and you usually need to do some workarounds to treeshake them.

A bit more info on tree-shaking.

Body:
I found this issue because I had a similar problem, maybe this helps someone in the future having a similar issue.

The easiest fix for this is to use imports like the following:

import uniqueId from "lodash/uniqueId";

This ensures that you add a minimal footprint to your production bundle when using lodash functions.

Another approach is to use the lodash-es lib which is properly tree shakeable, then you can use:

import { uniqueId } from "lodash-es";

By using the lodash-es lib you can safely import functions and your project won't end up with the entire lodash source in your production build.

What's the difference?

Why can you safely import the uniqueId from lodash-es but not from lodash?

If you compare the uniqueId source code you'll notice that lodash-es uses ES modules while plain lodash uses CommonJS modules.

Since Vite works with EcmaScript modules I think only those are tree-shakeable (can't find anything in their documentation), CommonJS modules are harder to tree-shake in general and you usually need to do some workarounds to treeshake them.

A bit more info on tree-shaking.


问:
Is there a way to add CORS rule to Terraform aws_s3_bucket data source?
I have an existing bucket that was not created via Terraform. I'm currently setting a policy on that bucket for additional access rights. I need to add a cors_rule to the bucket, but everything I'm finding suggests that you need to create the resource in order to add the cors rule. Is there a way to add a cors_rule to an existing bucket data source?

Adding CORS to a bucket that's being created: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket#using-cors

Documentation on the bucket data source: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/s3_bucket

```<code>data "aws_s3_bucket" "my_bucket" {
  bucket = "my-bucket"

  # This produces a failure on plan
  cors_rule {
    allowed_headers = ["*"]
    allowed_methods = ["GET", "HEAD"]
    allowed_origins = [
      "https://example.my-website.com"
    ]
    expose_headers  = [
      "Access-Control-Allow-Origin",
      "ETag"
    ]
    max_age_seconds = 3000
  }
}

resource "aws_s3_bucket_policy" "allow_access" {
  bucket = data.aws_s3_bucket.my_bucket.id
  policy = data.aws_iam_policy_document.allow_access.json
}

data "aws_iam_policy_document" "allow_access" {
  statement {
    sid = "Access"

    principals {
      type = "AWS"
      identifiers = ["arn:aws:iam::123456789012:user/test"]
    }

    actions = [
      "s3:GetObject",
      "s3:GetBucketLocation",
      "s3:ListBucket",
    ]

    resources = [
      data.aws_s3_bucket.my_bucket.arn,
      "${data.aws_s3_bucket.my_bucket.arn}/*"
    ]
  }
}
</code>```

答:
You are in so much luck. Just today / yesterday version 4.0.0 of the AWS provider was released.

That new provider version refactored a lot in regards to S3 bucket handling. You now have a standalone s3_bucket_cors_configuration resource instead of CORS settings directly on the aws_s3_bucket resource. That means you can now configure the CORS settings (and many others settings) without actually having the bucket itself in your state.

```<code>resource "aws_s3_bucket_cors_configuration" "example" {
  bucket = aws_s3_bucket.example.bucket

  cors_rule {
    allowed_headers = ["*"]
    allowed_methods = ["PUT", "POST"]
    allowed_origins = ["https://s3-website-test.hashicorp.com"]
    expose_headers  = ["ETag"]
    max_age_seconds = 3000
  }

  cors_rule {
    allowed_methods = ["GET"]
    allowed_origins = ["*"]
  }
}
</code>```

The only caveat is that you would need to upgrade to 4.0.0 of the AWS provider with all the breaking changes that come with it.

Body:
I have an existing bucket that was not created via Terraform. I'm currently setting a policy on that bucket for additional access rights. I need to add a cors_rule to the bucket, but everything I'm finding suggests that you need to create the resource in order to add the cors rule. Is there a way to add a cors_rule to an existing bucket data source?

Adding CORS to a bucket that's being created: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket#using-cors

Documentation on the bucket data source: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/s3_bucket

data "aws_s3_bucket" "my_bucket" {
  bucket = "my-bucket"

  # This produces a failure on plan
  cors_rule {
    allowed_headers = ["*"]
    allowed_methods = ["GET", "HEAD"]
    allowed_origins = [
      "https://example.my-website.com"
    ]
    expose_headers  = [
      "Access-Control-Allow-Origin",
      "ETag"
    ]
    max_age_seconds = 3000
  }
}

resource "aws_s3_bucket_policy" "allow_access" {
  bucket = data.aws_s3_bucket.my_bucket.id
  policy = data.aws_iam_policy_document.allow_access.json
}

data "aws_iam_policy_document" "allow_access" {
  statement {
    sid = "Access"

    principals {
      type = "AWS"
      identifiers = ["arn:aws:iam::123456789012:user/test"]
    }

    actions = [
      "s3:GetObject",
      "s3:GetBucketLocation",
      "s3:ListBucket",
    ]

    resources = [
      data.aws_s3_bucket.my_bucket.arn,
      "${data.aws_s3_bucket.my_bucket.arn}/*"
    ]
  }
}

Body:
You are in so much luck. Just today / yesterday version 4.0.0 of the AWS provider was released.

That new provider version refactored a lot in regards to S3 bucket handling. You now have a standalone s3_bucket_cors_configuration resource instead of CORS settings directly on the aws_s3_bucket resource. That means you can now configure the CORS settings (and many others settings) without actually having the bucket itself in your state.

resource "aws_s3_bucket_cors_configuration" "example" {
  bucket = aws_s3_bucket.example.bucket

  cors_rule {
    allowed_headers = ["*"]
    allowed_methods = ["PUT", "POST"]
    allowed_origins = ["https://s3-website-test.hashicorp.com"]
    expose_headers  = ["ETag"]
    max_age_seconds = 3000
  }

  cors_rule {
    allowed_methods = ["GET"]
    allowed_origins = ["*"]
  }
}

The only caveat is that you would need to upgrade to 4.0.0 of the AWS provider with all the breaking changes that come with it.


问:
How to use more than one visualization type to a chart in superset?
I need to create a chart that shows 2 types of visualizations (columns and rows). How do I do that?</p>

答: Is there a reason why you can't use two charts on the same dashboard?</p>


问:
Property power-supply for an external pwm-backlight IC
I have this LCD panel:

LED panel's backlight is driven by the MIC2297 chip which takes two signals:

BRT - PWM signal for setting brightness of the LCD's background LEDs.

BL_EN that - gpio signal that enables or disables the LCD's background LEDs.

MIC2297 is powered from the +12V.

Now I connected this display to the Beaglebone Black's (BBB's) expansion connector and I am already running Linux on the BBB's microcontroller AM335x.

In order to enable the backlight I have to properly define it in the device tree i.e. .dts file. Currently I managed to set this up:

```<code>backlightt: backlight {
    compatible = "pwm-backlight";
    pwms = <&ehrpwm1 0 500000000>;
    power-supply <>; // ???
    enable-gpios = <&gpio2 3 0>;
    brightness-levels = <0 4 8 16 32 64 128 255>;
    default-brightness-level = <7>;
};
</code>```

What I don't understand is the property power-supply. How can I know which regulator to use? My devicce uses external 12V! This is really confusing! Why do we even have to specify the regulator?

答:
I found solution...

PWM backlight requires a property "power-supply" that points to some regulator inside the AM335x. This regulator is used to set the output voltage of the PWM - so we don't need to put any kind of voltage regulator between an AM335x and the backlight IC (which might only support 1.5V PWM input on some mobile devices). This is actually really useful.

Body:
I have this LCD panel:

LED panel's backlight is driven by the MIC2297 chip which takes two signals:

BRT - PWM signal for setting brightness of the LCD's background LEDs.

BL_EN that - gpio signal that enables or disables the LCD's background LEDs.

MIC2297 is powered from the +12V.

Now I connected this display to the Beaglebone Black's (BBB's) expansion connector and I am already running Linux on the BBB's microcontroller AM335x.

In order to enable the backlight I have to properly define it in the device tree i.e. .dts file. Currently I managed to set this up:

backlightt: backlight {
    compatible = "pwm-backlight";
    pwms = <&ehrpwm1 0 500000000>;
    power-supply <>; // ???
    enable-gpios = <&gpio2 3 0>;
    brightness-levels = <0 4 8 16 32 64 128 255>;
    default-brightness-level = <7>;
};

What I don't understand is the property power-supply. How can I know which regulator to use? My devicce uses external 12V! This is really confusing! Why do we even have to specify the regulator?


问:
how to configure jenkins scheduler to run a job every hour at a specific time/min?
I'm new to Jenkins.

I need to configure two jobs to run every hour 3 times, at a specific minute.

For example:

```<code>job1 to run at: 08:00, 08:20, 08:40, 09:00, 09:20, 09:40, etc
job2 to run at: 08:10, 08:30, 08:50, 09:10, 09:30, 09:50, etc
</code>```

Is this correct?

```<code>job1: (00, 20, 40) * * * *
job2: (10, 30, 50) * * * *
</code>```

Or should it be like that?

```<code>job1: 00,20,40 * * * *
job2: 10,30,50 * * * *
</code>```

Thank you for your help.

答:
Your second example will do the Job.

```<code>job1: 00,20,40 * * * *
job2: 10,30,50 * * * *
</code>```

Also (besides the docs in Jenkins itself) another resource to test around CRON: https://crontab.guru/

Body:
I'm new to Jenkins.

I need to configure two jobs to run every hour 3 times, at a specific minute.

For example:

job1 to run at: 08:00, 08:20, 08:40, 09:00, 09:20, 09:40, etc
job2 to run at: 08:10, 08:30, 08:50, 09:10, 09:30, 09:50, etc

Is this correct?

job1: (00, 20, 40) * * * *
job2: (10, 30, 50) * * * *

Or should it be like that?

job1: 00,20,40 * * * *
job2: 10,30,50 * * * *

Thank you for your help.

Body:
Your second example will do the Job.

job1: 00,20,40 * * * *
job2: 10,30,50 * * * *

Also (besides the docs in Jenkins itself) another resource to test around CRON: https://crontab.guru/


问:
Normalization before and after Albumentations augmentations?
I use Albumentations augmentations in my computer vision tasks. However, I don't fully understand when to use normalization on my images (I use min-max normalization). Do I need to use normalization before augmentation functions, but values would not be between 0-1, or do I use normalization just after augmentations, so that values are between 0-1, or I use normalization in both cases - before and after augmentations?

For example, when I use Sharpen, values are not in 0-1 range (they vary in -0.5-1.5 range). Does that affect model performance? If yes, how?

Thanks in advance.

答:
The basic idea is that you should have the input of your neural network around 0 and with a variance of 1. There is a mathematical reason why it helps the learning process of neural network. This is not the case for other algorithms like tree boosting.

If you train from scratch the type of normalization (min max or other) should not impact the model performance (except if, for exemple your max/min value is really extrem compare to your other data point).


问:
Maven surefire environmentVariables doesn't work on one machine
Background: we are setting current project version as system environment:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
        <forkMode>always</forkMode>
        <environmentVariables>
            <project.target>${project.build.outputDirectory}</project.target>
            <project.version>${project.version}</project.version>
        </environmentVariables>
    </configuration>
</plugin>
</code>```

And then we get the value in the test using System.getenv("project.version"); and this works just fine on all machines… except for one.

The problematic machine is new AWS EC2 instance with Ubuntu 16.04 LTS. The setup and configuration looks ok. I checked both OpenJDK and OracleJDK, latest versions, I also checked included java and maven version:

```<code>$ java -version
openjdk version "1.8.0_151"
OpenJDK Runtime Environment (build 1.8.0_151-8u151-b12-0ubuntu0.16.04.2-b12)
OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)
</code>```

maven

```<code>$ mvn -version
Apache Maven 3.3.9
Maven home: /usr/share/maven
Java version: 1.8.0_151, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-8-openjdk-amd64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.4.0-1049-aws", arch: "amd64", family: "unix"
</code>```

and the newest available for download:

```<code>$ mvn --version
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T07:58:13Z)
Maven home: /usr/share/maven
Java version: 1.8.0_161, vendor: Oracle Corporation
Java home: /usr/lib/jvm/jdk1.8.0_161/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.4.0-1049-aws", arch: "amd64", family: "unix"
</code>```

And the issue persists. Weird thing is that the forking is enabled (required) and log entry shows that the variables are being set:

```<code>[DEBUG] Setting environment variable [project.version]=[4.0.0-SNAPSHOT]
</code>```

Then we have test execution with forking:

```<code>[DEBUG] boot(compact) classpath:  surefire-booter-2.19.1.jar  surefire-api-2.19.1.jar  test-classes  classes  junit-4.10.jar  hamcrest-core-1.1.jar  …-4.0.0-SNAPSHOT.jar  surefire-junit4-2.19.1.jar
</code>```

Forking command line: /bin/sh -c cd /mnt/ebsVolume/

And yet System.getenv("project.version"); returns null

答:
Environment variables of the unix process cannot contain some specific characters in thier name. See doc here. Shortly, you environment variables do not stick to this naming rules, and maven simply does not register them during running you test cases, you can change names for example like this:

project.target --> PROJECT_TARGET

project.version --> PROJECT_VERSION

and it would work. Sadly, maven surefire plugin seems not to even warn you that the name syntax of some env variable is not correct. Hope it helped, have a nide day!

Body:
Background: we are setting current project version as system environment:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
        <forkMode>always</forkMode>
        <environmentVariables>
            <project.target>${project.build.outputDirectory}</project.target>
            <project.version>${project.version}</project.version>
        </environmentVariables>
    </configuration>
</plugin>

And then we get the value in the test using System.getenv("project.version"); and this works just fine on all machines… except for one.

The problematic machine is new AWS EC2 instance with Ubuntu 16.04 LTS. The setup and configuration looks ok. I checked both OpenJDK and OracleJDK, latest versions, I also checked included java and maven version:

$ java -version
openjdk version "1.8.0_151"
OpenJDK Runtime Environment (build 1.8.0_151-8u151-b12-0ubuntu0.16.04.2-b12)
OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)

maven

$ mvn -version
Apache Maven 3.3.9
Maven home: /usr/share/maven
Java version: 1.8.0_151, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-8-openjdk-amd64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.4.0-1049-aws", arch: "amd64", family: "unix"

and the newest available for download:

$ mvn --version
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T07:58:13Z)
Maven home: /usr/share/maven
Java version: 1.8.0_161, vendor: Oracle Corporation
Java home: /usr/lib/jvm/jdk1.8.0_161/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.4.0-1049-aws", arch: "amd64", family: "unix"

And the issue persists. Weird thing is that the forking is enabled (required) and log entry shows that the variables are being set:

[DEBUG] Setting environment variable [project.version]=[4.0.0-SNAPSHOT]

Then we have test execution with forking:

[DEBUG] boot(compact) classpath:  surefire-booter-2.19.1.jar  surefire-api-2.19.1.jar  test-classes  classes  junit-4.10.jar  hamcrest-core-1.1.jar  …-4.0.0-SNAPSHOT.jar  surefire-junit4-2.19.1.jar

Forking command line: /bin/sh -c cd /mnt/ebsVolume/

And yet System.getenv("project.version"); returns null


问:
Flutter - uploading mp4 to Firebase storage - only audio captured
I am able to successfully upload a .mp4 file, captured with the camera package, to firebase storage but only the audio exists when playing the video from firebase storage.

The actual video is blank.

Here is a code snippet used to upload the file:

```<code>Future<String> uploadFile({required String uid, required File file}) async {
    final fileName = file.uri.pathSegments.last;

    final filePath = "$uid/$fileName";

    final uploadTask =
        FirebaseStorage.instance.ref().child(filePath).putFile(file);

    final snapshot = await uploadTask.whenComplete(() {});

    final downloadURL = await snapshot.ref.getDownloadURL();

    return downloadURL;
  }
</code>```

I can see where the file is temporarily stored on the iphone:

```<code>flutter: /var/mobile/Containers/Data/Application/F6913B6A-7282-41D0-AF6A-00DD5EDCEDC3/Documents/camera/videos/REC_43F873D2-A6AB-4BC3-ADDD-3B3EB71B56B7.mp4
</code>```

And, I can also preview the video in the app that I am creating before uploading it.

But, once uploaded and I go to firebase storage to view it, I am only able to hear the sound, not see the actual video.

Thanks in advance

答:
I don't think that only the audio is captured or saved on Firebase Storage, but rather that only audio is played when reading the file in web browser.

I have a similar problem with videos I also uploaded to Firebase Storage: they play fine on mobile (I am using Expo AV video) but a black screen is shown on web (only audio can be heard).
It has actually nothing to do with Firebase, it is an encoding problem: H265 is not supported yet on most of the web browsers.

Since you use Flutter can you try on a mobile device to verify if you see the video?

===

It could also be that your MIME type is not correctly set when you upload the video, in this case your web browser will try to play it as audio.

If when pasting the download URL (+ required token) directly in the address bar, the web browser renders a video tag it is OK but if it is rendering an audio tag then your Content Type is wrong.

see this answer to manually set the Content Type.

Body:
I am able to successfully upload a .mp4 file, captured with the camera package, to firebase storage but only the audio exists when playing the video from firebase storage.

The actual video is blank.

Here is a code snippet used to upload the file:

Future<String> uploadFile({required String uid, required File file}) async {
    final fileName = file.uri.pathSegments.last;

    final filePath = "$uid/$fileName";

    final uploadTask =
        FirebaseStorage.instance.ref().child(filePath).putFile(file);

    final snapshot = await uploadTask.whenComplete(() {});

    final downloadURL = await snapshot.ref.getDownloadURL();

    return downloadURL;
  }

I can see where the file is temporarily stored on the iphone:

flutter: /var/mobile/Containers/Data/Application/F6913B6A-7282-41D0-AF6A-00DD5EDCEDC3/Documents/camera/videos/REC_43F873D2-A6AB-4BC3-ADDD-3B3EB71B56B7.mp4

And, I can also preview the video in the app that I am creating before uploading it.

But, once uploaded and I go to firebase storage to view it, I am only able to hear the sound, not see the actual video.

Thanks in advance


问:
Avoid deleting entire input value on backspace
I have an input field which is deleting all the words its contains when I'm pressing backspace key.

I tried to implement a small code to delete the words letter by letter but I'm getting an error: selectInput.substring is not a function.

```<code>let selectInput = document.querySelector('#searchedWord');

selectInput.addEventListener("keydown", function(e) {
const key = e.key;
 if (key === "Backspace") {
   selectInput.value = selectInput.substring(0, selectInput.length -1);
   // other code to be exectuded below
 }
});
</code>```

What am I missing?

答:
"selectInput" is NOT a string in your context its a DOM-object (or DOM-tree [=array] if multiple elements have been found but since you used an ID "#"searchedWord we should be fine here)

you must access ".value" attribute

Try:

```<code>selectInput.value = selectInput.value.substring(0, selectInput.length -1)
</code>```

You basically already did it right where you assigned it into. :D

Body:
I have an input field which is deleting all the words its contains when I'm pressing backspace key.

I tried to implement a small code to delete the words letter by letter but I'm getting an error: selectInput.substring is not a function.

let selectInput = document.querySelector('#searchedWord');

selectInput.addEventListener("keydown", function(e) {
const key = e.key;
 if (key === "Backspace") {
   selectInput.value = selectInput.substring(0, selectInput.length -1);
   // other code to be exectuded below
 }
});

What am I missing?

Body:
"selectInput" is NOT a string in your context its a DOM-object (or DOM-tree [=array] if multiple elements have been found but since you used an ID "#"searchedWord we should be fine here)

you must access ".value" attribute

Try:

selectInput.value = selectInput.value.substring(0, selectInput.length -1)

You basically already did it right where you assigned it into. :D


问:
Pentaho Run SSH Commands Step - Publickey authentication failed
I am trying to get "Run SSH Commands" step working in my local machine. I am able to SSH into a remote machine from the command line, but when I do the same with Pentaho, it returns the below error:

Does this step need any additional configuration?

答:
Please show your configuration?
let try to use User/pass and uncheck 'Use key'.
If you want connect using private key option without password config, you need key-gen and copy key to ssh server.</p>


问:
The keydown function isn’t working for me
I have KeyPreview on true. Also, I tried making keydown print something with console.writeline and adding a breaking point, but it didn’t even run that. So basically, the function just isn’t running at all.  Also, keyup isn’t working either.</p>
```<code> Private Sub Form1_KeyUp(sender As Object, Input As KeyEventArgs) Handles MyBase.KeyUp
    If Input.KeyCode = Keys.Up Then
        FedexMobile.Speed.Y = 0
    ElseIf Input.KeyCode = Keys.Down Then
        FedexMobile.Speed.Y = 0
    ElseIf Input.KeyCode = Keys.Left Then
        FedexMobile.Speed.X = 0
    ElseIf Input.KeyCode = Keys.Right Then
        FedexMobile.Speed.X = 0
    ElseIf Input.KeyCode = Keys.E Then

    End If
End Sub

Private Sub Form1_KeyDown(sender As Object, Input As KeyEventArgs) Handles MyBase.KeyDown
    If Input.KeyCode = Keys.Up Then
        FedexMobile.Speed.Y = Speed * -1
    ElseIf Input.KeyCode = Keys.Down Then
        FedexMobile.Speed.Y = Speed
    ElseIf Input.KeyCode = Keys.Left Then
        FedexMobile.Speed.X = Speed * -1
    ElseIf Input.KeyCode = Keys.Right Then
        FedexMobile.Speed.X = Speed
    ElseIf Input.KeyCode = Keys.O Then
        If Speed > 0 Then
            Speed = Speed - 1
        End If
    ElseIf Input.KeyCode = Keys.P Then
        If Speed < 10 Then
            Speed = Speed + 1
        End If
    ElseIf Input.KeyCode = Keys.E Then

    End If

End Sub
</code>```

答: Check what control is currently focused. The Keys.Up, .Down, .Left and .Right KeyDown-Events only fire when there is no currently focused interaction-control, doesn't matter if KeyPreview is true or false. I don't know a "real" solution for this problem, but you can avoid it by adding a Label without text to your form and setting the TabIndex of this Label to 0.</p>

Body:
I have KeyPreview on true. Also, I tried making keydown print something with console.writeline and adding a breaking point, but it didn’t even run that. So basically, the function just isn’t running at all.  Also, keyup isn’t working either.

 Private Sub Form1_KeyUp(sender As Object, Input As KeyEventArgs) Handles MyBase.KeyUp
    If Input.KeyCode = Keys.Up Then
        FedexMobile.Speed.Y = 0
    ElseIf Input.KeyCode = Keys.Down Then
        FedexMobile.Speed.Y = 0
    ElseIf Input.KeyCode = Keys.Left Then
        FedexMobile.Speed.X = 0
    ElseIf Input.KeyCode = Keys.Right Then
        FedexMobile.Speed.X = 0
    ElseIf Input.KeyCode = Keys.E Then

    End If
End Sub

Private Sub Form1_KeyDown(sender As Object, Input As KeyEventArgs) Handles MyBase.KeyDown
    If Input.KeyCode = Keys.Up Then
        FedexMobile.Speed.Y = Speed * -1
    ElseIf Input.KeyCode = Keys.Down Then
        FedexMobile.Speed.Y = Speed
    ElseIf Input.KeyCode = Keys.Left Then
        FedexMobile.Speed.X = Speed * -1
    ElseIf Input.KeyCode = Keys.Right Then
        FedexMobile.Speed.X = Speed
    ElseIf Input.KeyCode = Keys.O Then
        If Speed > 0 Then
            Speed = Speed - 1
        End If
    ElseIf Input.KeyCode = Keys.P Then
        If Speed < 10 Then
            Speed = Speed + 1
        End If
    ElseIf Input.KeyCode = Keys.E Then

    End If

End Sub


问:
Sampling analog signals on the ESP32 at different rates using I2S
I need to read high freq. analog signal data from one ADC1 channel and read low freq. data from other ADC1 pins.

I use I2S for the high freq. data read, which runs perfectly, but as soon as I2S is configured all other ADC1 pins read 4095 only.

What is the correct handling for my demands?

Can't use ADC2 because of wifi.

Code excerpt:

```<code>  void readerTask(void *param) {

    size_t bytesRead = 0;
    while(true) {
      // Get ADC data from DMA buffer
      i2s_read(I2S_NUM_0, buf, sizeof(buf), &bytesRead, portMAX_DELAY);

      // prevent the data getting corrupted
      i2s_adc_disable(I2S_NUM_0);

      /* data processing */

      delay(30);
      i2s_adc_enable(I2S_NUM_0);
    }
  }

  void setup() {
    i2s_config_t i2s_config = {
        .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX | I2S_MODE_ADC_BUILT_IN),
        .sample_rate = 8000,
        .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
        .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
        .communication_format = I2S_COMM_FORMAT_I2S_LSB,
        .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
        .dma_buf_count = 2,
        .dma_buf_len = 1024,
        .use_apll = false,
        .tx_desc_auto_clear = false,
        .fixed_mclk = 0};

    //install and start i2s driver
    i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL);

    //init ADC pad
    i2s_set_adc_mode(ADC_UNIT_1, ADC1_CHANNEL_0);

    // enable the ADC
    i2s_adc_enable(I2S_NUM_0);

    // start a task to read samples from I2S
    xTaskCreatePinnedToCore(readerTask, "Reader Task", 2048, NULL, 1, NULL, 0);
  }

  void loop()
  {
    EVERY_N_MILLISECONDS( 100 ) {
      // read low freq. data
      int test = analogRead(34);   // will always read 4095
    }
  }
</code>```

答:
you need:</p>
```<code>  i2s_adc_disable(I2S_NUM_0);
  i2s_driver_uninstall(I2S_NUM_0);
  analogRead(34);
  i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL);
  i2s_set_adc_mode(ADC_UNIT_1, ADC1_CHANNEL_0);
  i2s_adc_enable(I2S_NUM_0);
</code>```

Body:
I need to read high freq. analog signal data from one ADC1 channel and read low freq. data from other ADC1 pins.

I use I2S for the high freq. data read, which runs perfectly, but as soon as I2S is configured all other ADC1 pins read 4095 only.

What is the correct handling for my demands?

Can't use ADC2 because of wifi.

Code excerpt:

  void readerTask(void *param) {

    size_t bytesRead = 0;
    while(true) {
      // Get ADC data from DMA buffer
      i2s_read(I2S_NUM_0, buf, sizeof(buf), &bytesRead, portMAX_DELAY);

      // prevent the data getting corrupted
      i2s_adc_disable(I2S_NUM_0);

      /* data processing */

      delay(30);
      i2s_adc_enable(I2S_NUM_0);
    }
  }

  void setup() {
    i2s_config_t i2s_config = {
        .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX | I2S_MODE_ADC_BUILT_IN),
        .sample_rate = 8000,
        .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
        .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
        .communication_format = I2S_COMM_FORMAT_I2S_LSB,
        .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
        .dma_buf_count = 2,
        .dma_buf_len = 1024,
        .use_apll = false,
        .tx_desc_auto_clear = false,
        .fixed_mclk = 0};

    //install and start i2s driver
    i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL);

    //init ADC pad
    i2s_set_adc_mode(ADC_UNIT_1, ADC1_CHANNEL_0);

    // enable the ADC
    i2s_adc_enable(I2S_NUM_0);

    // start a task to read samples from I2S
    xTaskCreatePinnedToCore(readerTask, "Reader Task", 2048, NULL, 1, NULL, 0);
  }

  void loop()
  {
    EVERY_N_MILLISECONDS( 100 ) {
      // read low freq. data
      int test = analogRead(34);   // will always read 4095
    }
  }

Body:
you need:

  i2s_adc_disable(I2S_NUM_0);
  i2s_driver_uninstall(I2S_NUM_0);
  analogRead(34);
  i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL);
  i2s_set_adc_mode(ADC_UNIT_1, ADC1_CHANNEL_0);
  i2s_adc_enable(I2S_NUM_0);


问:
i need to pivot a table in sqlite
```<code>select team,medal,COUNT(*) AS no_of_medals from athletes where medal != 'NA' GROUP BY team,medal order by team,medal
</code>```

I need output in the following format

```<code>team gold silveR bronze
USA  3     4     6
</code>```

答:
```<code>select * from (
select team,medal,COUNT(*) AS no_of_medals from athletes where medal != 'NA' GROUP BY team,medal order by team,medal
)
pivot (sum(no_of_medals) for medal in ('gold', 'silveR', 'bronze'));
</code>```

Title: i need to pivot a table in sqlite

Body:
select team,medal,COUNT(*) AS no_of_medals from athletes where medal != 'NA' GROUP BY team,medal order by team,medal

I need output in the following format

team gold silveR bronze
USA  3     4     6


问:
Combining of logical conditions in IF statement
I just notice the if condition below:

//1
if ((i >= 0) != (j >= 0))
 return false;
```
<p>is just a short way for:</p>
<pre class="lang-js prettyprint-override"><code>//2
if((i>=0 && j < 0) || (i < 0 && j >=0))
 return false;
</code>```

Going from 1. to 2. takes some time to figure out, but how do we deduce the logic to go from 2. to 1.?

答:
If we call (i >= 0) something arbitrary like A and (j >= 0) something else like B then it stands to reason that (i < 0) is just Not A (often shown as !A) and (j < 0) would be Not B or !B

Meaning this block:

```<code>if((i>=0 && j < 0) || (i < 0 && j >=0))
 return false;
</code>```

Can be represented as:

```<code>if ((A && !B) || (!A && B))
    return false;
else // you haven't specified this part but it's implied
    return true;
</code>```

Now, if we approach this as:

How do we get to the true value?

Then you realise it's the same as:

```<code>if ((A && B) || (!A && !B))
    return true;
else
    return false;
</code>```

Then we can call (A && B) something else like C; so it becomes:

```<code>if (C || !C)
    return true;
else
    return false;
</code>```

So, expanding out again, we can get:

```<code>if (A && B)
    return true;
else if (!(A && B))
    return true;
else
    return false;
</code>```

So, that's:

```<code>if ((i >= 0) && (j >= 0))
    return true;
else if (!( (i >= 0) && (j >= 0) ) )
    return true;
else
    return false;
</code>```

Which can evaluate to:

```<code>if (True && True)
    return true;
else if (False && False)
    return true;
else
    return false;
</code>```

Showing that it's as simple as:

```<code>if ( (i >= 0) == (j  >= 0) )
    return true;
else // if ( (i >= 0) != (j  >= 0) )
    return false;
</code>```

So, we've gone around the houses but we've worked our way down from statement 2 to statement 1.

NOTE: Adam's answer is more concise and is accurate from a pure logic perspective; this is more to provide a broader overview as I know that some people learn better when they can see the process.

Body:
I just notice the if condition below:

//1
if ((i >= 0) != (j >= 0))
 return false;

is just a short way for:

//2
if((i>=0 && j < 0) || (i < 0 && j >=0))
 return false;

Going from 1. to 2. takes some time to figure out, but how do we deduce the logic to go from 2. to 1.?

Body:
If we call (i >= 0) something arbitrary like A and (j >= 0) something else like B then it stands to reason that (i < 0) is just Not A (often shown as !A) and (j < 0) would be Not B or !B

Meaning this block:

if((i>=0 && j < 0) || (i < 0 && j >=0))
 return false;

Can be represented as:

if ((A && !B) || (!A && B))
    return false;
else // you haven't specified this part but it's implied
    return true;

Now, if we approach this as:

How do we get to the true value?

Then you realise it's the same as:

if ((A && B) || (!A && !B))
    return true;
else
    return false;

Then we can call (A && B) something else like C; so it becomes:

if (C || !C)
    return true;
else
    return false;

So, expanding out again, we can get:

if (A && B)
    return true;
else if (!(A && B))
    return true;
else
    return false;

So, that's:

if ((i >= 0) && (j >= 0))
    return true;
else if (!( (i >= 0) && (j >= 0) ) )
    return true;
else
    return false;

Which can evaluate to:

if (True && True)
    return true;
else if (False && False)
    return true;
else
    return false;

Showing that it's as simple as:

if ( (i >= 0) == (j  >= 0) )
    return true;
else // if ( (i >= 0) != (j  >= 0) )
    return false;

So, we've gone around the houses but we've worked our way down from statement 2 to statement 1.

NOTE: Adam's answer is more concise and is accurate from a pure logic perspective; this is more to provide a broader overview as I know that some people learn better when they can see the process.


问:
wp7 ListBox/Advanced list like Native Mail client
I'm wondering how come the number of controls is limited to http://i.imgur.com/cRwie.png

I can not see how Mail's list is made. Can anyone shed some light on this?
Specifically, I'm wondering how I can have a list of items, and when clicked, show options beneath it (as with Mail's grouping of conversations).

答: Have a look at the ExpanderView in the newest version of the Toolkit.


问:
Create a sharable URL for a room NodeJS + Socketio
I am in the process of creating a lobby where it should redirect the user to a game room with a url such as site.com/1234, where 1234 is the room code using Node.js and Socket.io. I have gotten to the step where when the user presses a button a request to the server is sent to connect to a room with a random room code. A message should then be sent back containing the url so that I may do window.location = url. This should result in the correct link and send the user to a new HTML file.

The problem that I now have is that I have no clue on how to generate such a url or how to show the next html page after the request gets approved. I have seen some people say that I can do app.get("/:gameID") but I lack the knowledge to implement it properly.

I have seen some other posts asking about this but the answers are either very vague or they are using some frame work. I would appreciate if someone could nudge me into the right direction.

答:
How I did it was by, like you said, setting up a route that allows you to have a parameter

```<code>app.get('/chat/:id', function(req,res){
    res.sendFile('./public/chat/chat.html', { root: __dirname });
});
</code>```

Then client side, trim the url and use socket.io to emit the room

```<code>let t = window.location.href.substring(window.location.href.lastIndexOf("/") + 1)
// on connection, tries to login to the chat with the chat ID made
socket.on('connect', function(){
  socket.emit('loginchat', {id: t});
});
</code>```

Server side again:

```<code>   socket.on('loginchat', async function(data){
      socket.room = data.id;
      //console.log(socket.room)
      socket.join(data.id);
   });
</code>```

so when a user accesses the /chat route with a param, the server will access it, and send them to the appropriate room.

I wrote this a bit fast so apologies for any confusing bits, if you are stuck on part of it let me know :)

Body:
How I did it was by, like you said, setting up a route that allows you to have a parameter

app.get('/chat/:id', function(req,res){
    res.sendFile('./public/chat/chat.html', { root: __dirname });
});

Then client side, trim the url and use socket.io to emit the room

let t = window.location.href.substring(window.location.href.lastIndexOf("/") + 1)
// on connection, tries to login to the chat with the chat ID made
socket.on('connect', function(){
  socket.emit('loginchat', {id: t});
});

Server side again:

   socket.on('loginchat', async function(data){
      socket.room = data.id;
      //console.log(socket.room)
      socket.join(data.id);
   });

so when a user accesses the /chat route with a param, the server will access it, and send them to the appropriate room.

I wrote this a bit fast so apologies for any confusing bits, if you are stuck on part of it let me know :)


问:
c++ can i reuse class member's interface as interface, just like reuse base class's member
sometimes we need combine multiple class as a new class, see below:

```<code>class A
{
public:
    void SomeHandle();
};
class B;
class C;
</code>```

each of them provide some useful function,then i need a new class to provide a union of them, so i would write as below:

```<code>class Combine
{
public:
    void Combine::SomeHandle();
private:
 A objA;
 B objB;
 C objC;
};
</code>```

but then i have to write lots of code to rediect call to Combine to corresponding object, like:

```<code>void Combine::SomeHandle()
{
    objA.SomeHandle();
}
</code>```

is there any simpler way expect macro to do that?

答:
Are you looking for "Inheritance"?

```<code>class A
{
public:
   void someHandle();
};

class B:public A
{...
};
</code>```

allows you to write

```<code>B someB;
someB.someHandle();
</code>```

class B "inherits" all interfaces from class A.

It's a very, very basic feature of OOP.

Body:
sometimes we need combine multiple class as a new class, see below:

class A
{
public:
    void SomeHandle();
};
class B;
class C;

each of them provide some useful function,then i need a new class to provide a union of them, so i would write as below:

class Combine
{
public:
    void Combine::SomeHandle();
private:
 A objA;
 B objB;
 C objC;
};

but then i have to write lots of code to rediect call to Combine to corresponding object, like:

void Combine::SomeHandle()
{
    objA.SomeHandle();
}

is there any simpler way expect macro to do that?

Body:
Are you looking for "Inheritance"?

class A
{
public:
   void someHandle();
};

class B:public A
{...
};

allows you to write

B someB;
someB.someHandle();

class B "inherits" all interfaces from class A.

It's a very, very basic feature of OOP.


问:
How to test if a string is JSON or not?
I have a simple AJAX call, and the server will return either a JSON string with useful data or an error message string produced by the PHP function mysql_error().  How can I test whether this data is a JSON string or the error message.

It would be nice to use a function called isJSON just like you can use the function instanceof to test if something is an Array.

This is what I want:

```<code>if (isJSON(data)){
    //do some data stuff
}else{
    //report the error
    alert(data);
}
</code>```

答:
Numbers and boolean values are accepted as valid json in JSON.parse(), just add type validations before parsing</p>
```<code>function isJson(str) {

    if(!isNaN(str) || str.toString() == 'true' || str.toString() == 'false'){
        return false;
    }

    try {

        JSON.parse(str);

    } catch (e) {

        return false;

    }

    return true;

}
</code>```

Title: How to test if a string is JSON or not?

Body:
I have a simple AJAX call, and the server will return either a JSON string with useful data or an error message string produced by the PHP function mysql_error().  How can I test whether this data is a JSON string or the error message.

It would be nice to use a function called isJSON just like you can use the function instanceof to test if something is an Array.

This is what I want:

if (isJSON(data)){
    //do some data stuff
}else{
    //report the error
    alert(data);
}

Body:
Numbers and boolean values are accepted as valid json in JSON.parse(), just add type validations before parsing

function isJson(str) {

    if(!isNaN(str) || str.toString() == 'true' || str.toString() == 'false'){
        return false;
    }

    try {

        JSON.parse(str);

    } catch (e) {

        return false;

    }

    return true;

}


问:
Removing header and footer in Elementor
I want to start designing with a blank page in Elementor but can't manage to remove the header and footer defined by the Wordpress theme.
As you can see in the screenshot I have already chosen the option "Elementor canvas." Nevertheless, the page still displays sidebar, header and footer from another theme.

Thanks in advance for any help!

答:
Make a new empty header & footer template and set it to display entire site.

User the theme "Hello Elementor" for a blank page.

Title: Removing header and footer in Elementor


问:
Replicate character across whole line on Vim/Neovim
I would to write a character, and instantly replicate it across the whole line. How can I write a function that mimics a keyboard shortcut in vim?</p>

答:
Go to the start of the line, visually select all the existing characters,
and replace them with the letter x:

0v$rx

Or if there are no characters already, you could insert an x 80 times in a
row:

80ix

An alternative would be to type the letter, then repeat it another 79 times:

ix

79.

Here's a function that will do it for you (called with <LEADER>r):

```<code>function! RepChar()
    let char = input("character to replicate: ")
    let line_length = &textwidth
    if line_length == 0
        let line_length = input("'textwidth' option not set... how long is a line: ")
    endif
    execute 'normal! '.line_length.'i'.char
endfunction
nnoremap <LEADER>r :call RepChar()<CR>
</code>```

Body:
Go to the start of the line, visually select all the existing characters,
and replace them with the letter x:

0v$rx

Or if there are no characters already, you could insert an x 80 times in a
row:

80ix

An alternative would be to type the letter, then repeat it another 79 times:

ix

79.

Here's a function that will do it for you (called with <LEADER>r):

function! RepChar()
    let char = input("character to replicate: ")
    let line_length = &textwidth
    if line_length == 0
        let line_length = input("'textwidth' option not set... how long is a line: ")
    endif
    execute 'normal! '.line_length.'i'.char
endfunction
nnoremap <LEADER>r :call RepChar()<CR>


问:
"Reply-to" field in Laravel mail is not working
I need help to figure out how to set the reply-to field in app/config/mail.php. I'm using Laravel 4 and it's not working. This is my app/config/mail.php:

```<code><?php

return array(
    'driver' => 'smtp',
    'host' => 'smtp.gmail.com',
    'port' => 587,
    'from' => [
        'address' => 'sender@domain.com',
        'name' => 'E-mail 1'
    ],
    'reply-to' => [
        'address' => 'replyto@domain.com',
        'name' => 'E-mail 2'
    ],
    'encryption' => 'tls',
    'username' => 'sender@domain.com',
    'password' => 'pwd',
    'pretend' => false,
);
</code>```

答:
Another option is to customizing SwiftMailer Message - https://laravel.com/docs/8.x/mail#customizing-the-swiftmailer-message.</p>
```<code>->withSwiftMessage(function ($message) use ($senderEmail) {
    $message->getHeaders()
        ->addTextHeader('Return-Path', $senderEmail);
})
</code>```

Body:
I need help to figure out how to set the reply-to field in app/config/mail.php. I'm using Laravel 4 and it's not working. This is my app/config/mail.php:

<?php

return array(
    'driver' => 'smtp',
    'host' => 'smtp.gmail.com',
    'port' => 587,
    'from' => [
        'address' => 'sender@domain.com',
        'name' => 'E-mail 1'
    ],
    'reply-to' => [
        'address' => 'replyto@domain.com',
        'name' => 'E-mail 2'
    ],
    'encryption' => 'tls',
    'username' => 'sender@domain.com',
    'password' => 'pwd',
    'pretend' => false,
);

Body:
Another option is to customizing SwiftMailer Message - https://laravel.com/docs/8.x/mail#customizing-the-swiftmailer-message.

->withSwiftMessage(function ($message) use ($senderEmail) {
    $message->getHeaders()
        ->addTextHeader('Return-Path', $senderEmail);
})


问:
Get the CN out of certificates information
I am trying to do a nice print out of the data from Ansible but have no idea on how to manipulate it.

This is what I have in the debug — I am trying to somehow manipulate the data so that it only gives me a CN= (without the CN=) value, and not the whole subject string:

[
        {
            "certkey": "Verisign_ca3_cer",
            "daystoexpiration": 0,
            "status": "Expired",
            "subject": " C=US,O=VeriSign, Inc.,OU=VeriSign Trust Network,OU=Terms of use at https://www.verisign.com/rpa (c)06,CN=VeriSign Class 3 Extended Validation SSL SGC CA"
        },
        {
            "certkey": "Verisign_ca5_cer",
            "daystoexpiration": 0,
            "status": "Expired",
            "subject": " C=US,O=VeriSign, Inc.,OU=VeriSign Trust Network,OU=Terms of use at https://www.verisign.com/rpa (c)10,CN=VeriSign Class 3 International Server CA - G3"
        }
]
```
<p>I wanted output similar to this:</p>
<pre class="lang-json prettyprint-override"><code>[
        {
            "certkey": "Verisign_ca3_cer",
            "daystoexpiration": 0,
            "status": "Expired",
            "subject": "CN=VeriSign Class 3 Extended Validation SSL SGC CA"
        },
        {
            "certkey": "Verisign_ca5_cer",
            "daystoexpiration": 0,
            "status": "Expired",
            "subject": "CN=VeriSign Class 3 International Server CA - G3"
        }
]
</code>```

答:
Q: "Select 'CN' from 'subject'."

A: Let's assume your data is a list of dictionaries, e.g.

    certs:
      - {"certkey": "Verisign_ca3_cer",
         "daystoexpiration": 0,
         "status": "Expired",
         "subject": " C=US,O=VeriSign, ...
```
<p>Create the list of the parsed subjects, e.g.</p>
<pre class="lang-yaml prettyprint-override"><code>    - set_fact:
        subjs: "{{ subjs|d([]) + [_subj] }}"
      loop: "{{ certs|map(attribute='subject')|list }}"
      vars:
        _subj: "{{ dict(item.split(',')|
                        select('match', '.*=.*')|
                        map('trim')|
                        map('split', '=')|
                        list) }}"
</code>```

gives

  subjs:
  - C: US
    CN: VeriSign Class 3 Extended Validation SSL SGC CA
    O: VeriSign
    OU: Terms of use at https://www.verisign.com/rpa (c)06
  - C: US
    CN: VeriSign Class 3 International Server CA - G3
    O: VeriSign
    OU: Terms of use at https://www.verisign.com/rpa (c)10
```
<p>and select the attribute 'CN'</p>
<pre class="lang-yaml prettyprint-override"><code>    - set_fact:
        CN: "{{ subjs|map(attribute='CN')|list }}"
</code>```

gives

  CN:
  - VeriSign Class 3 Extended Validation SSL SGC CA
  - VeriSign Class 3 International Server CA - G3
```
<hr>
<p>Combine the certificates with the updated attribute <em>subject</em>, e.g.</p>
<pre class="lang-yaml prettyprint-override"><code>    - set_fact:
        cert_cn: "{{ cert_cn|d([]) +
                     [item.0|combine({'subject': 'CN=' ~ item.1.CN})] }}"
      loop: "{{ certs|zip(subjs) }}"
</code>```

gives the output you want

  cert_cn:
  - certkey: Verisign_ca3_cer
    daystoexpiration: 0
    status: Expired
    subject: CN=VeriSign Class 3 Extended Validation SSL SGC CA
  - certkey: Verisign_ca5_cer
    daystoexpiration: 0
    status: Expired
    subject: CN=VeriSign Class 3 International Server CA - G3
```

Body:
I am trying to do a nice print out of the data from Ansible but have no idea on how to manipulate it.

This is what I have in the debug — I am trying to somehow manipulate the data so that it only gives me a CN= (without the CN=) value, and not the whole subject string:

[
        {
            "certkey": "Verisign_ca3_cer",
            "daystoexpiration": 0,
            "status": "Expired",
            "subject": " C=US,O=VeriSign, Inc.,OU=VeriSign Trust Network,OU=Terms of use at https://www.verisign.com/rpa (c)06,CN=VeriSign Class 3 Extended Validation SSL SGC CA"
        },
        {
            "certkey": "Verisign_ca5_cer",
            "daystoexpiration": 0,
            "status": "Expired",
            "subject": " C=US,O=VeriSign, Inc.,OU=VeriSign Trust Network,OU=Terms of use at https://www.verisign.com/rpa (c)10,CN=VeriSign Class 3 International Server CA - G3"
        }
]

I wanted output similar to this:

[
        {
            "certkey": "Verisign_ca3_cer",
            "daystoexpiration": 0,
            "status": "Expired",
            "subject": "CN=VeriSign Class 3 Extended Validation SSL SGC CA"
        },
        {
            "certkey": "Verisign_ca5_cer",
            "daystoexpiration": 0,
            "status": "Expired",
            "subject": "CN=VeriSign Class 3 International Server CA - G3"
        }
]

Body:
Q: "Select 'CN' from 'subject'."

A: Let's assume your data is a list of dictionaries, e.g.

    certs:
      - {"certkey": "Verisign_ca3_cer",
         "daystoexpiration": 0,
         "status": "Expired",
         "subject": " C=US,O=VeriSign, ...

Create the list of the parsed subjects, e.g.

    - set_fact:
        subjs: "{{ subjs|d([]) + [_subj] }}"
      loop: "{{ certs|map(attribute='subject')|list }}"
      vars:
        _subj: "{{ dict(item.split(',')|
                        select('match', '.*=.*')|
                        map('trim')|
                        map('split', '=')|
                        list) }}"

gives

  subjs:
  - C: US
    CN: VeriSign Class 3 Extended Validation SSL SGC CA
    O: VeriSign
    OU: Terms of use at https://www.verisign.com/rpa (c)06
  - C: US
    CN: VeriSign Class 3 International Server CA - G3
    O: VeriSign
    OU: Terms of use at https://www.verisign.com/rpa (c)10

and select the attribute 'CN'

    - set_fact:
        CN: "{{ subjs|map(attribute='CN')|list }}"

gives

  CN:
  - VeriSign Class 3 Extended Validation SSL SGC CA
  - VeriSign Class 3 International Server CA - G3

Combine the certificates with the updated attribute subject, e.g.

    - set_fact:
        cert_cn: "{{ cert_cn|d([]) +
                     [item.0|combine({'subject': 'CN=' ~ item.1.CN})] }}"
      loop: "{{ certs|zip(subjs) }}"

gives the output you want

  cert_cn:
  - certkey: Verisign_ca3_cer
    daystoexpiration: 0
    status: Expired
    subject: CN=VeriSign Class 3 Extended Validation SSL SGC CA
  - certkey: Verisign_ca5_cer
    daystoexpiration: 0
    status: Expired
    subject: CN=VeriSign Class 3 International Server CA - G3


问:
How to connect to testcontainers redis correctly during spring boot integration test?
I am writing test for my service in spring boot

```<code>@Component
public class MyService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    // a number of other @Autowired dependencies

    public User getUser(String uuid) {
        var key = String.format("user:%s", uuid);
        var cache = stringRedisTemplate.opsForValue().get(key);
        if (cache == null) {
            // return user from database
        } else {
            // return user from deserialized cache
        }
    }
}

@Testcontainers
@SpringBootTest
class MyServiceTest {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    MyService myService;

    @Container
    public static GenericContainer<?> redis =
        new GenericContainer<>("redis:5.0.14-alpine3.15").withExposedPorts(6379);

    @BeforeClass
    public static void startContainer() {
        redis.start();
        var redisUrl = String.format("redis://%s:%s", redis.getHost(), redis.getMappedPort(6379));
        System.setProperty("spring.redis.url", redisUrl);
    }

    @AfterClass
    public static void stopContainer() {
        redis.stop();
    }

    @Test
    void getUser_returnCachedUser() {
        // breakpoint here
        stringRedisTemplate.opsForValue().set("user:some-uuid", "{\"uuid\":\"some-uuid\",\"name\":\"cache\"}");
        var user = myService.getUser("some-uuid");
        assertEquals("cache", user.name);
    }
}
</code>```

When I ran this in debug mode and hit breakpoint, I noticed port redis.getMappedPort(6379) in console was not equal to stringRedisTemplate.connectionFactory.client or myService.stringRedisTemplate.connectionFactory.client.

Did System.setProperty overwrite properties and take effect in this case?
How can I use testcontainers in spring boot integration test?

答:
I'd suggest to use slightly different container from playtika which is built on top of testcontainers.

What you need to do is to include spring-cloud-starter-bootstrap in your pom.xml (it's enough as a test dependency).

and then in your test application.yaml|properties use following:

spring:
  redis:
    port: ${embedded.redis.port}
    password: ${embedded.redis.password}
    host: ${embedded.redis.host}
    ssl: false
```

Body:
I am writing test for my service in spring boot

@Component
public class MyService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    // a number of other @Autowired dependencies

    public User getUser(String uuid) {
        var key = String.format("user:%s", uuid);
        var cache = stringRedisTemplate.opsForValue().get(key);
        if (cache == null) {
            // return user from database
        } else {
            // return user from deserialized cache
        }
    }
}

@Testcontainers
@SpringBootTest
class MyServiceTest {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    MyService myService;

    @Container
    public static GenericContainer<?> redis =
        new GenericContainer<>("redis:5.0.14-alpine3.15").withExposedPorts(6379);

    @BeforeClass
    public static void startContainer() {
        redis.start();
        var redisUrl = String.format("redis://%s:%s", redis.getHost(), redis.getMappedPort(6379));
        System.setProperty("spring.redis.url", redisUrl);
    }

    @AfterClass
    public static void stopContainer() {
        redis.stop();
    }

    @Test
    void getUser_returnCachedUser() {
        // breakpoint here
        stringRedisTemplate.opsForValue().set("user:some-uuid", "{\"uuid\":\"some-uuid\",\"name\":\"cache\"}");
        var user = myService.getUser("some-uuid");
        assertEquals("cache", user.name);
    }
}

When I ran this in debug mode and hit breakpoint, I noticed port redis.getMappedPort(6379) in console was not equal to stringRedisTemplate.connectionFactory.client or myService.stringRedisTemplate.connectionFactory.client.

Did System.setProperty overwrite properties and take effect in this case?
How can I use testcontainers in spring boot integration test?


问:
Unable to remove the padding in Expanded Widget
I can't seem to find why after the first Text Widget, there is a big gap of space. I didn't put any Padding or SizedBox but somehow, the Expanded seem to have its own padding. Please help on how can I adjust that space in between the text and numbers. Thanks!

```<code>  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('Text'),
        Expanded(
          child: GridView.builder(
              physics: const NeverScrollableScrollPhysics(),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3, childAspectRatio: 5 / 1),
              itemCount: 6,
              itemBuilder: (BuildContext ctx, index) {
                return Text('$index');
              }),
        ),
      ],
    );
  }
</code>```

Output:

```<code>Text

0     1     2
3     4     5
</code>```

Expected output:

```<code>Text
0     1     2
3     4     5
</code>```

Note: This is the minimized code in order to show the essential.

答:
Change your GridView.builder to this:

```<code>  Expanded(
    child: GridView.builder(
      padding: const EdgeInsets.only(top: 0),
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3, childAspectRatio: 5 / 1),
        itemCount: 6,
        itemBuilder: (BuildContext ctx, index) {
          return Text('$index');
        }),
  )
</code>```

Body:
I can't seem to find why after the first Text Widget, there is a big gap of space. I didn't put any Padding or SizedBox but somehow, the Expanded seem to have its own padding. Please help on how can I adjust that space in between the text and numbers. Thanks!

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('Text'),
        Expanded(
          child: GridView.builder(
              physics: const NeverScrollableScrollPhysics(),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3, childAspectRatio: 5 / 1),
              itemCount: 6,
              itemBuilder: (BuildContext ctx, index) {
                return Text('$index');
              }),
        ),
      ],
    );
  }

Output:

Text

0     1     2
3     4     5

Expected output:

Text
0     1     2
3     4     5

Note: This is the minimized code in order to show the essential.

Body:
Change your GridView.builder to this:

  Expanded(
    child: GridView.builder(
      padding: const EdgeInsets.only(top: 0),
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3, childAspectRatio: 5 / 1),
        itemCount: 6,
        itemBuilder: (BuildContext ctx, index) {
          return Text('$index');
        }),
  )


问:
ERROR 1049 (42000): Unknown database 'mydatabasename'
I am trying to restore database from .sql file , i have created the database in phpmyadmin and also using the create if not exist command in the .sql file which i am restoring to the database and both names of database are same in phpmyadmin and .sql file which is"mydatabase".

Here is the command which i am using to restore database.

```<code>mysql -uroot -pmypassword mydatabase<mydatabase.sql;
</code>```

When i execute the above command i am getting the following error, i have also given all the permission to the user upon this database.

```<code>ERROR 1049 (42000): Unknown database 'mydatabasename'
</code>```

答:
Create database:

CREATE DATABASE mydatabasename;
USE mydatabasename;

use this one:
mysql -u root -p  'mydatabasename'< '/tmp/db_dump.sql'

Body:
I am trying to restore database from .sql file , i have created the database in phpmyadmin and also using the create if not exist command in the .sql file which i am restoring to the database and both names of database are same in phpmyadmin and .sql file which is"mydatabase".

Here is the command which i am using to restore database.

mysql -uroot -pmypassword mydatabase<mydatabase.sql;

When i execute the above command i am getting the following error, i have also given all the permission to the user upon this database.

ERROR 1049 (42000): Unknown database 'mydatabasename'


问:
How do I link to a static library (libtiff) using CMake in my wxWidgets project?
For my wxWidgets project, I am trying to make the switch from my self-written Makefile to Cmake. I develop on macOS.

When I was writing that Makefile I ran into an issue with libtiff. I wanted to statically link my application so that I don't have to distribute any dylibs myself or rely on my users to install them. I built wxWidgets as a static library but when I compiled my code and checked my binary with otool I always found that my binary required a local dylib.

```<code>/usr/local/opt/libtiff/lib/libtiff.5.dylib
</code>```

Finally I found a solution on here. In essence, in the linking line of my Makefile I replaced wx-config –-libs with LDFLAGS. LDFLAGS looks like this:

```<code>WXCONFIGLIBS := $(shell wx-config --libs)
WXCONFIGLIBS := $(WXCONFIGLIBS:-ltiff=/usr/local/opt/libtiff//lib/libtiff.a)
# I am not sure whether the double slash is a typo but it works so I don't change it
LDFLAGS := $(WXCONFIGLIBS)
</code>```

Basically, I search-and-replaced -ltiff with the path to my static libtiff library.

Now I've managed to compile my project using Cmake. However, I'm getting the same warning message as I did when I battled my original issue.

```<code>ld: warning: dylib (/usr/local/lib/libtiff.dylib) was built for newer macOS version (11.0) than being linked (10.11)
</code>```

How do I fix this? My CMakeLists contains these sections pertaining to wxWidgets:

```<code>find_package(wxWidgets REQUIRED gl core base OPTIONAL_COMPONENTS net)
include(${wxWidgets_USE_FILE})
...
add_executable(myapp ${SOURCES})
target_link_libraries(myapp ${wxWidgets_LIBRARIES})
set_property(TARGET myapp PROPERTY CXX_STANDARD 17)
</code>```

I already tried running some search-and-replace shenanigans like

```<code>string(REPLACE "-ltiff" "/usr/local/opt/libtiff/lib/libtiff.a" wxWidgets_LIBRARIES ${wxWidgets_LIBRARIES})
</code>```

But that doesn't work. It does replace -ltiff but also seems to remove the semicolons and whitespaces separating the different libraries.

I've been scouring the web for any clues as to what to do, but I don't seem to have a good enough grasp of libraries to fix this.

Any help would be greatly appreciated.

答:
My search-and-replace idea turned out to be not so bad. I was able to achieve the same outcome with Cmake as with my Makefile.

My problem was not using double quotes in the appropriate place. So instead of this:

```<code>string(REPLACE "-ltiff" "/usr/local/opt/libtiff/lib/libtiff.a" wxWidgets_LIBRARIES ${wxWidgets_LIBRARIES})
</code>```

I simply needed to write:

```<code>string(REPLACE "-ltiff" "/usr/local/opt/libtiff/lib/libtiff.a" wxWidgets_LIBRARIES "${wxWidgets_LIBRARIES}")
</code>```

So to solve my actual problem, I am calling this string() command just before the target_link_libraries() command.

Body:
For my wxWidgets project, I am trying to make the switch from my self-written Makefile to Cmake. I develop on macOS.

When I was writing that Makefile I ran into an issue with libtiff. I wanted to statically link my application so that I don't have to distribute any dylibs myself or rely on my users to install them. I built wxWidgets as a static library but when I compiled my code and checked my binary with otool I always found that my binary required a local dylib.

/usr/local/opt/libtiff/lib/libtiff.5.dylib

Finally I found a solution on here. In essence, in the linking line of my Makefile I replaced wx-config –-libs with LDFLAGS. LDFLAGS looks like this:

WXCONFIGLIBS := $(shell wx-config --libs)
WXCONFIGLIBS := $(WXCONFIGLIBS:-ltiff=/usr/local/opt/libtiff//lib/libtiff.a)
# I am not sure whether the double slash is a typo but it works so I don't change it
LDFLAGS := $(WXCONFIGLIBS)

Basically, I search-and-replaced -ltiff with the path to my static libtiff library.

Now I've managed to compile my project using Cmake. However, I'm getting the same warning message as I did when I battled my original issue.

ld: warning: dylib (/usr/local/lib/libtiff.dylib) was built for newer macOS version (11.0) than being linked (10.11)

How do I fix this? My CMakeLists contains these sections pertaining to wxWidgets:

find_package(wxWidgets REQUIRED gl core base OPTIONAL_COMPONENTS net)
include(${wxWidgets_USE_FILE})
...
add_executable(myapp ${SOURCES})
target_link_libraries(myapp ${wxWidgets_LIBRARIES})
set_property(TARGET myapp PROPERTY CXX_STANDARD 17)

I already tried running some search-and-replace shenanigans like

string(REPLACE "-ltiff" "/usr/local/opt/libtiff/lib/libtiff.a" wxWidgets_LIBRARIES ${wxWidgets_LIBRARIES})

But that doesn't work. It does replace -ltiff but also seems to remove the semicolons and whitespaces separating the different libraries.

I've been scouring the web for any clues as to what to do, but I don't seem to have a good enough grasp of libraries to fix this.

Any help would be greatly appreciated.

Body:
My search-and-replace idea turned out to be not so bad. I was able to achieve the same outcome with Cmake as with my Makefile.

My problem was not using double quotes in the appropriate place. So instead of this:

string(REPLACE "-ltiff" "/usr/local/opt/libtiff/lib/libtiff.a" wxWidgets_LIBRARIES ${wxWidgets_LIBRARIES})

I simply needed to write:

string(REPLACE "-ltiff" "/usr/local/opt/libtiff/lib/libtiff.a" wxWidgets_LIBRARIES "${wxWidgets_LIBRARIES}")

So to solve my actual problem, I am calling this string() command just before the target_link_libraries() command.


问:
Updating only SQLite database file of application without replacing application code and other files on air
I am developing an android application with inbuilt SQLite database. I need to replace SQLite database file only every 3 months. while doing this I should not alter any part of code.

Also I don't want to do this as upgrading application where changing app version I can replace old application with newer version and new database.

For example if I give a button "Update Database" and after clicking this button only database file is replaced using internet and other parts of application remains intact.

答:
simply do as you'd do with any file:

Download the database file from a web server to the devices temp directory (or cache or SDCard)

Move that file to your application's data directory

To do that automatically, you should use a service started by the AlarmManager.