问:
How to fix? Discord.js Bot keeps going offline because of Value error
I keep getting this error

```<code>TypeError: Cannot read property 'size' of undefined
at Client.client.on.message
(/home/colter/Code/groundskeeper/index.js:38:30)
at emitOne (events.js:116:13)
at Client.emit (events.js:211:7)
at MessageCreateHandler.handle
</code>```

I have checked for errors and compared it to the sample code. It all looks right to me.

```<code>client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot)
return;

const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();

// Here is my syntax for adding commands. So far simple ones, but commands non the less!
if (command === 'ping') {
    message.channel.send('Pong');
}
else if (command === 'beep') {
    message.channel.send('Boop');
}
else if (command === 'server') {
    message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);
}
else if (command === 'user-info') {
    message.channel.send(`Your username: ${message.author.username}\nYour ID: ${message.author.id}`);
}
else if (command === 'args-info') {
    if (!args.length) {
        return message.channel.send(`Your didnt provide any arguments, ${message.author}!`);
    }
    else if (args[0] === 'foo') {
        return message.channel.send('bar');
    }
    message.channel.send(`first argument: ${args[0]}`);
}
else if (command === 'kick') {
    if (!message.mentions.user.size) {
        return message.reply('you need to tag a user in order to kick them');
    }

    const taggedUser = message.mentions.users.first();

    message.channel.send(`You wanted to kick: ${taggedUser}`);
}
});

client.login(token);
</code>```

the expected output should be you need to tag a user in order to kick them from my bot when I use the ?kick command.

答:
On your code:

```<code>message.mentions.user.size
</code>```

Is trying to read the property size of user, that is inside mentions, that is inside message.
If message, mentions and user don't exist, there's no size property to be read, you cannot read a property of something that does not exist.
You can check beforehand if it exists:

```<code>if(message.mentions.user) {
    if (!message.mentions.user.size) {
        return message.reply('you need to tag a user in order to kick them');
    }
}
</code>```

Body:
I keep getting this error

TypeError: Cannot read property 'size' of undefined
at Client.client.on.message
(/home/colter/Code/groundskeeper/index.js:38:30)
at emitOne (events.js:116:13)
at Client.emit (events.js:211:7)
at MessageCreateHandler.handle

I have checked for errors and compared it to the sample code. It all looks right to me.

client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot)
return;

const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();

// Here is my syntax for adding commands. So far simple ones, but commands non the less!
if (command === 'ping') {
    message.channel.send('Pong');
}
else if (command === 'beep') {
    message.channel.send('Boop');
}
else if (command === 'server') {
    message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);
}
else if (command === 'user-info') {
    message.channel.send(`Your username: ${message.author.username}\nYour ID: ${message.author.id}`);
}
else if (command === 'args-info') {
    if (!args.length) {
        return message.channel.send(`Your didnt provide any arguments, ${message.author}!`);
    }
    else if (args[0] === 'foo') {
        return message.channel.send('bar');
    }
    message.channel.send(`first argument: ${args[0]}`);
}
else if (command === 'kick') {
    if (!message.mentions.user.size) {
        return message.reply('you need to tag a user in order to kick them');
    }

    const taggedUser = message.mentions.users.first();

    message.channel.send(`You wanted to kick: ${taggedUser}`);
}
});

client.login(token);

the expected output should be you need to tag a user in order to kick them from my bot when I use the ?kick command.

Body:
On your code:

message.mentions.user.size

Is trying to read the property size of user, that is inside mentions, that is inside message.
If message, mentions and user don't exist, there's no size property to be read, you cannot read a property of something that does not exist.
You can check beforehand if it exists:

if(message.mentions.user) {
    if (!message.mentions.user.size) {
        return message.reply('you need to tag a user in order to kick them');
    }
}


来源: stackexchange

问:
Visual Studio - Pre- and post-build execution locations
Is there a way to change the location of the path in which Visual Studio 2015 executes the pre- and post-build events?

In my company there was a change in the Group Policy, so pre- and post-build events are resulting in the following error message:

This program is blocked by group policy. For more information, contact your system administrator.

This is because the new group policy prevents cmds from running out of the USER-folder.

Any idea of how to resolve this without running Visual Studio as an administrator or changing the Group Policy?

答: To resolve this issue, you can run your Visual Studio as Administrator </p>

ContentLicense: CC BY-SA 4.0


问:
How to Implement step Progress bar like flipkart delivery report bar
I need to implement a progress bar which shows the background processes step wise when i click on a submit button. When i click on the button the process should start which involves steps like patch started, patch in process, patch completed, process completed and  at the same time it should show the steps happening on progress bar.
For example, delivery report bar on the flipkart.
What needs to be done?
Im using asp.net

Thank you

答:
You can use SignalR in this case, which allows server code to send asynchronous notifications to client-side web applications.
This link can help you to understand how you can implement in asp.net.


问:
Conversion of tensorflow float32 is incompatible with a java object
Error:
Caused by: java.lang.IllegalArgumentException: Cannot convert between a TensorFlowLite tensor with type FLOAT32 and a Java object of type java.lang.String (which is compatible with the TensorFlowLite type STRING).

I have built a neural network from my dataset and have 2 layers then I have saved the model as h5 and then converted it into tflite using tf.keras model and conversions but when I deploy it in the application it gives me the above error

I have tried inputting with a lot of type of arrays and array lists

Error:
Caused by: java.lang.IllegalArgumentException: Cannot convert between a TensorFlowLite tensor with type FLOAT32 and a Java object of type java.lang.String (which is compatible with the TensorFlowLite type STRING).

```<code>model.add(layers.Dense(500, input_dim=3, activation='relu'))
model.add(layers.Dense(1, activation= "relu"))
model.summary() #Print model Summary
model.compile(loss='mean_squared_error',optimizer='adam')
model.fit(X_train,Y_train,epochs=1000,validation_split=0.3)
</code>```

How I convert:-

```<code>from tensorflow.contrib import lite
converter = lite.TFLiteConverter.from_keras_model_file( 'Model.h5')
tfmodel = converter.convert()
open ("model.tflite" , "wb") .write(tfmodel)
</code>```

Implementation to android

```<code>ArrayList<String> list = new ArrayList<>();
list.add("-0.5698444");
list.add("-0.57369368");
list.add("-1.31490297");

try (Interpreter interpreter = new Interpreter(mappedByteBuffer)) {
    interpreter.run(list, "output");
}

private MappedByteBuffer loadModelFile() throws IOException {
    AssetFileDescriptor fileDescriptor = getAssets().openFd("model.tflite");
    FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
    FileChannel fileChannel = inputStream.getChannel();
    long startOffset = fileDescriptor.getStartOffset();
    long declaredLength = fileDescriptor.getDeclaredLength();
    return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
}
</code>```

答:
Found the mistake. In the line,

```<code>try (Interpreter interpreter = new Interpreter(mappedByteBuffer)) {
    interpreter.run(list, "output");
 }
</code>```

The 2nd argument for the interpreter.run() has to be a float[] and not "output". The float[] will be populated with the class probabilities when the model is run.

The correct method to provide inputs and outputs to the interpreter.run() method:

```<code>Interpreter interpreter = new Interpreter(mappedByteBuffer)

float[][] inputs = new float[1][num_features]
// populate the inputs float array above
float[][] outputs = new float[1][num_classes]

interpreter.run( inputs , outputs )

float[] classProb = outputs[0]
</code>```

Body:
Error:
Caused by: java.lang.IllegalArgumentException: Cannot convert between a TensorFlowLite tensor with type FLOAT32 and a Java object of type java.lang.String (which is compatible with the TensorFlowLite type STRING).

I have built a neural network from my dataset and have 2 layers then I have saved the model as h5 and then converted it into tflite using tf.keras model and conversions but when I deploy it in the application it gives me the above error

I have tried inputting with a lot of type of arrays and array lists

Error:
Caused by: java.lang.IllegalArgumentException: Cannot convert between a TensorFlowLite tensor with type FLOAT32 and a Java object of type java.lang.String (which is compatible with the TensorFlowLite type STRING).

model.add(layers.Dense(500, input_dim=3, activation='relu'))
model.add(layers.Dense(1, activation= "relu"))
model.summary() #Print model Summary
model.compile(loss='mean_squared_error',optimizer='adam')
model.fit(X_train,Y_train,epochs=1000,validation_split=0.3)

How I convert:-

from tensorflow.contrib import lite
converter = lite.TFLiteConverter.from_keras_model_file( 'Model.h5')
tfmodel = converter.convert()
open ("model.tflite" , "wb") .write(tfmodel)

Implementation to android

ArrayList<String> list = new ArrayList<>();
list.add("-0.5698444");
list.add("-0.57369368");
list.add("-1.31490297");

try (Interpreter interpreter = new Interpreter(mappedByteBuffer)) {
    interpreter.run(list, "output");
}

private MappedByteBuffer loadModelFile() throws IOException {
    AssetFileDescriptor fileDescriptor = getAssets().openFd("model.tflite");
    FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
    FileChannel fileChannel = inputStream.getChannel();
    long startOffset = fileDescriptor.getStartOffset();
    long declaredLength = fileDescriptor.getDeclaredLength();
    return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
}

Body:
Found the mistake. In the line,

try (Interpreter interpreter = new Interpreter(mappedByteBuffer)) {
    interpreter.run(list, "output");
 }

The 2nd argument for the interpreter.run() has to be a float[] and not "output". The float[] will be populated with the class probabilities when the model is run.

The correct method to provide inputs and outputs to the interpreter.run() method:

Interpreter interpreter = new Interpreter(mappedByteBuffer)

float[][] inputs = new float[1][num_features]
// populate the inputs float array above
float[][] outputs = new float[1][num_classes]

interpreter.run( inputs , outputs )

float[] classProb = outputs[0]


问:
Binary operator '*' cannot be applied to operands of type 'Float' and 'Double'
I am implementing AudioVisualizer and I am trying to calculate time of audio but I am getting below error

Binary operator '*' cannot be applied to operands of type 'Float' and 'Double'

Here is my code:

```<code> var lowPassReslts: Double = 0.0
 var lowPassReslts1: Double = 0.0

 let ALPHA: Float = 1.05

 let averagePowerForChannel = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 0)))
 lowPassReslts = ALPHA * averagePowerForChannel + (1.0 - ALPHA) * lowPassReslts //HERE i am getting error which i mention above

 let averagePowerForChannel1 = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 1)))
 lowPassReslts1 = ALPHA * averagePowerForChannel1 + (1.0 - ALPHA) * lowPassReslts1 //HERE i am getting error
</code>```

This above code have converted from Objective-C. This code works perfect in Objective-C but it is not working in Swift. Can anyone please tell me how to solve this error?

答:
Make your parameter type of ALPHA as Double or change your lowPassReslts as Float.

Try the following code:

```<code>var lowPassReslts: Double = 0.0
var lowPassReslts1: Double = 0.0

let ALPHA: Double = 1.05

let averagePowerForChannel = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 0)))
lowPassReslts = ALPHA * averagePowerForChannel + (1.0 - ALPHA) * lowPassReslts

let averagePowerForChannel1 = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 1)))
lowPassReslts1 = ALPHA * averagePowerForChannel1 + (1.0 - ALPHA) * lowPassReslts1
</code>```

In swift there is no need to declare the variable type. You can directly declare the variable as,

```<code>  var lowPassReslts = 0.0
  var lowPassReslts1 = 0.0
  let ALPHA = 1.05
</code>```

Try any of the above method. Hope it will help you.

Body:
I am implementing AudioVisualizer and I am trying to calculate time of audio but I am getting below error

Binary operator '*' cannot be applied to operands of type 'Float' and 'Double'

Here is my code:

 var lowPassReslts: Double = 0.0
 var lowPassReslts1: Double = 0.0

 let ALPHA: Float = 1.05

 let averagePowerForChannel = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 0)))
 lowPassReslts = ALPHA * averagePowerForChannel + (1.0 - ALPHA) * lowPassReslts //HERE i am getting error which i mention above

 let averagePowerForChannel1 = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 1)))
 lowPassReslts1 = ALPHA * averagePowerForChannel1 + (1.0 - ALPHA) * lowPassReslts1 //HERE i am getting error

This above code have converted from Objective-C. This code works perfect in Objective-C but it is not working in Swift. Can anyone please tell me how to solve this error?

Body:
Make your parameter type of ALPHA as Double or change your lowPassReslts as Float.

Try the following code:

var lowPassReslts: Double = 0.0
var lowPassReslts1: Double = 0.0

let ALPHA: Double = 1.05

let averagePowerForChannel = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 0)))
lowPassReslts = ALPHA * averagePowerForChannel + (1.0 - ALPHA) * lowPassReslts

let averagePowerForChannel1 = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 1)))
lowPassReslts1 = ALPHA * averagePowerForChannel1 + (1.0 - ALPHA) * lowPassReslts1

In swift there is no need to declare the variable type. You can directly declare the variable as,

  var lowPassReslts = 0.0
  var lowPassReslts1 = 0.0
  let ALPHA = 1.05

Try any of the above method. Hope it will help you.


问:
How do I respond with a message to a user when they trigger an error on my Discord bot?
I'm trying to make my Discord bot reply to a user letting them know that there was an error if one occurred when they ran a command. I'm unsure of how I'm supposed to get my message variable from the command message in my index file from the command.

I've already tried using the message variable in a function that is running in my index.js file from the command file, but when it runs it says that 'message' is not defined. I suspect that it may be where I've put my .catch(). Here is the code that I am using.

```<code>//This is the area in my index that handles errors
bot.on('error', (err, message) => {
  console.error();
  message.reply("error here, possibly a rich presence");
});

//Heres the function with the .catch()
http.request(options, function(res) {
    var body = '';

    res.on('data', function (chunk) {
        body+= chunk;
    });

    res.on('end', function() {
       var jsondata = JSON.parse(body);
       var converteddate = new Date(jsondata.toTimestamp*1000)
       console.log(converteddate)
       var hours = converteddate.getHours();
       var minutes = "0" + converteddate.getMinutes();
       var finishedtime = hours + ':' + minutes.substr(-2);
        message.reply(finishedtime + " EST.")
})
}).end()
.catch(err => bot.emit('error', err, message));
}
</code>```

The expected output of this is to run the command and if there are any errors, notify the user of them. Thanks for the help!

答:
Ok, so first you have a problem with your '}' (there's one that shouldn't be here at the end)

Then, a simple example how to catch:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function error() {
  await sleep(3000); // wait 5 sec for the sake of the example
  throw 'I have a problem';
}
console.log('starting')
error().catch((err) => console.log('The error:',err))```
</div>
</div>
</p>

<p>I'm not sure what is the <code>.end()</code>, but I think you don't need it</p>

<p>So here, you want to do :</p>

```http.request(options, function(){
    // do something
    return 'text message'; // what you want to reply
}).catch((err) => err).then((msg) => message.reply(msg))
```

Body:
I'm trying to make my Discord bot reply to a user letting them know that there was an error if one occurred when they ran a command. I'm unsure of how I'm supposed to get my message variable from the command message in my index file from the command.

I've already tried using the message variable in a function that is running in my index.js file from the command file, but when it runs it says that 'message' is not defined. I suspect that it may be where I've put my .catch(). Here is the code that I am using.

//This is the area in my index that handles errors
bot.on('error', (err, message) => {
  console.error();
  message.reply("error here, possibly a rich presence");
});

//Heres the function with the .catch()
http.request(options, function(res) {
    var body = '';

    res.on('data', function (chunk) {
        body+= chunk;
    });

    res.on('end', function() {
       var jsondata = JSON.parse(body);
       var converteddate = new Date(jsondata.toTimestamp*1000)
       console.log(converteddate)
       var hours = converteddate.getHours();
       var minutes = "0" + converteddate.getMinutes();
       var finishedtime = hours + ':' + minutes.substr(-2);
        message.reply(finishedtime + " EST.")
})
}).end()
.catch(err => bot.emit('error', err, message));
}

The expected output of this is to run the command and if there are any errors, notify the user of them. Thanks for the help!

Body:
Ok, so first you have a problem with your '}' (there's one that shouldn't be here at the end)

Then, a simple example how to catch:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function error() {
  await sleep(3000); // wait 5 sec for the sake of the example
  throw 'I have a problem';
}
console.log('starting')
error().catch((err) => console.log('The error:',err))

I'm not sure what is the .end(), but I think you don't need it

So here, you want to do :

http.request(options, function(){
    // do something
    return 'text message'; // what you want to reply
}).catch((err) => err).then((msg) => message.reply(msg))


问:
How to add dropdown in OnClick editor?
I'm looking for a way to add a dropdown box to the OnClick editor in the inspector (circled in the image below)

I would like the dropdown to be populated by a custom enum.

Is this possible at all or do I need to find another way to do this?

Goal:

Have an enum of audio clips and be able to assign a clip to a button all from the inspector without having to go into the code.

答:
Assuming you know how the editor and C# script interface with each other I would simply use:

```<code>public static bool DropdownButton(GUIContent content, FocusType focusType, params GUILayoutOption[] options);
</code>```

More info can be found here: https://docs.unity3d.com/ScriptReference/EditorGUILayout.DropdownButton.html

Title: How to add dropdown in OnClick editor?

Body:
Assuming you know how the editor and C# script interface with each other I would simply use:

public static bool DropdownButton(GUIContent content, FocusType focusType, params GUILayoutOption[] options);

More info can be found here: https://docs.unity3d.com/ScriptReference/EditorGUILayout.DropdownButton.html


问:
Login using PHP to protect from downloading a file
Can I use PHP to protect someone from downloading a file unless he enters a username and password just like the sample image?

sample: http://up.iranblog.com/images/f1ufuir6kl8srq4ww4.jpg

答:
If you're trying to use PHP to download a ZIP file from another server which asks for authentication, try the following:</p>

```<code><?php

copy("http://username:password@domain.com/path/to/file.zip", "./file.zip");

?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you're trying to use PHP to download a ZIP file from another server which asks for authentication, try the following:

<?php

copy("http://username:password@domain.com/path/to/file.zip", "./file.zip");

?>


问:
RegEx for passing punctuation
I am using:

```<code>(.*) CO\s?[\(.*\)|\[.*\]|\{.*\}|''.*''|".*"](.*)
</code>```

to represent

```<code>3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY).
</code>```

However, the first Single quotation mark cannot be covered by the regex code. Could you please tell me why?

```<code>s/(.*) CO\s?[\(.*\)|\[.*\]|\{.*\}|''.*''|".*"](.*)/$1 CO $2
</code>```

I expect to get:

```<code>3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY)
</code>```

but I get

```<code>3M CO A'(MINNESOTA MINING AND MANUFACTURING COMPANY)
</code>```

答:
Your regex should be expressed to

```<code>/(.*)\sCO\s?(\(.+\).*|".+".*|'.+'.*|{.+}.*|\[.+\].*)/
</code>```

(.*) First capture group will capture starting group ("3M" in your example)

\sCO\s Then looks for a whitespace followed by CO followed by a whitespace

(".+".* etc.) Second capture group that looks for starting quote or bracket followed by at least one character of anything followed by closing quote, then followed by any number of any character

Why Original Regex Didn't Work

In the original regex, [\(.*\)|\[.*\]|\{.*\}|''.*''|".*"] can be simplified into [''.*''] (for the string you provided). I realize that for other strings, you might want to look for (.*) or [.*] or {.*} or ".*", but for the "3M" string, only the [''.*''] is relevant so we'll just look at this.

So [''.*''] just means: match any character in the list inside [], in any order. In this case, there are three unique characters in the list: ', . and * (although you did repeat ' 3 times).  So it matched the first '. But since this match is outside your capture group (), this first ' is not included in your capture group response.

So the next match with (.*) matches everything else that comes after the first ' and includes them in the second matching group, i.e. A'(MINNESOTA MINING AND MANUFACTURING COMPANY) without the ' in front.

Does that make sense?

Demo

If you wanted to ensure the format includes 'A' or [A] or "A" or {A} or (A), then this is what you want:

let regex = /(.*)\sCO\s?(\(.+\)|".+".*|'.+'.*|{.+}.*|\[.+\].*)/;

[pattern, match1, match2] = "3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY)".match(regex);
console.log(match1 + " CO " + match2);
//3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY)

[pattern, match1, match2] = '3M CO (A)(MINNESOTA MINING AND MANUFACTURING COMPANY)'.match(regex);
console.log(match1 + " CO " + match2);
//3M CO (A)(MINNESOTA MINING AND MANUFACTURING COMPANY)

[pattern, match1, match2] = '3M CO "A"(MINNESOTA MINING AND MANUFACTURING COMPANY)'.match(regex);
console.log(match1 + " CO " + match2);
//3M CO "A"(MINNESOTA MINING AND MANUFACTURING COMPANY)

[pattern, match1, match2] = "3M CO [A](MINNESOTA MINING AND MANUFACTURING COMPANY)".match(regex);
console.log(match1 + " CO " + match2);
//3M CO [A](MINNESOTA MINING AND MANUFACTURING COMPANY)

[pattern, match1, match2] = "3M CO {A}(MINNESOTA MINING AND MANUFACTURING COMPANY)".match(regex);
console.log(match1 + " CO " + match2);
//3M CO {A}(MINNESOTA MINING AND MANUFACTURING COMPANY)```

Title: RegEx for passing punctuation

Body:
I am using:

(.*) CO\s?[\(.*\)|\[.*\]|\{.*\}|''.*''|".*"](.*)

to represent

3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY).

However, the first Single quotation mark cannot be covered by the regex code. Could you please tell me why?

s/(.*) CO\s?[\(.*\)|\[.*\]|\{.*\}|''.*''|".*"](.*)/$1 CO $2

I expect to get:

3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY)

but I get

3M CO A'(MINNESOTA MINING AND MANUFACTURING COMPANY)

Body:
Your regex should be expressed to

/(.*)\sCO\s?(\(.+\).*|".+".*|'.+'.*|{.+}.*|\[.+\].*)/

(.*) First capture group will capture starting group ("3M" in your example)

\sCO\s Then looks for a whitespace followed by CO followed by a whitespace

(".+".* etc.) Second capture group that looks for starting quote or bracket followed by at least one character of anything followed by closing quote, then followed by any number of any character

Why Original Regex Didn't Work

In the original regex, [\(.*\)|\[.*\]|\{.*\}|''.*''|".*"] can be simplified into [''.*''] (for the string you provided). I realize that for other strings, you might want to look for (.*) or [.*] or {.*} or ".*", but for the "3M" string, only the [''.*''] is relevant so we'll just look at this.

So [''.*''] just means: match any character in the list inside [], in any order. In this case, there are three unique characters in the list: ', . and * (although you did repeat ' 3 times).  So it matched the first '. But since this match is outside your capture group (), this first ' is not included in your capture group response.

So the next match with (.*) matches everything else that comes after the first ' and includes them in the second matching group, i.e. A'(MINNESOTA MINING AND MANUFACTURING COMPANY) without the ' in front.

Does that make sense?

Demo

If you wanted to ensure the format includes 'A' or [A] or "A" or {A} or (A), then this is what you want:

let regex = /(.*)\sCO\s?(\(.+\)|".+".*|'.+'.*|{.+}.*|\[.+\].*)/;

[pattern, match1, match2] = "3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY)".match(regex);
console.log(match1 + " CO " + match2);
//3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY)

[pattern, match1, match2] = '3M CO (A)(MINNESOTA MINING AND MANUFACTURING COMPANY)'.match(regex);
console.log(match1 + " CO " + match2);
//3M CO (A)(MINNESOTA MINING AND MANUFACTURING COMPANY)

[pattern, match1, match2] = '3M CO "A"(MINNESOTA MINING AND MANUFACTURING COMPANY)'.match(regex);
console.log(match1 + " CO " + match2);
//3M CO "A"(MINNESOTA MINING AND MANUFACTURING COMPANY)

[pattern, match1, match2] = "3M CO [A](MINNESOTA MINING AND MANUFACTURING COMPANY)".match(regex);
console.log(match1 + " CO " + match2);
//3M CO [A](MINNESOTA MINING AND MANUFACTURING COMPANY)

[pattern, match1, match2] = "3M CO {A}(MINNESOTA MINING AND MANUFACTURING COMPANY)".match(regex);
console.log(match1 + " CO " + match2);
//3M CO {A}(MINNESOTA MINING AND MANUFACTURING COMPANY)


问:
Convert SQL query to use Laravel query builder
I am trying to convert this SQL code to use Laravel's query builder.</p>

```<code>SELECT b.name
FROM brands b
INNER JOIN products p
    ON b.id = p.brand_id
INNER JOIN transaction_sell_lines tr
    ON p.brand_id=tr.product_id
</code>```

答:
Use the query,</p>

```<code>$res=DB::table('products')
    ->select('brands.name')
    ->join('brands','brands.id','=','products.brand_id')
    ->join('transaction_sell_lines','products.brand_id','=','transaction_sell_lines.product_id')
    ->get();
</code>```

Body:
I am trying to convert this SQL code to use Laravel's query builder.

SELECT b.name
FROM brands b
INNER JOIN products p
    ON b.id = p.brand_id
INNER JOIN transaction_sell_lines tr
    ON p.brand_id=tr.product_id

Body:
Use the query,

$res=DB::table('products')
    ->select('brands.name')
    ->join('brands','brands.id','=','products.brand_id')
    ->join('transaction_sell_lines','products.brand_id','=','transaction_sell_lines.product_id')
    ->get();


问:
How to pass text value to action parameter?
i need to pass input value to action method in controller

i have text and button , so I need to click on the button and take the value of input to parameter and re back to the same view but in post status

i tried many things but not works

i tried to create post form and the type of button is submit but does not work

this is my view code

```<code><form method="post">
    <input  type="text" id="Comments" , name="ID" value="" />
    <button type="submit">Go</button>

</form>
</code>```

this is my controller code

```<code> public ActionResult Index()
        {
            Entities db = new Entities();
            var Query = from acc in db.tbl_Accounts
                        select acc ;

            var accList= Query.ToList<tbl_Accounts>();
            return View(accList);

        }
        [HttpPost]
        public ActionResult Index(int ID)
        {
            Entities db = new Entities();
            var Query = from Acc in db.tbl_Accounts
                        where Acc.id== ID
                        select Acc ;

            var accList= Query.ToList<tbl_Accounts>();
            return View(accList);

        }
</code>```

答:
There is a few typo mistakes in your code, if you correct it as following then it will work as expected:

```<code><form method="post">
    <input type="text" id="Comments" name="ID" />
    <button type="submit">Go</button>
</form>
</code>```

So now check only the parameter value, if it is there:

```<code>[HttpPost]
public ActionResult Index(int ID)
{//Put a breakpoint here and check if ID has value

   return View();
}
</code>```

If the value exists there, than assume that it is okay.

Here is a screenshot that I have tested this answer.

Body:
i need to pass input value to action method in controller

i have text and button , so I need to click on the button and take the value of input to parameter and re back to the same view but in post status

i tried many things but not works

i tried to create post form and the type of button is submit but does not work

this is my view code

<form method="post">
    <input  type="text" id="Comments" , name="ID" value="" />
    <button type="submit">Go</button>

</form>

this is my controller code

 public ActionResult Index()
        {
            Entities db = new Entities();
            var Query = from acc in db.tbl_Accounts
                        select acc ;

            var accList= Query.ToList<tbl_Accounts>();
            return View(accList);

        }
        [HttpPost]
        public ActionResult Index(int ID)
        {
            Entities db = new Entities();
            var Query = from Acc in db.tbl_Accounts
                        where Acc.id== ID
                        select Acc ;

            var accList= Query.ToList<tbl_Accounts>();
            return View(accList);

        }

Body:
There is a few typo mistakes in your code, if you correct it as following then it will work as expected:

<form method="post">
    <input type="text" id="Comments" name="ID" />
    <button type="submit">Go</button>
</form>

So now check only the parameter value, if it is there:

[HttpPost]
public ActionResult Index(int ID)
{//Put a breakpoint here and check if ID has value

   return View();
}

If the value exists there, than assume that it is okay.

Here is a screenshot that I have tested this answer.


问:
excel chart date displaying in daily instead of weekly
I have 2 sets of date to display on my excel histogram chart. However the dates which are on the x-axis will tend to display dates in daily sequence - even though i only have data on a weekly basis. How do i remove the dates that are irrelevant here?</p>

答:
Change the axis from "Automatic" or "Date" or "Time" to "Text" or "Category" (nomenclature varies with Excel version).

In Excel 2007 or 2010 it's on the main screen of the Format Axis dialog. In Excel 2003 and earlier, you need to go to Chart menu > Chart Options > Axes.


问:
Modify DATE in COLUMN using CASES and LOOP
I have One month data.

```<code>DATE       | AMOUNT
04/01/2019 | 3437824
04/02/2019 | 234834
04/03/2019 | 2343478
.
.
.
04/30/2019 | 343729
</code>```

I want to change the Date Column to give me something like this

```<code>OLDDATE    | DATE       | AMOUNT
04/01/2019 | 01/01/2019 | 3437824
04/02/2019 | 02/01/2019 | 234834
04/03/2019 | 03/01/2019 | 2343478
.
.
.
04/12/2019 | 12/01/2019 | 328456
04/13/2019 | 01/02/2019 |845754
04/14/2019 | 02/02/2019 |845754
.
.
04/24/2019 | 12/02/2019 |845754
04/25/2019 | 01/03/2019 |845754
04/26/2019 | 02/03/2019 |845754
.
.
.
04/30/2019 | 06/03/2019 | 343729
</code>```

I tried to achieve the same using a switch case inside a while loop but was not able to get the desired result

```<code>BEGIN
DECLARE @Mth INT = 1;
DECLARE @Iteration INT = 1;

WHILE @Iteration != 1000000
    BEGIN
        WHILE @Mth <= 12
            BEGIN
                UPDATE TACC
                SET BUSINESSDATE =
                CASE
                    WHEN DAY([BUSINESSDATE])<13
                    THEN datefromparts(year([BUSINESSDATE]), @Mth, 1)
                    WHEN DAY([BUSINESSDATE]) BETWEEN 13 AND 24
                    THEN datefromparts(year([BUSINESSDATE]), @Mth, 2)
                    ELSE datefromparts(year([BUSINESSDATE]), @Mth, 3)
                END
                SET @Mth = @Mth + 1
                IF @Mth=13
                    BEGIN
                        SET @Mth=1
                    END
            END
        SET @Iteration = @Iteration + 1
    END
END
</code>```

Which will be the better way to do it T-SQL or DAX if i have to do this for say 10 million rows

Body:
I have One month data.

DATE       | AMOUNT
04/01/2019 | 3437824
04/02/2019 | 234834
04/03/2019 | 2343478
.
.
.
04/30/2019 | 343729

I want to change the Date Column to give me something like this

OLDDATE    | DATE       | AMOUNT
04/01/2019 | 01/01/2019 | 3437824
04/02/2019 | 02/01/2019 | 234834
04/03/2019 | 03/01/2019 | 2343478
.
.
.
04/12/2019 | 12/01/2019 | 328456
04/13/2019 | 01/02/2019 |845754
04/14/2019 | 02/02/2019 |845754
.
.
04/24/2019 | 12/02/2019 |845754
04/25/2019 | 01/03/2019 |845754
04/26/2019 | 02/03/2019 |845754
.
.
.
04/30/2019 | 06/03/2019 | 343729

I tried to achieve the same using a switch case inside a while loop but was not able to get the desired result

BEGIN
DECLARE @Mth INT = 1;
DECLARE @Iteration INT = 1;

WHILE @Iteration != 1000000
    BEGIN
        WHILE @Mth <= 12
            BEGIN
                UPDATE TACC
                SET BUSINESSDATE =
                CASE
                    WHEN DAY([BUSINESSDATE])<13
                    THEN datefromparts(year([BUSINESSDATE]), @Mth, 1)
                    WHEN DAY([BUSINESSDATE]) BETWEEN 13 AND 24
                    THEN datefromparts(year([BUSINESSDATE]), @Mth, 2)
                    ELSE datefromparts(year([BUSINESSDATE]), @Mth, 3)
                END
                SET @Mth = @Mth + 1
                IF @Mth=13
                    BEGIN
                        SET @Mth=1
                    END
            END
        SET @Iteration = @Iteration + 1
    END
END

Which will be the better way to do it T-SQL or DAX if i have to do this for say 10 million rows

Body:
Basically, we need to divide the rows in groups of 12 and for each group to increase the month part of the new date. The rows in the each groups need to be ordered and we need to increase the day part of each new date with one.

You can use ROW_NUMBER to order the rows and divide them in groups. Then you can use DATEADD to built the new date for each row:

DECLARE @DataSource TABLE
(
    [DATE] DATETIME2(0)
   ,[AMOUNT] INT
);

INSERT INTO @DataSource ([DATE], [AMOUNT])
VALUES ('2019-04-01', 100)
      ,('2019-04-02', 100)
      ,('2019-04-03', 100)
      ,('2019-04-04', 100)
      ,('2019-04-05', 100)
      ,('2019-04-06', 100)
      ,('2019-04-07', 100)
      ,('2019-04-08', 100)
      ,('2019-04-09', 100)
      ,('2019-04-10', 100)
      ,('2019-04-11', 100)
      ,('2019-04-12', 100)
      ,('2019-04-13', 100)
      ,('2019-04-14', 100)
      ,('2019-04-15', 100)
      ,('2019-04-16', 100)
      ,('2019-04-17', 100)
      ,('2019-04-18', 100)
      ,('2019-04-19', 100)
      ,('2019-04-20', 100)
      ,('2019-04-21', 100)
      ,('2019-04-22', 100)
      ,('2019-04-23', 100)
      ,('2019-04-24', 100)
      ,('2019-04-25', 100)
      ,('2019-04-26', 100)
      ,('2019-04-27', 100)
      ,('2019-04-28', 100)
      ,('2019-04-29', 100);

DECLARE @StartDate DATETIME2 = '2019-01-01'
       ,@Step TINYINT = 12;

WITH DataSource ([OLDDATE], [AMOUNT], [AddMonth]) AS
(
    SELECT *
          ,(ROW_NUMBER() OVER (ORDER BY [Date] ASC) -1 ) / 12
    FROM @DataSource
)
SELECT [OLDDATE]
      ,[AMOUNT]
      ,DATEADD(DAY, ROW_NUMBER() OVER (PARTITION BY [AddMonth] ORDER BY [OLDDATE] ASC) - 1, DATEADD(MONTH, [AddMonth], @StartDate))
FROM DataSource;


问:
How to transfer data from one file to another?
I am having two files such as,

employee-rates-controller.ts:

```<code>private load() {

return this.entityService
      .load(this.$scope.projectRevisionUid)
      .then(resp => {
        localStorage.removeItem('employeerates');
        this.$scope.employeeRates = resp.employeeRates;
        return this.refreshCostRate(...resp.employeeRates)
          .then(() =>
            localStorage.setItem(
              'employeerates',
              JSON.stringify(this.$scope.employeeRates)
            )
          )
      .then(() => this.refreshBillRate(...resp.employeeRates))
      .then(() => resp.employeeRates.forEach(erm => this.calculate(erm)))
      .then(() => DatepickerUtil.reinitializeDatepickers(this.$scope));
      })

}
</code>```

And in another file,

getEmployeeRates.ts:

```<code>  const employeerates = JSON.parse(
    localStorage.getItem('employeerates')
  );

  if (employeerates && employeerates.length != null) {
    employeerates.forEach((element: any) => {
      if (
        this.employee.getUid() === element.user.personUid &&
        element.internalRate
      ) {
        this.cost_rate_uom = element.internalRate * this.uom_factor;
        this.cost_rate_per_hour =
          this.cost_rate_uom / this.uom_factor;
        this.cost_rate.setValue(this.ap4_cost_rate_per_hour);
      }
    });
  }
</code>```

Here you can see,

In first ts file,

```<code>localStorage.setItem('employeerates',JSON.stringify(this.$scope.employeeRates))
</code>```

And in second ts file receiving the data,

```<code>const employeerates = JSON.parse(localStorage.getItem('employeerates'));
</code>```

I couldn't not find any problem if i add very few employees but when i keep on adding employee which means storing them into localstorage, i am getting the error at certain point of time when the data size was huge and it blocks the entire process.

The error was,

QuotaExceededError: Failed to execute 'setItem' on 'Storage': Setting
  the value of 'employeerates' exceeded the quota.

So i would like to get some good solution in transferring any large data from one file to another without using the localstorage..

As the application is made in Angularjs and Typescript combination, i couldn't find out right solution as i am new to this scenario.

Edit:

Instead of first TS file, i am also able to get the value in this file.

employeeratemodel.ts:

```<code>export class EmployeeRateModel {
public uid: string;
.
.
.
public internalRate: number; // Getting the value here
}
</code>```

How to fetch this value inside the second ts getEmployeeRates.ts: file..

My try:

```<code>import { EmployeeRateModel } from '../component/employee-rates/model/employee-rate.model';

constructor() {
    const data = new EmployeeRateModel();
    console.log(data) // {}  // Gives empty object.. I need to fetch the internalRate from it..
  }
</code>```

Here if i get the data then it will be ease for me to get the internalRate which is needed for calculation, but as everything returns empty, this also fails for me..

Kindly help me to fix it in appropriate way, stucked for long..

答:
Chrome's Local Storage default size is 10 Mb (https://en.wikipedia.org/wiki/Web_storage), so clearing your chrome's local storage could help you, if your data is larger than the limits, you may need to find alternatives like storing on blob storage and accessing the contents from blob itself.

For the reference, you can handle the error if you want using the code below.

try {
     var counter = 1;
     var stringData = "AddLocalStorageTillItIsFull";
     for (var i = 0; i <= counter; counter + 1) {
         stringData += stringData;
         localStorage.setItem("localStorageData", stringData);
         console.log(stringData);
         console.log(counter);
     }

 }
 catch (e) {
     // When local storage is full, it goes hits this carch block
     console.log("Local Storage is full, Please clear local storage data to add more");
 }```

Body:
I am having two files such as,

employee-rates-controller.ts:

private load() {

return this.entityService
      .load(this.$scope.projectRevisionUid)
      .then(resp => {
        localStorage.removeItem('employeerates');
        this.$scope.employeeRates = resp.employeeRates;
        return this.refreshCostRate(...resp.employeeRates)
          .then(() =>
            localStorage.setItem(
              'employeerates',
              JSON.stringify(this.$scope.employeeRates)
            )
          )
      .then(() => this.refreshBillRate(...resp.employeeRates))
      .then(() => resp.employeeRates.forEach(erm => this.calculate(erm)))
      .then(() => DatepickerUtil.reinitializeDatepickers(this.$scope));
      })

}

And in another file,

getEmployeeRates.ts:

  const employeerates = JSON.parse(
    localStorage.getItem('employeerates')
  );

  if (employeerates && employeerates.length != null) {
    employeerates.forEach((element: any) => {
      if (
        this.employee.getUid() === element.user.personUid &&
        element.internalRate
      ) {
        this.cost_rate_uom = element.internalRate * this.uom_factor;
        this.cost_rate_per_hour =
          this.cost_rate_uom / this.uom_factor;
        this.cost_rate.setValue(this.ap4_cost_rate_per_hour);
      }
    });
  }

Here you can see,

In first ts file,

localStorage.setItem('employeerates',JSON.stringify(this.$scope.employeeRates))

And in second ts file receiving the data,

const employeerates = JSON.parse(localStorage.getItem('employeerates'));

I couldn't not find any problem if i add very few employees but when i keep on adding employee which means storing them into localstorage, i am getting the error at certain point of time when the data size was huge and it blocks the entire process.

The error was,

QuotaExceededError: Failed to execute 'setItem' on 'Storage': Setting
  the value of 'employeerates' exceeded the quota.

So i would like to get some good solution in transferring any large data from one file to another without using the localstorage..

As the application is made in Angularjs and Typescript combination, i couldn't find out right solution as i am new to this scenario.

Edit:

Instead of first TS file, i am also able to get the value in this file.

employeeratemodel.ts:

export class EmployeeRateModel {
public uid: string;
.
.
.
public internalRate: number; // Getting the value here
}

How to fetch this value inside the second ts getEmployeeRates.ts: file..

My try:

import { EmployeeRateModel } from '../component/employee-rates/model/employee-rate.model';

constructor() {
    const data = new EmployeeRateModel();
    console.log(data) // {}  // Gives empty object.. I need to fetch the internalRate from it..
  }

Here if i get the data then it will be ease for me to get the internalRate which is needed for calculation, but as everything returns empty, this also fails for me..

Kindly help me to fix it in appropriate way, stucked for long..


问:
Beginner - How can a Node_module access a local config file?
I am making adjustments to a node module, which will be used across many repos in my application. This module manipulates and prints a list of messages which are stored in a simple array of strings. I would like each repo to be able to use this module to print that list of "universal" messages, but, if they so choose, they can also use this module to print off additional strings defined locally (maybe in a config file?). I don't know in general how a module is able to access a local file - and I'm not sure what question to ask google.</p>

答:
If you just want to know how to read from the filesystem, the node module fs should do the trick. There is documentation how to use it below the table of contents.

As an alternative, require() will read and parse JSON so you could simply store your config as a JSON file in the project and require it.


问:
Issues in generating Mongo query using Morphia with nested $and and $or criteria
Need to construct a Mongo query dynamically based on expression pattern. But noticed that Morphia query built is producing wrong results even with hardcoded criteria

Created a BasicDAO with morphia-1.3.2.jar.
Created a Unit test with System.out.println constructing a query with the criteria expected.

```<code>System.out.println("Test Query" +

    ((CriteriaContainerImpl) query1.and(
                                    query1.or(
                                                 query1.criteria("_id").equal("234"), query1.criteria("_id").equal("456")
                                              ),
                                    query1.and(
                                                query1.or(
                                                            query1.criteria("_id").equal("789"), query1.criteria("_id").equal("666")
                                                           ),
                                                query1.criteria("_id").equal("459")
                                                )
                                        )
                            )
                        .getQuery().toString());
</code>```

Actual Result:

```<code>{ query: { "_id" : "459", "$or" : [{ "_id" : "789" }, { "_id" : "666" }] }  }
</code>```

This is the result produced as part of above print statement.

Expected Result:

```<code>{query:
{ "$and":[
            { "$or" : [{ "_id" : "234" }, { "_id" : "456" }] } ,
            {"$and":[
                { "$or" : [{ "_id" : "789" }, { "_id" : "666" }] },
                {"_id":459}
                    ]
            }     ] }}
</code>```

答:
upgrading to morphia 1.5.0 or above is resolving this issue. Got the solution from Morphia forum.
https://github.com/MorphiaOrg/morphia/issues/1278  </p>

Body:
Need to construct a Mongo query dynamically based on expression pattern. But noticed that Morphia query built is producing wrong results even with hardcoded criteria

Created a BasicDAO with morphia-1.3.2.jar.
Created a Unit test with System.out.println constructing a query with the criteria expected.

System.out.println("Test Query" +

    ((CriteriaContainerImpl) query1.and(
                                    query1.or(
                                                 query1.criteria("_id").equal("234"), query1.criteria("_id").equal("456")
                                              ),
                                    query1.and(
                                                query1.or(
                                                            query1.criteria("_id").equal("789"), query1.criteria("_id").equal("666")
                                                           ),
                                                query1.criteria("_id").equal("459")
                                                )
                                        )
                            )
                        .getQuery().toString());

Actual Result:

{ query: { "_id" : "459", "$or" : [{ "_id" : "789" }, { "_id" : "666" }] }  }

This is the result produced as part of above print statement.

Expected Result:

{query:
{ "$and":[
            { "$or" : [{ "_id" : "234" }, { "_id" : "456" }] } ,
            {"$and":[
                { "$or" : [{ "_id" : "789" }, { "_id" : "666" }] },
                {"_id":459}
                    ]
            }     ] }}


问:
sql query related issue
I have one more question in want to the user between the operator in php. This is my SQL query.

```<code>$results=$wpdb->get_results( "SELECT user_id,day,activity,hotel
FROM wp_user_activity
WHERE user_id = '$user_id' AND date BETWEEN $start AND $end ");
</code>```

it gives me an error

```<code>$results=$wpdb->get_results( "SELECT user_id,day,activity,hotel
FROM wp_user_activity
WHERE user_id = '$user_id' AND date BETWEEN '26/05/2019' AND '31/05/2019' ");
</code>```

am getting data in this why in the $start and $end am not getting any data

答:
try the following to see your SQL then review :

$sql = "SELECT user_id,day,activity,hotel FROM wp_user_activity WHERE user_id = '$user_id' AND date BETWEEN $start AND $end ";

echo $sql;
exit;

Title: sql query related issue

Body:
I have one more question in want to the user between the operator in php. This is my SQL query.

$results=$wpdb->get_results( "SELECT user_id,day,activity,hotel
FROM wp_user_activity
WHERE user_id = '$user_id' AND date BETWEEN $start AND $end ");

it gives me an error

$results=$wpdb->get_results( "SELECT user_id,day,activity,hotel
FROM wp_user_activity
WHERE user_id = '$user_id' AND date BETWEEN '26/05/2019' AND '31/05/2019' ");

am getting data in this why in the $start and $end am not getting any data


问:
How to update a scatter plot in PyQt via a callback?
I have this program, that upon user's click on a button, I want to update the previously drawn plot with the new data given by the user. What I'm trying to do is to show a user is a plot of the decision boundary of a classifier system, and when the user adds new data, I want to update my scatter plot accordingly. Here's my code:

```<code>from matplotlib.backends.backend_qt5agg import (
    FigureCanvasQTAgg,
    FigureManagerQT,
)
from PyQt5 import QtWidgets
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import numpy as np
class CustomFigureCanvas(FigureCanvasQTAgg):
    def __init__(self, parent=None, cmap_name="coolwarm"):
        fig = Figure()
        self.color_map = plt.get_cmap(cmap_name)
        self.axes = fig.add_subplot(111)
        super().__init__(fig)
        self.setParent(parent)
        self.setBaseSize(300, 300)
        self.setMaximumSize(400, 400)
        self.setMinimumSize(250, 250)
        self.setSizePolicy(
            QtWidgets.QSizePolicy.MinimumExpanding,
            QtWidgets.QSizePolicy.MinimumExpanding,
        )

    def set_clf_2d(self, clf_2d):
        self.clf = clf_2d

    def plot_new_datapoints(self, x2D):
        self.add_datapoint(x2D)

    @staticmethod
    def _make_meshgrid(x, y, h=0.02):
        x_min, x_max = x.min() - 1, x.max() + 1
        y_min, y_max = y.min() - 1, y.max() + 1
        XX, YY = np.meshgrid(
            np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)
        )
        return XX, YY

    def _plot_contours(self, xx, yy, **params):
        """Plot the decision boundaries for a classifier.

        Parameters
        ----------
        ax: matplotlib axes object
        clf: a classifier
        xx: meshgrid ndarray
        yy: meshgrid ndarray
        params: dictionary of params to pass to contourf, optional
        """
        Z = self.clf.predict(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        self.axes.contourf(xx, yy, Z, **params)

    def plot_data(self, x2D, y):
        """plots the given array and the decision function bounday.

        Arguments:
            x2D {np.array} -- [2d array]
            y {np.array} -- [1d array]
        """

        x0, x1 = x2D[:, 0], x2D[:, 1]
        xx, yy = CustomFigureCanvas._make_meshgrid(x0, x1)
        labels = ["Cognitive", "Not Cognitive"]
        colors = ["r", "b"]
        self.axes.clear()
        self._plot_contours(xx, yy, cmap=self.color_map, alpha=0.8)
        target_ids = [0, 1]

        for i, c, label in zip(target_ids, colors, labels):
            print(i, label)
            self.axes.scatter(
                x0[y == i],
                x1[y == i],
                color=c,
                label=label,
                marker="o",
                s=(15, 15),
            )

        self.axes.set_xlim(xx.min(), xx.max())
        self.axes.set_ylim(yy.min(), yy.max())
        self.axes.set_title("2D Representation using PCA")
        self.axes.legend(fontsize=8)
        self.axes.plot()

    def add_datapoint(self, x2d):
        """Adds a new datapoint to the plot

        Arguments:
            x2d {a 2d single point, [x,y]} -- [np.array with shape (1,2)]
            axes {plt.axes} -- [description]

        """
        print(x2d, type(x2d))
        self.axes.scatter(
            x2d[:, 0],
            x2d[:, 1],
            color="k",
            label="Current Text",
            marker="o",
            s=(15, 15),
        )
        self.axes.legend(fontsize=8)
        self.axes.plot()
</code>```

The problem I'm currently having is that, after the call of _plot_contours, the plot won't be updated. After reading about "update able" figures in matplotlib, I saw a few suggesting using plt.ion() for generating update-able figures. There also been some suggestion about using FuncAnimation class, but this is not exactly the solution that I need, since it doesn't rely on user's button clicked callback, and instead refreshes the plot in a given interval.

EDIT: This a minimal code that reproduces the problem I'm having:

```<code>import sys
from PyQt5 import QtWidgets

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import (
    NavigationToolbar2QT as NavigationToolbar,
)
from matplotlib.figure import Figure
from custom_figure_canvas import CustomFigureCanvas

import random
import numpy as np
from sklearn.svm import SVC

class Window(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = CustomFigureCanvas(parent=self)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QtWidgets.QPushButton("Plot")
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):

        x2D = np.random.rand(50, 2)
        y = np.random.randint(0, 2, size=(50,))

        x2D_train = np.random.rand(50, 2)
        y_train = np.random.randint(0, 2, size=(50,))

        clf = SVC()
        clf.fit(x2D_train, y_train)

        print(x2D)
        self.canvas.set_clf_2d(clf)
        self.canvas.plot_data(x2D, y)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())
</code>```

答:
In the case of matplotlib with Qt you must refresh the painting, for this you can use the following methods:

self.axes.figure.canvas.draw_idle()
```

<p>Or</p>

<pre class="lang-py prettyprint-override"><code>self.axes.figure.canvas.draw()
</code>```

In your case:

# ...

def _plot_contours(self, xx, yy, **params):
    # ...
    self.axes.contourf(xx, yy, Z, **params)
    self.axes.figure.canvas.draw()

def plot_data(self, x2D, y):
    # ...
    self.axes.plot()
    self.axes.figure.canvas.draw()

# ...
```

Output:

Body:
I have this program, that upon user's click on a button, I want to update the previously drawn plot with the new data given by the user. What I'm trying to do is to show a user is a plot of the decision boundary of a classifier system, and when the user adds new data, I want to update my scatter plot accordingly. Here's my code:

from matplotlib.backends.backend_qt5agg import (
    FigureCanvasQTAgg,
    FigureManagerQT,
)
from PyQt5 import QtWidgets
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import numpy as np
class CustomFigureCanvas(FigureCanvasQTAgg):
    def __init__(self, parent=None, cmap_name="coolwarm"):
        fig = Figure()
        self.color_map = plt.get_cmap(cmap_name)
        self.axes = fig.add_subplot(111)
        super().__init__(fig)
        self.setParent(parent)
        self.setBaseSize(300, 300)
        self.setMaximumSize(400, 400)
        self.setMinimumSize(250, 250)
        self.setSizePolicy(
            QtWidgets.QSizePolicy.MinimumExpanding,
            QtWidgets.QSizePolicy.MinimumExpanding,
        )

    def set_clf_2d(self, clf_2d):
        self.clf = clf_2d

    def plot_new_datapoints(self, x2D):
        self.add_datapoint(x2D)

    @staticmethod
    def _make_meshgrid(x, y, h=0.02):
        x_min, x_max = x.min() - 1, x.max() + 1
        y_min, y_max = y.min() - 1, y.max() + 1
        XX, YY = np.meshgrid(
            np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)
        )
        return XX, YY

    def _plot_contours(self, xx, yy, **params):
        """Plot the decision boundaries for a classifier.

        Parameters
        ----------
        ax: matplotlib axes object
        clf: a classifier
        xx: meshgrid ndarray
        yy: meshgrid ndarray
        params: dictionary of params to pass to contourf, optional
        """
        Z = self.clf.predict(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        self.axes.contourf(xx, yy, Z, **params)

    def plot_data(self, x2D, y):
        """plots the given array and the decision function bounday.

        Arguments:
            x2D {np.array} -- [2d array]
            y {np.array} -- [1d array]
        """

        x0, x1 = x2D[:, 0], x2D[:, 1]
        xx, yy = CustomFigureCanvas._make_meshgrid(x0, x1)
        labels = ["Cognitive", "Not Cognitive"]
        colors = ["r", "b"]
        self.axes.clear()
        self._plot_contours(xx, yy, cmap=self.color_map, alpha=0.8)
        target_ids = [0, 1]

        for i, c, label in zip(target_ids, colors, labels):
            print(i, label)
            self.axes.scatter(
                x0[y == i],
                x1[y == i],
                color=c,
                label=label,
                marker="o",
                s=(15, 15),
            )

        self.axes.set_xlim(xx.min(), xx.max())
        self.axes.set_ylim(yy.min(), yy.max())
        self.axes.set_title("2D Representation using PCA")
        self.axes.legend(fontsize=8)
        self.axes.plot()

    def add_datapoint(self, x2d):
        """Adds a new datapoint to the plot

        Arguments:
            x2d {a 2d single point, [x,y]} -- [np.array with shape (1,2)]
            axes {plt.axes} -- [description]

        """
        print(x2d, type(x2d))
        self.axes.scatter(
            x2d[:, 0],
            x2d[:, 1],
            color="k",
            label="Current Text",
            marker="o",
            s=(15, 15),
        )
        self.axes.legend(fontsize=8)
        self.axes.plot()

The problem I'm currently having is that, after the call of _plot_contours, the plot won't be updated. After reading about "update able" figures in matplotlib, I saw a few suggesting using plt.ion() for generating update-able figures. There also been some suggestion about using FuncAnimation class, but this is not exactly the solution that I need, since it doesn't rely on user's button clicked callback, and instead refreshes the plot in a given interval.

EDIT: This a minimal code that reproduces the problem I'm having:

import sys
from PyQt5 import QtWidgets

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import (
    NavigationToolbar2QT as NavigationToolbar,
)
from matplotlib.figure import Figure
from custom_figure_canvas import CustomFigureCanvas

import random
import numpy as np
from sklearn.svm import SVC

class Window(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = CustomFigureCanvas(parent=self)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QtWidgets.QPushButton("Plot")
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):

        x2D = np.random.rand(50, 2)
        y = np.random.randint(0, 2, size=(50,))

        x2D_train = np.random.rand(50, 2)
        y_train = np.random.randint(0, 2, size=(50,))

        clf = SVC()
        clf.fit(x2D_train, y_train)

        print(x2D)
        self.canvas.set_clf_2d(clf)
        self.canvas.plot_data(x2D, y)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

Body:
In the case of matplotlib with Qt you must refresh the painting, for this you can use the following methods:

self.axes.figure.canvas.draw_idle()

Or

self.axes.figure.canvas.draw()

In your case:

# ...

def _plot_contours(self, xx, yy, **params):
    # ...
    self.axes.contourf(xx, yy, Z, **params)
    self.axes.figure.canvas.draw()

def plot_data(self, x2D, y):
    # ...
    self.axes.plot()
    self.axes.figure.canvas.draw()

# ...

Output:


问:
SQL: Dupe check using multiple columns
I have to make a:

```<code>INSERT INTO aaa(DateFrom, DateTo)
SELECT DateFrom, DateTo FROM bbb
</code>```

but sometimes this date interval already exists in aaa

How should I add the WHERE to the SELECT, to not insert in aaa if that date interval already exists

My problem is this: if I add something like:

```<code>WHERE bbb.DateFrom NOT IN aaa.DateFrom AND bbb.DateTo NOT IN aaa.DateTo
</code>```

this will not check for both dates (interval), but either "From" or "To" dates

答:
Your insert is fine,

INSERT INTO @aaa(DateFrom, DateTo)
  SELECT b.DateFrom, b.DateTo  FROM @bbb
  b

You need to get rid of your existing WHERE clause and perform a LEFT JOIN instead.

LEFT JOIN @aaa a ON a.DateFrom =
  b.DateFrom AND a.DateTo = b.DateTo

You can then combine this with a new WHERE clause to test for the absence of entries in the second table:

WHERE ISNULL(a.DateFrom,'') = ''

And voila you have your query!

Fully worked example below:

DECLARE @aaa TABLE  (   DateFrom
  datetime, DateTo datetime )

INSERT INTO @aaa(DateFrom, DateTo)
  VALUES('01 Jan 2011','31 Jan 2011')
  INSERT INTO @aaa(DateFrom, DateTo)
  VALUES('01 Mar 2011','15 Mar 2011')

SELECT * FROM @aaa

DECLARE @bbb TABLE  (   DateFrom
  datetime, DateTo datetime )

INSERT INTO @bbb(DateFrom, DateTo)
  VALUES('01 Jan 2011','31 Jan 2011')
  INSERT INTO @bbb(DateFrom, DateTo)
  VALUES('01 Mar 2011','16 Mar 2011')
  INSERT INTO @bbb(DateFrom, DateTo)
  VALUES('01 Feb 2011','3 Jun 2011')

SELECT * FROM @bbb

INSERT INTO @aaa(DateFrom, DateTo)
  SELECT b.DateFrom, b.DateTo  FROM @bbb
  b LEFT JOIN @aaa a ON a.DateFrom =
  b.DateFrom AND a.DateTo = b.DateTo
  WHERE ISNULL(a.DateFrom,'') = ''

SELECT * FROM @aaa

Title: SQL: Dupe check using multiple columns

Body:
I have to make a:

INSERT INTO aaa(DateFrom, DateTo)
SELECT DateFrom, DateTo FROM bbb

but sometimes this date interval already exists in aaa

How should I add the WHERE to the SELECT, to not insert in aaa if that date interval already exists

My problem is this: if I add something like:

WHERE bbb.DateFrom NOT IN aaa.DateFrom AND bbb.DateTo NOT IN aaa.DateTo

this will not check for both dates (interval), but either "From" or "To" dates


问:
How to pass both object and hashmap to model attribute in spring MVC so i can use them at the same time?
I am trying to create an "add Employee form" with basic attributes like name gender email etc which users can fill in

in the form, there will be a  drop down options for departments available where the list will be pre-populated by a linkedhashmap that will be sent over from the controller

I have already added an attribute object type "Employee" onto my model so when i fill in the form

and return to controller, the employee object will be set automatically

Controller.java

```<code>@GetMapping("/showFormForAdd")

public String showFormForAdd(Model theModel) {

    //fetch new list(if any) of departments added
    List<Department> theDepartments = departmentService.getDepartments();

    //Create a linkedhash map to hold our department_id-department name information
    final LinkedHashMap<Integer, String> departmentOptions = departmentService.generateDepartmentOptions(theDepartments);

    // create new employee object and attach to our model atrribute.

            //how to add multiple objects?? doing this so i can pre-populate available departments for selection
    theModel.addAttribute("employee", departmentOptions);

    Employee theEmployee = new Employee();
            //how to add multiple objects?? doing this so when program return control to controller it will help me set the attribute of employees so I can save it into the database
    theModel.addAttribute("employee", theEmployee);

    return "customer-form";
}
</code>```

The problem:
How do i add multiple attributes for example, the employee object and the linkedhashmap onto my model so I can prepopulate the selection box and at the same time have methods available for my controller to set attributes for my employee object and save into my database when I return control to the controller?

any help will be appreciated..thanks!

EDIT:
just an update, every answer provided works..i was getting mixed up.

答:
If I got it correct(from your code's comment)

//how to add multiple objects?? doing this so i can pre-populate
  available departments for selection

You have to simply set different name for each object in your modelAttribute. In your code, you used same name twice, so the departmentOptions employee object  will be replaced by the later employee object. To overcome this, just set their unique name and you can send list of objects or different single type object like:

//adding multiple object to modelAttribute.

```<code>theModel.addAttribute("departmentOptions", departmentOptions);
Employee theEmployee = new Employee();
theModel.addAttribute("employee", theEmployee);
-----
theModel.addAttribute("anotherObject", anotherObject);
</code>```

Body:
I am trying to create an "add Employee form" with basic attributes like name gender email etc which users can fill in

in the form, there will be a  drop down options for departments available where the list will be pre-populated by a linkedhashmap that will be sent over from the controller

I have already added an attribute object type "Employee" onto my model so when i fill in the form

and return to controller, the employee object will be set automatically

Controller.java

@GetMapping("/showFormForAdd")

public String showFormForAdd(Model theModel) {

    //fetch new list(if any) of departments added
    List<Department> theDepartments = departmentService.getDepartments();

    //Create a linkedhash map to hold our department_id-department name information
    final LinkedHashMap<Integer, String> departmentOptions = departmentService.generateDepartmentOptions(theDepartments);

    // create new employee object and attach to our model atrribute.

            //how to add multiple objects?? doing this so i can pre-populate available departments for selection
    theModel.addAttribute("employee", departmentOptions);

    Employee theEmployee = new Employee();
            //how to add multiple objects?? doing this so when program return control to controller it will help me set the attribute of employees so I can save it into the database
    theModel.addAttribute("employee", theEmployee);

    return "customer-form";
}

The problem:
How do i add multiple attributes for example, the employee object and the linkedhashmap onto my model so I can prepopulate the selection box and at the same time have methods available for my controller to set attributes for my employee object and save into my database when I return control to the controller?

any help will be appreciated..thanks!

EDIT:
just an update, every answer provided works..i was getting mixed up.

Body:
If I got it correct(from your code's comment)

//how to add multiple objects?? doing this so i can pre-populate
  available departments for selection

You have to simply set different name for each object in your modelAttribute. In your code, you used same name twice, so the departmentOptions employee object  will be replaced by the later employee object. To overcome this, just set their unique name and you can send list of objects or different single type object like:

//adding multiple object to modelAttribute.

theModel.addAttribute("departmentOptions", departmentOptions);
Employee theEmployee = new Employee();
theModel.addAttribute("employee", theEmployee);
-----
theModel.addAttribute("anotherObject", anotherObject);


问:
Efficient method to append only the new rows from pandas dataframe to a table in database
Suppose I have a table X in MySQL as follows

```<code>A   B
1   2
3   4
5   6
</code>```

and I have a dataframe df as follows

```<code>A   B
1   2
5   6
7   8
9  10
</code>```

I want to append to X only new rows from df (rows that are in df but not in X).  The results should be:

```<code>A   B
1   2
3   4
5   6
7   8
9  10
</code>```

Note that sorting does not matter for me.  Currently, what I can do are

```<code>1. Read table X and store in a dataframe called dfx
2. Concat df and dfx
3. Drop duplicate rows
4. Insert the results back to the table X with to_sql(if_exist='replace')
</code>```

However, I think this is not a good practice particularly when the table X is very large.  May I have your suggestions for the better way?  Thank you

答: If you have a unique index in your table that would prevent you to insert duplicate records (the primary key should do the job), then using INSERT IGNOREinstead of INSERT will be enough: duplicate records will be silently discarded instead of generating an error.

Body:
Suppose I have a table X in MySQL as follows

A   B
1   2
3   4
5   6

and I have a dataframe df as follows

A   B
1   2
5   6
7   8
9  10

I want to append to X only new rows from df (rows that are in df but not in X).  The results should be:

A   B
1   2
3   4
5   6
7   8
9  10

Note that sorting does not matter for me.  Currently, what I can do are

1. Read table X and store in a dataframe called dfx
2. Concat df and dfx
3. Drop duplicate rows
4. Insert the results back to the table X with to_sql(if_exist='replace')

However, I think this is not a good practice particularly when the table X is very large.  May I have your suggestions for the better way?  Thank you


问:
Distinct Column Selection using Spring JPA Specifications and Pagination gives InvalidDataAccessApiUsageException
I am trying to filter results from a table based on a bunch of query parameters I receive using Spring Data JPA Specifications. I need to get results of Distinct Column which is of type UUID. All the other query params I need to query by are of type String.

So the repository method I try is findDistinctByTransactionId(Specficiation<T> spec, Pageable page)

I expect the result to be of type Page<UUID>. But I get an exception. The error message is :

```<code>org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [org.springframework.data.jpa.domain.Specifications@7c900524] did not match expected type [java.util.UUID (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [org.springframework.data.jpa.domain.Specifications@7c900524] did not match expected type [java.util.UUID (n/a)]
</code>```

So the problem here is the way to let the JPA know that the Distinct Column we are looking for is of type UUID.

答:
The problem is that you are trying to combine two distinct feature of Spring Data JPA: Specifications and Query Derivation. This does not work.

What you should do is create a custom method implementation of your method which constructs a query using the JPA Criteria API and then adds the predicate you pass in as an argument.

Body:
I am trying to filter results from a table based on a bunch of query parameters I receive using Spring Data JPA Specifications. I need to get results of Distinct Column which is of type UUID. All the other query params I need to query by are of type String.

So the repository method I try is findDistinctByTransactionId(Specficiation<T> spec, Pageable page)

I expect the result to be of type Page<UUID>. But I get an exception. The error message is :

org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [org.springframework.data.jpa.domain.Specifications@7c900524] did not match expected type [java.util.UUID (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [org.springframework.data.jpa.domain.Specifications@7c900524] did not match expected type [java.util.UUID (n/a)]

So the problem here is the way to let the JPA know that the Distinct Column we are looking for is of type UUID.


问:
Encrypted in Node using AES/CBC/NOPADDING and decrypted in JAVA using same algorithm gives some junk like e�J�,�d�|*�5Ҝ��
I have to decrypt some text which is encrypted in Node using AES/CBC/NOPADDING algorithm but end up getting some garbage value when decrypted in JAVA .. Please help...

Node Encryption code:

```<code>const iv = "0123456789012345";
ALGORITHM : 'aes-256-cbc',
ACCESS_CODE : MD5('Imgine#123$')

function encrypt(text) {
 var cipher      = crypto.createCipheriv(algorithm, key, iv);
 var encrypted   = cipher.update(text, "utf8", "base64");
 encrypted       += cipher.final("base64"); // to hex

 return encrypted;
}
</code>```

Java Decryption code:

```<code>private static final Charset UTF8 = Charset.forName("UTF-8");

    public static String decrypt() throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException,
            InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
    {
        String base64Cipher = "t7rCN8nBGlruCiSvpQ9DPg==";
        byte [] iv = "0123456789012345".getBytes(UTF8);
        byte [] secretBytes = "Imgine#123$".getBytes(UTF8);

        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(secretBytes);

        SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
        cipher.init(Cipher.DECRYPT_MODE, skey, new IvParameterSpec(iv));

        return new String(cipher.doFinal(Base64.getDecoder().decode(base64Cipher))) ;
   }
</code>```

Result: e�J�,�d�|*�5Ҝ��

答:
Eventually, I found the root cause, the culprit is converting key to MD5 which doesn't convert as required, the MessageDigest is converting the key to 128 bit, it has to be 256, am using the below method to convert the key as required which worked for me, Thanks for all your valuable inputs.</p>

```<code>public static String getMd5(String input)
{
    try {

        // Static getInstance method is called with hashing MD5
        MessageDigest md = MessageDigest.getInstance("MD5");

        // digest() method is called to calculate message digest
        //  of an input digest() return array of byte
        byte[] messageDigest = md.digest(input.getBytes());

        // Convert byte array into signum representation
        BigInteger no = new BigInteger(1, messageDigest);

        // Convert message digest into hex value
        String hashtext = no.toString(16);
        while (hashtext.length() < 32) {
            hashtext = "0" + hashtext;
        }
        return hashtext;
    }

    // For specifying wrong message digest algorithms
    catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
</code>```

Body:
I have to decrypt some text which is encrypted in Node using AES/CBC/NOPADDING algorithm but end up getting some garbage value when decrypted in JAVA .. Please help...

Node Encryption code:

const iv = "0123456789012345";
ALGORITHM : 'aes-256-cbc',
ACCESS_CODE : MD5('Imgine#123$')

function encrypt(text) {
 var cipher      = crypto.createCipheriv(algorithm, key, iv);
 var encrypted   = cipher.update(text, "utf8", "base64");
 encrypted       += cipher.final("base64"); // to hex

 return encrypted;
}

Java Decryption code:

private static final Charset UTF8 = Charset.forName("UTF-8");

    public static String decrypt() throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException,
            InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
    {
        String base64Cipher = "t7rCN8nBGlruCiSvpQ9DPg==";
        byte [] iv = "0123456789012345".getBytes(UTF8);
        byte [] secretBytes = "Imgine#123$".getBytes(UTF8);

        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(secretBytes);

        SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
        cipher.init(Cipher.DECRYPT_MODE, skey, new IvParameterSpec(iv));

        return new String(cipher.doFinal(Base64.getDecoder().decode(base64Cipher))) ;
   }

Result: e�J�,�d�|*�5Ҝ��

Body:
Eventually, I found the root cause, the culprit is converting key to MD5 which doesn't convert as required, the MessageDigest is converting the key to 128 bit, it has to be 256, am using the below method to convert the key as required which worked for me, Thanks for all your valuable inputs.

public static String getMd5(String input)
{
    try {

        // Static getInstance method is called with hashing MD5
        MessageDigest md = MessageDigest.getInstance("MD5");

        // digest() method is called to calculate message digest
        //  of an input digest() return array of byte
        byte[] messageDigest = md.digest(input.getBytes());

        // Convert byte array into signum representation
        BigInteger no = new BigInteger(1, messageDigest);

        // Convert message digest into hex value
        String hashtext = no.toString(16);
        while (hashtext.length() < 32) {
            hashtext = "0" + hashtext;
        }
        return hashtext;
    }

    // For specifying wrong message digest algorithms
    catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}


问:
WPF - Cannot find resource defined in app xaml file
Heyho...

My WPF application has a customized startup to show a custom splash screen and doing some preparation (e.g. parsing arguments, prepare filesystem, ...). For this I override the OnStartup Method.

App.xaml.cs

```<code>public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
      base.OnStartup(e);

      var splash = new SplashWindow();
      splash.Show();

      // do some black magic

      splash.Close();
      var mw = new MainWindow();
      mw.Show();
    }
  }
}
</code>```

App.xaml

```<code><Application x:Class="Example.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1"
             ShutdownMode="OnExplicitShutdown">
    <Application.Resources>
        <ResourceDictionary>
            <Color x:Key="Foo">#FFFFAA00</Color>
            <SolidColorBrush x:Key="Bar" Color="{StaticResource Foo}" />
        </ResourceDictionary>
    </Application.Resources>
</Application>

</code>```

But handling the start up this way I cannot access resources defined in app.xaml i.e., in MainWindow.xaml or Splash.xaml.

Some other had already the same issue, i.e., https://stackoverflow.com/a/13425695

Following the workaround link takes me to this stackoverflow post: https://stackoverflow.com/a/3896209/5663348

The suggested workaround is to define x:Name of the Application element. But how does it help me accessing the defined resource? Unfortunately the link for "more information" is broken (too old)...

Applying the accepted answer of this question does even not solve the problem.

I'm using .Net Framework 7.4.2

Can someone give me some hints, how I can solve this?

Cheers and thanks :)

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

Problem solved...
The real world app had initialized MainWindow and SplashWindow while the App class was instanciated... stupid mistake...

答:
The Problem

SplashWindow and MainWindow tried to access Resources defined in App.xaml.
In App.xaml.cs was some preparation done et al. loading some files. But while App was instancied it already tried to create an instance of SplashWindow and MainWindow

```<code>public partial class App : Application
{
    private readonly SplashWindow splash;

    public App() {
        splash = new SplashWindow();  // this cannot work, if SplashWindow has a reference to a resource defined in App
        this.MainWindow = new MainWindow();  // this cannot work, if MainWindow has a reference to a resource defined in App
    }

    protected override void OnStartup(StartupEventArgs e) {
        base.OnStartup(e);

        var splash = new SplashWindow(); // yes, splash was instancied multiple times...
        splash.Show();

        // do some magic

        splash.Close();
        MainWindow.Show();
    }
}
</code>```

The instanciation of SplashScreen and MainWindow caused the Exception, cause they tried to access resources which are defined in App, but App wasn't finish instanciated, so the Object couldn't be accessed.

While trying to rebuild the error I created a much simpler App, where MainWindow and SplashWindow where instanciated in App.OnStartup(e), but when this Event is called the App object exists, so it can work.

The Solution

Removing the field splash and don't use the constructor to create instances of SplashWindow and MainWindow

```<code>public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e) {
        base.OnStartup(e);

        var splash = new SplashWindow(); // yes, splash was instancied multiple times...
        splash.Show();

        // do some magic

        this.MainWindow = new MainWindow();
        splash.Close();
        MainWindow.Show();
    }
}
</code>```

Thx to all who helped me to find out this mistake...

And a special thanks to @Default, who rembered me to answer this question :)

Body:
Heyho...

My WPF application has a customized startup to show a custom splash screen and doing some preparation (e.g. parsing arguments, prepare filesystem, ...). For this I override the OnStartup Method.

App.xaml.cs

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
      base.OnStartup(e);

      var splash = new SplashWindow();
      splash.Show();

      // do some black magic

      splash.Close();
      var mw = new MainWindow();
      mw.Show();
    }
  }
}

App.xaml

<Application x:Class="Example.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1"
             ShutdownMode="OnExplicitShutdown">
    <Application.Resources>
        <ResourceDictionary>
            <Color x:Key="Foo">#FFFFAA00</Color>
            <SolidColorBrush x:Key="Bar" Color="{StaticResource Foo}" />
        </ResourceDictionary>
    </Application.Resources>
</Application>

But handling the start up this way I cannot access resources defined in app.xaml i.e., in MainWindow.xaml or Splash.xaml.

Some other had already the same issue, i.e., https://stackoverflow.com/a/13425695

Following the workaround link takes me to this stackoverflow post: https://stackoverflow.com/a/3896209/5663348

The suggested workaround is to define x:Name of the Application element. But how does it help me accessing the defined resource? Unfortunately the link for "more information" is broken (too old)...

Applying the accepted answer of this question does even not solve the problem.

I'm using .Net Framework 7.4.2

Can someone give me some hints, how I can solve this?

Cheers and thanks :)

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

Problem solved...
The real world app had initialized MainWindow and SplashWindow while the App class was instanciated... stupid mistake...

Body:
The Problem

SplashWindow and MainWindow tried to access Resources defined in App.xaml.
In App.xaml.cs was some preparation done et al. loading some files. But while App was instancied it already tried to create an instance of SplashWindow and MainWindow

public partial class App : Application
{
    private readonly SplashWindow splash;

    public App() {
        splash = new SplashWindow();  // this cannot work, if SplashWindow has a reference to a resource defined in App
        this.MainWindow = new MainWindow();  // this cannot work, if MainWindow has a reference to a resource defined in App
    }

    protected override void OnStartup(StartupEventArgs e) {
        base.OnStartup(e);

        var splash = new SplashWindow(); // yes, splash was instancied multiple times...
        splash.Show();

        // do some magic

        splash.Close();
        MainWindow.Show();
    }
}

The instanciation of SplashScreen and MainWindow caused the Exception, cause they tried to access resources which are defined in App, but App wasn't finish instanciated, so the Object couldn't be accessed.

While trying to rebuild the error I created a much simpler App, where MainWindow and SplashWindow where instanciated in App.OnStartup(e), but when this Event is called the App object exists, so it can work.

The Solution

Removing the field splash and don't use the constructor to create instances of SplashWindow and MainWindow

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e) {
        base.OnStartup(e);

        var splash = new SplashWindow(); // yes, splash was instancied multiple times...
        splash.Show();

        // do some magic

        this.MainWindow = new MainWindow();
        splash.Close();
        MainWindow.Show();
    }
}

Thx to all who helped me to find out this mistake...

And a special thanks to @Default, who rembered me to answer this question :)


问:
Unable to escape the escape quotes when assigning the string to variable
I have a bash command to run for which I am assigning it to a variable.
The command to be run is:

```<code>papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
</code>```

I am able to print it in python3, as:

```<code>>>> print("papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}'))
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
</code>```

However, when I assign the same value to the variable:

```<code>a= "papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}')
</code>```

I get the following:

```<code>'papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y \'{"aviral":"srivastava"}\''
</code>```

Notice the \ in the output.

I expect to achieve the desired result(which is done in the print statement) using variable assigning.

答:
Look at this,

```<code>>>> print("papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}'))
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
>>> a= "papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}')
</code>```

Here, you are seeing \ because it is printing a string literal in single quotes.

```<code>>>> a
'papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y \'{"aviral":"srivastava"}\''
</code>```

If you print the variable, it will look normal as you required.

```<code>>>> print(a)
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
</code>```

Body:
I have a bash command to run for which I am assigning it to a variable.
The command to be run is:

papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'

I am able to print it in python3, as:

>>> print("papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}'))
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'

However, when I assign the same value to the variable:

a= "papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}')

I get the following:

'papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y \'{"aviral":"srivastava"}\''

Notice the \ in the output.

I expect to achieve the desired result(which is done in the print statement) using variable assigning.

Body:
Look at this,

>>> print("papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}'))
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
>>> a= "papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}')

Here, you are seeing \ because it is printing a string literal in single quotes.

>>> a
'papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y \'{"aviral":"srivastava"}\''

If you print the variable, it will look normal as you required.

>>> print(a)
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'


问:
How to solve ArrayIndexOutOfBoundsException in this code?
I'm just working on a easy easy program with for loop and while loop,
and an ArrayIndexOutOfBoundsException occurred.

Here is my code:

```<code>public class ForWhileLoops
{
   public static void main(String[] args)
   {
     int[] mary = new int[30];

     for(int a = 0; a < 31; a++)
     {
      mary[a]= a*3;
     }
     for(int b = 0; b < 31; b++)
     {
       System.out.println(mary);
     }
     int c = 0;
     while(c < 31)
     {
       c++;
       System.out.println(c);
     }
  }
}
</code>```

And here is the error that occurred:

```<code>java.lang.ArrayIndexOutOfBoundsException: 30
    at ForWhileLoops.main(ForWhileLoops.java:9)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
</code>```

答: there is only 30 space in ArrayList(index 0 to 29). index 31 cannot be created.</p>

Body:
I'm just working on a easy easy program with for loop and while loop,
and an ArrayIndexOutOfBoundsException occurred.

Here is my code:

public class ForWhileLoops
{
   public static void main(String[] args)
   {
     int[] mary = new int[30];

     for(int a = 0; a < 31; a++)
     {
      mary[a]= a*3;
     }
     for(int b = 0; b < 31; b++)
     {
       System.out.println(mary);
     }
     int c = 0;
     while(c < 31)
     {
       c++;
       System.out.println(c);
     }
  }
}

And here is the error that occurred:

java.lang.ArrayIndexOutOfBoundsException: 30
    at ForWhileLoops.main(ForWhileLoops.java:9)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)


问:
Custom ordering by calculation in Django
Any solutions for custom calculation sorting in Django? I want to create a view that shows the Top Posts in my Blog. The ranking will be calculated by Post's attributes. Let's just say I have 3 IntegerFields called x, y, and z, and the ranking calculation will be x * y / z.

Any ideas? I would like to do Top Post ever, and also other variations filtered by time such as last 24 hours, 7 days, 1 month, etc.

Thanks!

答:
You can use extra to retrieve extra calculated column(s) and sort by it:

```<code>MyModel.objects.filter(post_date__lt=#date#)
       .extra(select={'custom_order': "x*y/z"}).order_by('custom_order')
</code>```

The problem with this approach is that you're writing sql so it is not always portable across databases (although, for the example you supplied, this problem is avoided because it's a simple calculation)

Otherwise, you can do the sorting with pure python:

```<code>sorted_models = sorted(MyModel.objects.filter(post_date__lt=#date#)
                , key=lambda my_model:my_model.x*my_model.y/my_model.z))
</code>```

Body:
You can use extra to retrieve extra calculated column(s) and sort by it:

MyModel.objects.filter(post_date__lt=#date#)
       .extra(select={'custom_order': "x*y/z"}).order_by('custom_order')

The problem with this approach is that you're writing sql so it is not always portable across databases (although, for the example you supplied, this problem is avoided because it's a simple calculation)

Otherwise, you can do the sorting with pure python:

sorted_models = sorted(MyModel.objects.filter(post_date__lt=#date#)
                , key=lambda my_model:my_model.x*my_model.y/my_model.z))


问:
How can I use a google classroom API on a website I am making to access specific rosters and put them on a list displayed on the website?
I am making a website for a teacher and he wants to be able to take attendance easily and he wants me to use the google classroom api to access his roster in his class so that it can then display that list of names on the website and he can easily take attendance there</p>

答:
Roster importing is a common use case we see with the Classroom API. Here's what the workflow typically looks like:

On your website, the teacher chooses the option to import a Classroom Course.

On your backend, call the courses.list method through the Classroom API, which will return a json response.

From this json response, list the titles of the teacher's courses for them to select 1. Note: you'll need to keep track of the course IDs to continue onto the next step.

With the course ID, call the students.list method and display all names on your website for teachers to take attendance.

On each of the links above, you can use the API Explorer to see exactly how these methods behave. I also recommend you check the documentation for managing courses and students/teachers -- there are code snippets for a few different languages, including Python.

Hope this helps!