问:
How to maintain state during recursion in python
I am trying to implement a simple min max algorithm for a tic tac toe game in python I have an issue with the following method:

```<code>def get_best_move(self, board, empty_cells, turns, points=None):
        if points is None:
            points = []

#here I loop trough the empty cells on the board and fill it with 'X' or 'O'
        for cell in empty_cells:
            new_board = copy.deepcopy(board)
            new_turns = turns.copy()

            if turns[-1] == 'X':
              new_board[cell[0]][cell[1]] = 'O'
              new_turns.append('O')
            elif turns[-1] == 'O':
              new_board[cell[0]][cell[1]] = 'X'
              new_turns.append('X')

#here i select all the empty cells after a move
            new_empty_cells = [[index1,index2] for index1,value1 in enumerate(new_board) for index2,value2 in enumerate(value1) if value2==' ']

#here I check if there is a winner and append the points list with 1,0,-1 accordingly
            if self.winner(new_board) == 'X':
                return points.append(-1)
            elif self.winner(new_board) == 'O':
                return points.append(1)
            elif len(new_empty_cells) == 0:
                return points.append(0)
            else:
#here I call this method again if there is no winner or the game is not a draw.
                self.get_best_move(new_board, new_empty_cells, new_turns, points)
            return print(points)
</code>```

the method takes the following arguments:

```<code>board = [[' ',' ',' '],
         [' ',' ',' '],
         [' ',' ',' ']]

empty_cells = [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]

turns = ['X']
</code>```

So given a board like this there should be 255168 possible outcomes thus I would expect my points list to contain 255168 values of 1,0,-1 but all I have is this:

```<code>[1]
[1]
[1]
[1]
[1]
[1]
</code>```

Ideally I would like to get a separate list for each cell in the for loop. I have a feeling that I am making some pretty obvious mistake but I just can not spot it, so any help would be greatly appreciated.

答:
As stated in comments, your loop will always exit on its first iteration.

Either an if will lead to a return statement, or there is the catch-all return print(points) at the bottom of your for loop body. So whatever happens, your for loop will execute a return in its first iteration.

This is obviously not the desired behaviour. Move the final return out of the for loop.

Body:
I am trying to implement a simple min max algorithm for a tic tac toe game in python I have an issue with the following method:

def get_best_move(self, board, empty_cells, turns, points=None):
        if points is None:
            points = []

#here I loop trough the empty cells on the board and fill it with 'X' or 'O'
        for cell in empty_cells:
            new_board = copy.deepcopy(board)
            new_turns = turns.copy()

            if turns[-1] == 'X':
              new_board[cell[0]][cell[1]] = 'O'
              new_turns.append('O')
            elif turns[-1] == 'O':
              new_board[cell[0]][cell[1]] = 'X'
              new_turns.append('X')

#here i select all the empty cells after a move
            new_empty_cells = [[index1,index2] for index1,value1 in enumerate(new_board) for index2,value2 in enumerate(value1) if value2==' ']

#here I check if there is a winner and append the points list with 1,0,-1 accordingly
            if self.winner(new_board) == 'X':
                return points.append(-1)
            elif self.winner(new_board) == 'O':
                return points.append(1)
            elif len(new_empty_cells) == 0:
                return points.append(0)
            else:
#here I call this method again if there is no winner or the game is not a draw.
                self.get_best_move(new_board, new_empty_cells, new_turns, points)
            return print(points)

the method takes the following arguments:

board = [[' ',' ',' '],
         [' ',' ',' '],
         [' ',' ',' ']]

empty_cells = [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]

turns = ['X']

So given a board like this there should be 255168 possible outcomes thus I would expect my points list to contain 255168 values of 1,0,-1 but all I have is this:

[1]
[1]
[1]
[1]
[1]
[1]

Ideally I would like to get a separate list for each cell in the for loop. I have a feeling that I am making some pretty obvious mistake but I just can not spot it, so any help would be greatly appreciated.


来源: stackexchange

问:
check or change keyboard typing language from server or client side
how can we check or change keyboard typing language from server or client side ?</p>

答:
To detect the language you can use this Goggle API:

http://code.google.com/apis/language/translate/v1/using_rest_langdetect.html

You will have to send the request from the Server side code as there's no JSONP exposed, they didn't provide ASP.NET sample but translating from PHP to C# should not be difficult.

ContentLicense: CC BY-SA 3.0


问:
How create a user and a profile with a single form in Django?
I have created a Clients model in models.py that is intended to be a Client (user) Profile.

```<code>class Clients(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=30, verbose_name="Primeiro Nome")
    last_name = models.CharField(max_length=30, verbose_name="Apelido")
    address = models.CharField(max_length=200, verbose_name="Morada")
    nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], primary_key=True)
    mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')])
    email = models.CharField(max_length=200, null=True, verbose_name="Email")
    avatar = models.ImageField(null=True)

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

    class Meta:
        verbose_name_plural = "Clientes"

    @receiver(post_save, sender=User)
    def update_user_profile(sender, instance, created, **kwargs):
        if created:
            Clients.objects.create(user=instance)
            instance.profile.save()
</code>```

This model is connected to the Django Users through a OneToOneField called user.

I created a form that is capable of adding data to the Clients model in forms.py:

```<code>from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.core.validators import RegexValidator

class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, label="Primeiro Nome")
    last_name = forms.CharField(max_length=30, label="Apelido")
    address = forms.CharField(max_length=200, label="Morada")
    nif = forms.CharField(max_length=9, label="NIF", validators=[RegexValidator(r'^\d{1,10}$')])
    mobile = forms.CharField(max_length=9, label="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')])
    email = forms.CharField(max_length=200, label="Email")

    class Meta:
        model = User
        fields = ('username', 'password1', 'password2', 'first_name', 'last_name', 'address', 'nif', 'mobile', 'email')
</code>```

How can I, through this single form, add a username and password field so that, through the OneToOneField, it creates an user connected to this profile?

EDIT

The new version of the files above. Now, it creates the user, but all other fields for the Clients get passed empty.

My views.py

```<code>def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()  # load the profile instance created by the signal
            user.first_name = form.cleaned_data.get('first_name')
            user.last_name = form.cleaned_data.get('last_name')
            user.address = form.cleaned_data.get('address')
            user.nif = form.cleaned_data.get('nif')
            user.mobile = form.cleaned_data.get('mobile')
            user.email = form.cleaned_data.get('email')
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            login(request, user)
            return redirect('clientes')
    else:
        form = SignUpForm()
    return render(request, 'backend/new_client.html', {'form': form})
</code>```

答:
The fields you added are just regular form fields, django doesn't know anything about where to save these values. So you need to override the form's save() method or save them in your view. Here's how to save them in your view, since this is what you started to do:

```<code>if form.is_valid():
    user = form.save()  # this creates the user with first_name, email and last_name as well!
    user.refresh_from_db()  # load the profile instance created by the signal
    user.clients.address = form.cleaned_data.get('address')
    user.clients.nif = form.cleaned_data.get('nif')
    user.clients.mobile = form.cleaned_data.get('mobile')
    user.clients.save()
    login(request, user)
    return redirect('clientes')
</code>```

Note: I don't do anything with first_name, last_name and email in the view, they are fields of the User model so they will already be saved automatically when you do form.save(). You should remove them from your Clients model.

Note 2: Renaming your Clients model to Client would make your code more readable. You should always use singular for your models. This way you can do user.client.address which makes more sense than user.clients.address since it's a one-to-one field.

Alternatively, you can override the form's save() method, which is a method I would prefer as I don't think the view should care about how to save the user's profile:

```<code># in SignupForm(UserCreationForm):
def save(self, commit=True):
    user = super().save(commit)  # this creates the new user
    if commit:
        user.refresh_from_db()  # not sure if this is needed
        user.clients.nib = self.cleaned_data.get('nib')
        user.clients.address = self.cleaned_data.get('address')
        user.clients.mobile = self.cleaned_data.get('mobile')
        user.clients.save()
    return user
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have created a Clients model in models.py that is intended to be a Client (user) Profile.

class Clients(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=30, verbose_name="Primeiro Nome")
    last_name = models.CharField(max_length=30, verbose_name="Apelido")
    address = models.CharField(max_length=200, verbose_name="Morada")
    nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], primary_key=True)
    mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')])
    email = models.CharField(max_length=200, null=True, verbose_name="Email")
    avatar = models.ImageField(null=True)

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

    class Meta:
        verbose_name_plural = "Clientes"

    @receiver(post_save, sender=User)
    def update_user_profile(sender, instance, created, **kwargs):
        if created:
            Clients.objects.create(user=instance)
            instance.profile.save()

This model is connected to the Django Users through a OneToOneField called user.

I created a form that is capable of adding data to the Clients model in forms.py:

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.core.validators import RegexValidator

class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, label="Primeiro Nome")
    last_name = forms.CharField(max_length=30, label="Apelido")
    address = forms.CharField(max_length=200, label="Morada")
    nif = forms.CharField(max_length=9, label="NIF", validators=[RegexValidator(r'^\d{1,10}$')])
    mobile = forms.CharField(max_length=9, label="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')])
    email = forms.CharField(max_length=200, label="Email")

    class Meta:
        model = User
        fields = ('username', 'password1', 'password2', 'first_name', 'last_name', 'address', 'nif', 'mobile', 'email')

How can I, through this single form, add a username and password field so that, through the OneToOneField, it creates an user connected to this profile?

EDIT

The new version of the files above. Now, it creates the user, but all other fields for the Clients get passed empty.

My views.py

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()  # load the profile instance created by the signal
            user.first_name = form.cleaned_data.get('first_name')
            user.last_name = form.cleaned_data.get('last_name')
            user.address = form.cleaned_data.get('address')
            user.nif = form.cleaned_data.get('nif')
            user.mobile = form.cleaned_data.get('mobile')
            user.email = form.cleaned_data.get('email')
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            login(request, user)
            return redirect('clientes')
    else:
        form = SignUpForm()
    return render(request, 'backend/new_client.html', {'form': form})

Body:
The fields you added are just regular form fields, django doesn't know anything about where to save these values. So you need to override the form's save() method or save them in your view. Here's how to save them in your view, since this is what you started to do:

if form.is_valid():
    user = form.save()  # this creates the user with first_name, email and last_name as well!
    user.refresh_from_db()  # load the profile instance created by the signal
    user.clients.address = form.cleaned_data.get('address')
    user.clients.nif = form.cleaned_data.get('nif')
    user.clients.mobile = form.cleaned_data.get('mobile')
    user.clients.save()
    login(request, user)
    return redirect('clientes')

Note: I don't do anything with first_name, last_name and email in the view, they are fields of the User model so they will already be saved automatically when you do form.save(). You should remove them from your Clients model.

Note 2: Renaming your Clients model to Client would make your code more readable. You should always use singular for your models. This way you can do user.client.address which makes more sense than user.clients.address since it's a one-to-one field.

Alternatively, you can override the form's save() method, which is a method I would prefer as I don't think the view should care about how to save the user's profile:

# in SignupForm(UserCreationForm):
def save(self, commit=True):
    user = super().save(commit)  # this creates the new user
    if commit:
        user.refresh_from_db()  # not sure if this is needed
        user.clients.nib = self.cleaned_data.get('nib')
        user.clients.address = self.cleaned_data.get('address')
        user.clients.mobile = self.cleaned_data.get('mobile')
        user.clients.save()
    return user


问:
Convert argb to string
Which method allows convert ARGB to string as 'int, int, int'? Example. The $Main background color is set as a string '0, 100, 200'. Return $Main.BackColor gives ARGB but not string '0, 100, 200':

```<code>$Main  = [System.Windows.Forms.Form] @{
    BackColor = '0, 100, 200'
}

$Main.BackColor
--------------
R             : 0
G             : 100
B             : 200
A             : 255
IsKnownColor  : False
IsEmpty       : False
IsNamedColor  : False
IsSystemColor : False
Name          : ff0064c8
</code>```

The To.String() method returns the result Color [A=255, R=0, G=100, B=200]
. This is not what is expected.

At the moment I am doing this:

```<code> ('R', 'G', 'B').ForEach({ $Main.BackColor.$_ }) -join ', '

--------------
0, 100, 200
</code>```

However, I hope that there are special methods for converting as ARGB to string, as string to ARGB. What are these methods? Thanks

答:
Reza Aghaei's helpful answer shows the proper solution and Mathias R. Jessen's excellent answer shows robust alternatives.

Let me complement them with a pragmatic hack; while deriving serializable representations from for-display strings (.ToString()) is generally ill-advised, the format at hand is unlikely to change in a way that will break this:

```<code>PS> $Main.BackColor -replace '[^\d,]'  # remove all chars. except digits and commas
255,0,100,200
</code>```

Note: The above includes the alpha value, unlike the original input string; however, casting back to [System.Drawing.Color] works equally well.

Title: Convert argb to string

Body:
Which method allows convert ARGB to string as 'int, int, int'? Example. The $Main background color is set as a string '0, 100, 200'. Return $Main.BackColor gives ARGB but not string '0, 100, 200':

$Main  = [System.Windows.Forms.Form] @{
    BackColor = '0, 100, 200'
}

$Main.BackColor
--------------
R             : 0
G             : 100
B             : 200
A             : 255
IsKnownColor  : False
IsEmpty       : False
IsNamedColor  : False
IsSystemColor : False
Name          : ff0064c8

The To.String() method returns the result Color [A=255, R=0, G=100, B=200]
. This is not what is expected.

At the moment I am doing this:

 ('R', 'G', 'B').ForEach({ $Main.BackColor.$_ }) -join ', '

--------------
0, 100, 200

However, I hope that there are special methods for converting as ARGB to string, as string to ARGB. What are these methods? Thanks

Body:
Reza Aghaei's helpful answer shows the proper solution and Mathias R. Jessen's excellent answer shows robust alternatives.

Let me complement them with a pragmatic hack; while deriving serializable representations from for-display strings (.ToString()) is generally ill-advised, the format at hand is unlikely to change in a way that will break this:

PS> $Main.BackColor -replace '[^\d,]'  # remove all chars. except digits and commas
255,0,100,200

Note: The above includes the alpha value, unlike the original input string; however, casting back to [System.Drawing.Color] works equally well.


问:
I can't show data from a local API
I need to convert a PHP project to NodeJS, and I already have the API done without errors. The problem is when I want to fetch that data from the front-end, it returns me nothing than 404 errors. When I copy and paste the code in the browser console it works fine.

Server.js

```<code>const express = require("express");
const app = express();
const { Sequelize } = require('sequelize');
const path = require('path');

app.use(express.json());

// Conexion
const sequelize = new Sequelize('interaccion', 'carlos', 'CARLOSpsp1', {
    host: 'localhost',
    dialect: 'mysql'
});

app.get('/', (req,res) => {
    res.sendFile(path.join(`${__dirname}/client/index.html`));
});

app.get('/ejes', async (req, res) => {
    try {
        await sequelize.authenticate();
        console.log('Conexion exitosa');
        const [result, metadata] = await sequelize.query("SELECT * FROM ejes");
        return res.json(result);
    } catch (error) {
        console.error('Hubo un error: ', error);
    }
});

const puerto = process.env.PORT || 3000;

app.listen(puerto,() => console.log(`Servidor en el puerto: ${puerto}`));
</code>```

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hola mundo desde index</h1>

    <div id="container" class="container">

    </div>

    <script src="main.js"></script>
</body>
</html>
</code>```

main.js

```<code>let container = document.getElementById("id");
let div = document.createElement("div");

const fetchData = async () => {
    try{
        const res = await fetch("http://localhost:3000/ejes");
        const roles = await res.json();
        console.log(roles);
        roles.forEach(rol => {
            console.log(rol);
        });
    }catch(e){
        console.log("Error", e);
    }
}

window.onload = fetchData;
</code>```

Response from the route /ejes

console outputs

答:
The problem here is that, you didn't specify the client static files. The static file includes all your javascript, css, images and other static resources.

setup the static resource folder from which the client can request the resource, else express will try to match the specific route. (which you don't have it)

Static resource configuration

```<code>app.use(express.static("client"));
</code>```

Title: I can't show data from a local API

Body:
I need to convert a PHP project to NodeJS, and I already have the API done without errors. The problem is when I want to fetch that data from the front-end, it returns me nothing than 404 errors. When I copy and paste the code in the browser console it works fine.

Server.js

const express = require("express");
const app = express();
const { Sequelize } = require('sequelize');
const path = require('path');

app.use(express.json());

// Conexion
const sequelize = new Sequelize('interaccion', 'carlos', 'CARLOSpsp1', {
    host: 'localhost',
    dialect: 'mysql'
});

app.get('/', (req,res) => {
    res.sendFile(path.join(`${__dirname}/client/index.html`));
});

app.get('/ejes', async (req, res) => {
    try {
        await sequelize.authenticate();
        console.log('Conexion exitosa');
        const [result, metadata] = await sequelize.query("SELECT * FROM ejes");
        return res.json(result);
    } catch (error) {
        console.error('Hubo un error: ', error);
    }
});

const puerto = process.env.PORT || 3000;

app.listen(puerto,() => console.log(`Servidor en el puerto: ${puerto}`));

index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

Hola mundo desde index

main.js

let container = document.getElementById("id");
let div = document.createElement("div");

const fetchData = async () => {
    try{
        const res = await fetch("http://localhost:3000/ejes");
        const roles = await res.json();
        console.log(roles);
        roles.forEach(rol => {
            console.log(rol);
        });
    }catch(e){
        console.log("Error", e);
    }
}

window.onload = fetchData;

Response from the route /ejes

console outputs

Body:
The problem here is that, you didn't specify the client static files. The static file includes all your javascript, css, images and other static resources.

setup the static resource folder from which the client can request the resource, else express will try to match the specific route. (which you don't have it)

Static resource configuration

app.use(express.static("client"));


问:
Spring Boot 2 fails starting due to Hystrix?
I started investigating to migrate a Spring Boot application from 1.5.x to 2.
This appliication has a dependency to hystrix, which does not be compatible to Spring Boot 2 yet.
When I have the following in my pom:

```<code><dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-hystrix</artifactId>
  <version>1.4.4.RELEASE</version>
</dependency>
</code>```

I get the following error when starting the application:

```<code>java.lang.NoSuchMethodError: org.springframework.boot.builder.SpringApplicationBuilder.<init>([Ljava/lang/Object;)V
    at org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:125)
</code>```

Anybody has experienced the same?
Is there a solution yet?

答:
I faced a similar problem with Spring Boot 2, concisely 2.2.0.RELEASE. My mvn project compiled well but Spring Boot application stopped starting, without showing any real hints.

The solution that worked was using the artifact spring-cloud-starter-netflix-hystrix instead of spring-cloud-starter-hystrix from the same group. Then you can use the same same version as Spring Boot to retrieve the dependency.

From old pom.xml :

```<code><!-- hysterix -->
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-hystrix</artifactId>
  <version>1.4.7.RELEASE</version>
</dependency>
</code>```

New part in working pom.xml:

```<code><!-- hysterix -->
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
  <version>${spring.boot.version}</version>
</dependency>
</code>```

Body:
I started investigating to migrate a Spring Boot application from 1.5.x to 2.
This appliication has a dependency to hystrix, which does not be compatible to Spring Boot 2 yet.
When I have the following in my pom:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-hystrix</artifactId>
  <version>1.4.4.RELEASE</version>
</dependency>

I get the following error when starting the application:

java.lang.NoSuchMethodError: org.springframework.boot.builder.SpringApplicationBuilder.<init>([Ljava/lang/Object;)V
    at org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:125)

Anybody has experienced the same?
Is there a solution yet?

Body:
I faced a similar problem with Spring Boot 2, concisely 2.2.0.RELEASE. My mvn project compiled well but Spring Boot application stopped starting, without showing any real hints.

The solution that worked was using the artifact spring-cloud-starter-netflix-hystrix instead of spring-cloud-starter-hystrix from the same group. Then you can use the same same version as Spring Boot to retrieve the dependency.

From old pom.xml :

<!-- hysterix -->
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-hystrix</artifactId>
  <version>1.4.7.RELEASE</version>
</dependency>

New part in working pom.xml:

<!-- hysterix -->
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
  <version>${spring.boot.version}</version>
</dependency>


问:
Which IDE (Android Studio and Visual Code) is better in terms of less memory consumption for Android application development?
I have 4GB RAM and Intel HD graphics so suggest to me in that way which one to choose between Android Studio and Visual Code for android app dev.?</p>

答:
Unfortunately, Visual Code itself doesn't support creating Android projects. You need to install this extension to have some Android development features which are seriously limited compared to the Android Studio.

You can use the Android Studio with 4GB of RAM without having much headache unless you are dealing with really large projects and/or using the Android Emulator at the same time.


问:
How to get xUnit Current Test Name?
In nUnit we can get current test name like TestContext.CurrentContext.Test.Name that I am passing in Sauce Labs with ChromeOptions to show method name in saucelabs like below

```<code>ChromeOptions options = new ChromeOptions();
options.AddAdditionalCapability("username", sauceUserName, true);
options.AddAdditionalCapability("accessKey", sauceAccessKey, true);
options.AddAdditionalCapability("name", TestContext.CurrentContext.Test.Name, true);

_driver = new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"), options.ToCapabilities(), TimeSpan.FromSeconds(600));
</code>```

but TestContext is not present in xUnit. Please help how I can pass the context or method name?

答:
As stated in the comments. Now as an answer:

There seems to be already a solution for this. See here.

Title: How to get xUnit Current Test Name?

Body:
In nUnit we can get current test name like TestContext.CurrentContext.Test.Name that I am passing in Sauce Labs with ChromeOptions to show method name in saucelabs like below

ChromeOptions options = new ChromeOptions();
options.AddAdditionalCapability("username", sauceUserName, true);
options.AddAdditionalCapability("accessKey", sauceAccessKey, true);
options.AddAdditionalCapability("name", TestContext.CurrentContext.Test.Name, true);

_driver = new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"), options.ToCapabilities(), TimeSpan.FromSeconds(600));

but TestContext is not present in xUnit. Please help how I can pass the context or method name?


问:
Calculate maximum of column values with common value in another column in PostgreSQL
I am trying to calculalate maximum of column values with common id.

I have following table as input

```<code>TABLE 1:

| id    | seq    | score |
| ----- | ------ | ----- |
| UA502 | qrst   | 8.2   |
| UA502 | abcdef | 2.2   |
| UA504 | yzab   | 8.8   |
| UA504 | lmnop  | 2.8   |
| UA503 | uvwx   | 8.6   |
| UA503 | ghijk  | 2.6   |

</code>```

The desired output is:

```<code>| id    | seq    | score |
| ----- | ------ | ----- |
| UA502 | qrst   | 8.2   |
| UA504 | yzab   | 8.8   |
| UA503 | uvwx   | 8.6   |
</code>```

I am running following WITH query (max_calc) with groupby and max function on the output of another WITH query (union_data; TABLE 1).

```<code>max_calc as(

  select id, seq, max(score)
  from union_data
  GROUP BY id

  )

select * from max_calc
;

</code>```

The error I am getting is:

```<code> Query Error: error: column "union_data.seq" must appear in the GROUP BY clause or be used in an aggregate function
</code>```

I do not understand this error. I am grouping the data based on common id not seq. Why I should include column "union_data.seq" in GROUPBY.

Thanks

答:
In Postgres, you can use handy extension distinct on for this:

```<code>select distinct on (id) u.*
from union_data u
order by id, score desc
</code>```

Body:
I am trying to calculalate maximum of column values with common id.

I have following table as input

TABLE 1:

| id    | seq    | score |
| ----- | ------ | ----- |
| UA502 | qrst   | 8.2   |
| UA502 | abcdef | 2.2   |
| UA504 | yzab   | 8.8   |
| UA504 | lmnop  | 2.8   |
| UA503 | uvwx   | 8.6   |
| UA503 | ghijk  | 2.6   |

The desired output is:

| id    | seq    | score |
| ----- | ------ | ----- |
| UA502 | qrst   | 8.2   |
| UA504 | yzab   | 8.8   |
| UA503 | uvwx   | 8.6   |

I am running following WITH query (max_calc) with groupby and max function on the output of another WITH query (union_data; TABLE 1).

max_calc as(

  select id, seq, max(score)
  from union_data
  GROUP BY id

  )

select * from max_calc
;

The error I am getting is:

 Query Error: error: column "union_data.seq" must appear in the GROUP BY clause or be used in an aggregate function

I do not understand this error. I am grouping the data based on common id not seq. Why I should include column "union_data.seq" in GROUPBY.

Thanks

Body:
In Postgres, you can use handy extension distinct on for this:

select distinct on (id) u.*
from union_data u
order by id, score desc


问:
Unspecified Margin Problem?
On this page, the title says it has a margin top & bottom of 25px (when I use inspect element in Chrome 10) - but the CSS looks like this:

```<code>.post h2 {
margin:0;
text-align: left;
font-size: 18px;
overflow:hidden;
font-weight:normal;
}
</code>```

I'm trying to decrease the top and bottom margins around the title.

Here's a screenshot of the problem:

答: There's no such element on the page. You should edit .title h2 instead of .post h2.

Title: Unspecified Margin Problem?

Body:
On this page, the title says it has a margin top & bottom of 25px (when I use inspect element in Chrome 10) - but the CSS looks like this:

.post h2 {
margin:0;
text-align: left;
font-size: 18px;
overflow:hidden;
font-weight:normal;
}

I'm trying to decrease the top and bottom margins around the title.

Here's a screenshot of the problem:


问:
Is it possible to use iterate with call and agregate in the same sequence?
I have a scenario in which I need to iterate through an xml and call an endpoint multiple times. After that I need to aggregate the results and use a custom mediator on it. The problem is that all of this has to be done in a single sequence executed by a scheduled task.

Unfortunatelly agregate doesn't seem to wait for the responses. Is there anyway to do this without creating some kind of proxy on the side?

Here's my example code:

<?xml version="1.0" encoding="UTF-8"?>
<sequence name="s_queue_kernel_dev" xmlns="http://ws.apache.org/ns/synapse">
    <kernel.prepare/>
    <iterate continueParent="true"
        expression="//*[local-name()='request']" id="it1"
        sequential="true" xmlns:ns="http://org.apache.synapse/xsd">
        <target>
            <sequence>
                <payloadFactory media-type="xml">
                    <format>
                        <ser:getEntity xmlns:ser="http://services">
                            <ser:entityID>$1</ser:entityID>
                        </ser:getEntity>
                    </format>
                    <args>
                        <arg evaluator="xml"
                            expression="./*[local-name()='entityId']" literal="false"/>
                    </args>
                </payloadFactory>
                <kernel.log>
                    <operation>REQUEST</operation>
                    <description>{$body}</description>
                </kernel.log>
                <call blocking="false">
                    <endpoint key="gov:atena/endpoints/egida/entities.xml"/>
                </call>
            </sequence>
        </target>
    </iterate>
    <aggregate id="it1">
        <completeCondition>
            <messageCount max="-1" min="-1"/>
        </completeCondition>
        <onComplete expression="//*[local-name()='getEntityReturn']" xmlns:ns="http://org.apache.synapse/xsd">
            <kernel.log>
                <operation>RESPONSE</operation>
                <description>{$body}</description>
            </kernel.log>
        </onComplete>
    </aggregate>
    <kernel.log>
        <operation>SUCCESS</operation>
        <description>{$body}</description>
    </kernel.log>
    <kernel.success/>
</sequence>```

答:
I couldn't see an enclosing element tag to aggregate the messages.
Following is a working example. Please modify your sequence accordingly.</p>

```<code><sequence>
        <property name="messageType" value="text/xml" scope="axis2"/>
        <iterate continueParent="true" id="check" expression="//Samples/Sample">
            <target>
                <sequence>
                    <call>
                        <endpoint>
                            <http method="GET" uri-template="http://www.mocky.io/v2/5e2aaab832000066001c6d06"/>
                        </endpoint>
                    </call>
                    <property name="info" scope="default">
                        <ns:Information xmlns:ns="www.asankatechtalks.com"/>
                    </property>
                </sequence>
            </target>
        </iterate>
        <aggregate id="check">
            <completeCondition>
                <messageCount max="-1" min="-1"/>
            </completeCondition>
            <onComplete expression="$body/*[1]" enclosingElementProperty="info">
                <respond/>
            </onComplete>
        </aggregate>
    </sequence>
</code>```

Body:
I couldn't see an enclosing element tag to aggregate the messages.
Following is a working example. Please modify your sequence accordingly.

<sequence>
        <property name="messageType" value="text/xml" scope="axis2"/>
        <iterate continueParent="true" id="check" expression="//Samples/Sample">
            <target>
                <sequence>
                    <call>
                        <endpoint>
                            <http method="GET" uri-template="http://www.mocky.io/v2/5e2aaab832000066001c6d06"/>
                        </endpoint>
                    </call>
                    <property name="info" scope="default">
                        <ns:Information xmlns:ns="www.asankatechtalks.com"/>
                    </property>
                </sequence>
            </target>
        </iterate>
        <aggregate id="check">
            <completeCondition>
                <messageCount max="-1" min="-1"/>
            </completeCondition>
            <onComplete expression="$body/*[1]" enclosingElementProperty="info">
                <respond/>
            </onComplete>
        </aggregate>
    </sequence>


问:
Golang equivalent of java servlet filter
Does the Go language have an equivalent of the java servlet filter, such that you can have a single function of code that automatically gets added to all incoming http requests?  I'm also curious if it's possible to apply the filter to a URL pattern, ie, a subset of incoming requests based on URI.

What is the Golang way of doing this?

答:
It a Middleware func which wrapps a HandleFunc

Something like it is descrived here
https://www.alexedwards.net/blog/making-and-using-middleware


问:
DeafultcCellStyle format not working on unbound DataGridView C# Winforms
I have an unbound DataGridView that I populate with data from an SQL database. One of the columns in the database is of type ‘datetime’.

On the load event of my winforms application, I use code below in order to format the column to only show date part of datetime column. However it shows the full datetime. I want 18/02/2020 and it’s showing 18/02/2020 00:00:00

```<code>dgv.Columns["Date"].DefaultCellStyle.Format = "dd/MM/yyyy"
dgv.Columns["Date"].ValueType = typeof(System.DateTime);
</code>```

How do I format the column to only show the date portion of the datetime column?

答:
I added some data in the gridview within my code and tried your code above. The DefaultCellStyle.Format works well.

Which means that you might need to check the way you're retrieving the data from your SQL Database. You may be filling your grid with strings instead of "dates" for example.

Body:
I have an unbound DataGridView that I populate with data from an SQL database. One of the columns in the database is of type ‘datetime’.

On the load event of my winforms application, I use code below in order to format the column to only show date part of datetime column. However it shows the full datetime. I want 18/02/2020 and it’s showing 18/02/2020 00:00:00

dgv.Columns["Date"].DefaultCellStyle.Format = "dd/MM/yyyy"
dgv.Columns["Date"].ValueType = typeof(System.DateTime);

How do I format the column to only show the date portion of the datetime column?


问:
Uploading the content of a variable as a file into FTP server using Bash
Using Bash scripting, I'm trying to upload the content of variable into an FTP server.

The variable is $HASHED and it contains some hashed password

echo $HASHED

The output of the above command is: M0eSl8NR40wH

I need to do the following:

Create a time/date stamped file in the FTP server (i.e. PASSWORD_18_02_2014)

The file needs to have the same content of the $HASHED value (i.e. the PASSWORD_18_02_2014 needs to have M0eSl8NR40wH inside it).

Trying Curl, I couldn't get it working using the following:

```<code>UPLOAD="curl -T $HASHED ftp://192.168.0.1/passwords/ --user username:password"
$UPLOAD
</code>```

Your help is very much appreciated.

答:
Please try this:

```<code>HASHED="M0eSl8NR40wH"
echo "$HASHED" | curl --silent --show-error --upload-file \
-ftp://192.168.0.1/passwords/$(date +PASSWORD_%d_%m_%Y) --user username:password
</code>```

Where:

```<code>--silent        : prevents the progress bar
--show-error    : shows errors if any
--upload-file - : get file from stdin
</code>```

The target name is indicated as part of the URL

Body:
Using Bash scripting, I'm trying to upload the content of variable into an FTP server.

The variable is $HASHED and it contains some hashed password

echo $HASHED

The output of the above command is: M0eSl8NR40wH

I need to do the following:

Create a time/date stamped file in the FTP server (i.e. PASSWORD_18_02_2014)

The file needs to have the same content of the $HASHED value (i.e. the PASSWORD_18_02_2014 needs to have M0eSl8NR40wH inside it).

Trying Curl, I couldn't get it working using the following:

UPLOAD="curl -T $HASHED ftp://192.168.0.1/passwords/ --user username:password"
$UPLOAD

Your help is very much appreciated.

Body:
Please try this:

HASHED="M0eSl8NR40wH"
echo "$HASHED" | curl --silent --show-error --upload-file \
-ftp://192.168.0.1/passwords/$(date +PASSWORD_%d_%m_%Y) --user username:password

Where:

--silent        : prevents the progress bar
--show-error    : shows errors if any
--upload-file - : get file from stdin

The target name is indicated as part of the URL


问:
merge and update not present values
I am trying to merge two dataframes such that if any not columns present in df1's variables source should take from df2's rows. I tried the merge below but no works. Please help.

```<code>df1 <- data.frame(source = c("Pr1", "Pr2","Pr3"),
                     date = c("Jan 2018","Feb 2018","Mar 2018"),
                     Freq = c(100,20,30))
df2 <- data.frame(source = c("Pr1","Pr2","Pr1"),
                     date = c("Sep 2018","Aug 2018","Jan 2018"),
                     Freq = c(0,0,0))

df <- merge(df1,df2,by = c("source","date"))
</code>```

Expected Output:

```<code>  source     date Freq
1    Pr1 Jan 2018  100
2    Pr2 Feb 2018   20
3    Pr3 Mar 2018   30
4    Pr1 Sep 2018    0
5    Pr2 Aug 2018    0
</code>```

答:
Here's a tidyverse/dplyr answer.

```<code>library(tidyverse)

df1 <- data.frame(source = c("Pr1", "Pr2","Pr3"),
                  date = c("Jan 2018","Feb 2018","Mar 2018"),
                  Freq = c(100,20,30))
df2 <- data.frame(source = c("Pr1","Pr2","Pr1"),
                  date = c("Sep 2018","Aug 2018","Jan 2018"),
                  Freq = c(0,0,0))

df <- full_join(df1,df2,by = c("source","date"))
</code>```

```<code>  source     date Freq.x Freq.y
1    Pr1 Jan 2018    100      0
2    Pr2 Feb 2018     20     NA
3    Pr3 Mar 2018     30     NA
4    Pr1 Sep 2018     NA      0
5    Pr2 Aug 2018     NA      0
</code>```

```<code>final_df <- df %>%
  mutate(Frequency = if_else(is.na(Freq.x), Freq.y, Freq.x)) %>%
  select(source, date, Frequency)
</code>```

```<code>  source     date Frequency
1    Pr1 Jan 2018       100
2    Pr2 Feb 2018        20
3    Pr3 Mar 2018        30
4    Pr1 Sep 2018         0
5    Pr2 Aug 2018         0
</code>```

Just note the behavior of the if_else() -  it will keep the df1 frequency if it is 0 (not NA).

Title: merge and update not present values

Body:
I am trying to merge two dataframes such that if any not columns present in df1's variables source should take from df2's rows. I tried the merge below but no works. Please help.

df1 <- data.frame(source = c("Pr1", "Pr2","Pr3"),
                     date = c("Jan 2018","Feb 2018","Mar 2018"),
                     Freq = c(100,20,30))
df2 <- data.frame(source = c("Pr1","Pr2","Pr1"),
                     date = c("Sep 2018","Aug 2018","Jan 2018"),
                     Freq = c(0,0,0))

df <- merge(df1,df2,by = c("source","date"))

Expected Output:

  source     date Freq
1    Pr1 Jan 2018  100
2    Pr2 Feb 2018   20
3    Pr3 Mar 2018   30
4    Pr1 Sep 2018    0
5    Pr2 Aug 2018    0

Body:
Here's a tidyverse/dplyr answer.

library(tidyverse)

df1 <- data.frame(source = c("Pr1", "Pr2","Pr3"),
                  date = c("Jan 2018","Feb 2018","Mar 2018"),
                  Freq = c(100,20,30))
df2 <- data.frame(source = c("Pr1","Pr2","Pr1"),
                  date = c("Sep 2018","Aug 2018","Jan 2018"),
                  Freq = c(0,0,0))

df <- full_join(df1,df2,by = c("source","date"))

  source     date Freq.x Freq.y
1    Pr1 Jan 2018    100      0
2    Pr2 Feb 2018     20     NA
3    Pr3 Mar 2018     30     NA
4    Pr1 Sep 2018     NA      0
5    Pr2 Aug 2018     NA      0

final_df <- df %>%
  mutate(Frequency = if_else(is.na(Freq.x), Freq.y, Freq.x)) %>%
  select(source, date, Frequency)

  source     date Frequency
1    Pr1 Jan 2018       100
2    Pr2 Feb 2018        20
3    Pr3 Mar 2018        30
4    Pr1 Sep 2018         0
5    Pr2 Aug 2018         0

Just note the behavior of the if_else() -  it will keep the df1 frequency if it is 0 (not NA).


问:
How to figure out (using terminal) which version of python pip is installing to (MacOS)
Question in title. How do I figure out (using terminal) which version of python pip is installing to (Ex. Python 2.7 or Python 3.6). I am looking to use Terminal on MacOS.</p>

答:
This is easily Google-able, but to save you a few seconds:  </p>

```<code>python --version
</code>```

Body:
This is easily Google-able, but to save you a few seconds:

python --version


问:
parsing string with respect to string format |how
I have ;

```<code> string  str = "";
</code>```

in str, I store data is in following form "_ : _, _ "
"_" can be just a word like "X" or a composition of words like "a sds 23 dsds 1"

I want them parse it to three different string ;

```<code>in str       : X:y dfj kd kk,sdd 12 89 ++
string parsed[i] ;
in parsed[0] : X
in parsed[1] : y dfj kd kk
in parsed[2] : sdd 12 89 ++
</code>```

How can I do that over using c++ std::string features ?

答:
Using boost/algorithm/string.hpp

```<code>std::string str = "X:y dfj kd kk,sdd 12 89 ++"
std::vector<std::string> v;
boost::split(v, str, boost::is_any_of(":,"));
</code>```

You can also use it for multibyte strings.

Body:
I have ;

 string  str = "";

in str, I store data is in following form "_ : _, _ "
"_" can be just a word like "X" or a composition of words like "a sds 23 dsds 1"

I want them parse it to three different string ;

in str       : X:y dfj kd kk,sdd 12 89 ++
string parsed[i] ;
in parsed[0] : X
in parsed[1] : y dfj kd kk
in parsed[2] : sdd 12 89 ++

How can I do that over using c++ std::string features ?

Body:
Using boost/algorithm/string.hpp

std::string str = "X:y dfj kd kk,sdd 12 89 ++"
std::vector<std::string> v;
boost::split(v, str, boost::is_any_of(":,"));

You can also use it for multibyte strings.


问:
scss animation works once
I am trying to make a side menu that slides to left and right when you click on it
but it only happens once with animation
the menu goes to left and right but without any animation

html code

```<code><div class="arrow" (click)="gaucheDroite()"
    [ngClass] = "{
            'classgauche' : gauche == 1,
            'classdroite' : gauche == 2
        }">
    <i class="fas fa-arrow-right"></i>
</div>
<div class="mere"
[ngClass] = "{
    'classgauche' : gauche == 1,
    'classdroite' : gauche == 2
}">

</div>
</code>```

scss code  animation of the menu

```<code>
.classgauche{
    animation: translatex 1000ms ease-in-out 100ms both;
}
.classdroite{
    animation: translatex 1000ms ease-in-out 100ms reverse both;
}
@keyframes translatex{
    0% {
        transform: translateX(-300px);
    }
    100% {
        transform: translateX(0);
    }
}
.arrow{
    height: 50px;
    width: 50px;
    background-color: #fdfdfd;
    z-index: 11;
    border-radius: 0 2px 2px 0;
    display: inline-block;
    box-shadow: 2px 0.5px 3px #b4b4b4;
    //transform: translateX(-300px);
}
</code>```

Angular code on click method

```<code>  gaucheDroite(){
    //this.gauche = ! this.gauche;
    if(this.gauche == 0 || this.gauche == 1){
      this.gauche =2;
      setTimeout(function() {
          this.gauche =0;
      }, 100);
    }
    else if(this.gauche == 2){
      this.gauche = 1;
      setTimeout(function() {
          this.gauche =0;
      }, 100);
    }
  }

}

</code>```

答: Best thing to do that is use Angular animations. Here you have an example of how to do it https://stackblitz.com/edit/angular-8zy3pi?file=src%2Fapp%2Fcomponents%2Fleft-menu%2Fleft-menu.component.ts</p>

Title: scss animation works once

Body:
I am trying to make a side menu that slides to left and right when you click on it
but it only happens once with animation
the menu goes to left and right but without any animation

html code

scss code  animation of the menu

.classgauche{
    animation: translatex 1000ms ease-in-out 100ms both;
}
.classdroite{
    animation: translatex 1000ms ease-in-out 100ms reverse both;
}
@keyframes translatex{
    0% {
        transform: translateX(-300px);
    }
    100% {
        transform: translateX(0);
    }
}
.arrow{
    height: 50px;
    width: 50px;
    background-color: #fdfdfd;
    z-index: 11;
    border-radius: 0 2px 2px 0;
    display: inline-block;
    box-shadow: 2px 0.5px 3px #b4b4b4;
    //transform: translateX(-300px);
}

Angular code on click method

  gaucheDroite(){
    //this.gauche = ! this.gauche;
    if(this.gauche == 0 || this.gauche == 1){
      this.gauche =2;
      setTimeout(function() {
          this.gauche =0;
      }, 100);
    }
    else if(this.gauche == 2){
      this.gauche = 1;
      setTimeout(function() {
          this.gauche =0;
      }, 100);
    }
  }

}


问:
AES Encryption/Decryption in Node JS similar to Java
I am trying to replicate the Java code for AES Encryption and Decryption in Node JS.

Java Code

```<code>    SecretKeySpec skeySpec;
    String key = "a4e1112f45e84f785358bb86ba750f48";

    public void encryptString(String key) throws Exception {
        try {
            skeySpec = new SecretKeySpec(key.getBytes(), "AES");
            cipher = Cipher.getInstance("AES");
            cipher.init(1, skeySpec);
            byte encstr[] = cipher.doFinal(message.getBytes());
            String encData = new String(encstr, "UTF-8");
            System.out.println(encData);
        } catch (NoSuchAlgorithmException nsae) {
            throw new Exception("Invalid Java Version");
        } catch (NoSuchPaddingException nse) {
            throw new Exception("Invalid Key");
        }
    }
</code>```

Node JS

```<code>    var encryptKey = function (text) {
        var cipher = crypto.createCipher('aes256', 'a4e1112f45e84f785358bb86ba750f48');
        var crypted = cipher.update(text,'utf8', 'hex')
        crypted += cipher.final('hex');
        console.log(crypted);
        return crypted;
    }
</code>```

I am unable to get the exact cipher-text in Node JS, which i am getting in Java.

答:
Your code actually uses different encryption parameters in the 2 cases. AES, being a block cipher, takes: the plain text to encrypt, the initialization vector, also called IV (which is used in conjunction with the plaintext), and the encryption key.

In Java, the IV is, apparently, generated automatically on init() - from the Java SE platform docs for Cipher.init:

The generated parameters can be retrieved using getParameters or getIV
  (if the parameter is an IV).

In Node.js, if using the deprecated createCipher function, the IV is generated automatically based on the provided key, probably in a different way than in Java, so you will get a different cipher text. However, you should be using the non-deprecated variant crypto.createCipheriv: https://nodejs.org/docs/latest-v12.x/api/crypto.html#crypto_crypto_createcipheriv_algorithm_key_iv_options

In order to exactly reproduce the cipher text, you should:

Use the same encryption algorithm on both sides - it's best to specify this exactly, for example aes-256-cbc, or an authenticated encryption scheme such as aes-256-gcm, which is harder to use but provides message authentication.

Use the same IV on both sides, by providing it in the initialization params in Java, and by using createCipheriv in Node; though beware, you should always randomize it in production! See https://stackoverflow.com/a/20888967/6098312

As a closing remark, when using block encryption, you'll usually be generating securely-random IVs, which means the ciphertexts will always differ from one another, even for the same plaintext. This is a good thing! It protects your payload from an attacker who observes the encrypted data and makes conclusions based on message repetitions.

Body:
I am trying to replicate the Java code for AES Encryption and Decryption in Node JS.

Java Code

    SecretKeySpec skeySpec;
    String key = "a4e1112f45e84f785358bb86ba750f48";

    public void encryptString(String key) throws Exception {
        try {
            skeySpec = new SecretKeySpec(key.getBytes(), "AES");
            cipher = Cipher.getInstance("AES");
            cipher.init(1, skeySpec);
            byte encstr[] = cipher.doFinal(message.getBytes());
            String encData = new String(encstr, "UTF-8");
            System.out.println(encData);
        } catch (NoSuchAlgorithmException nsae) {
            throw new Exception("Invalid Java Version");
        } catch (NoSuchPaddingException nse) {
            throw new Exception("Invalid Key");
        }
    }

Node JS

    var encryptKey = function (text) {
        var cipher = crypto.createCipher('aes256', 'a4e1112f45e84f785358bb86ba750f48');
        var crypted = cipher.update(text,'utf8', 'hex')
        crypted += cipher.final('hex');
        console.log(crypted);
        return crypted;
    }

I am unable to get the exact cipher-text in Node JS, which i am getting in Java.


问:
Adding Zeromq to an existing Java Gradle project from Github
I have downloaded a Java Gradle project from Github. I'm using Eclipse.
Now I want to incorporate ZeroQM to the project using Jeromq.
https://github.com/zeromq/jeromq

What steps must I follow in Eclipse so I can write
import org.zeromq.ZMQ;
import org.zeromq.ZContext;

and create a Zmq client inside an existing class in the current gradle environment

Thanks

答:
If you use gradle there is no need to download anything.
Just open the file build.gradle that you should already have and add

```<code>compile group: 'org.zeromq', name: 'jeromq', version: '0.5.2'
</code>```

inside the 'dependencies' section.
At least this is how IntelliJ Idea works, but Eclipse should be more or less the same.

Hope this helps.

Body:
If you use gradle there is no need to download anything.
Just open the file build.gradle that you should already have and add

compile group: 'org.zeromq', name: 'jeromq', version: '0.5.2'

inside the 'dependencies' section.
At least this is how IntelliJ Idea works, but Eclipse should be more or less the same.

Hope this helps.


答:
Use

```<code>pip -V
</code>```

which will tell you the PIP version and the python version. If you'd like to decide which python version to install to:

```<code>$ pip2.6 install otherpackage
$ pip2.7 install mybarpackage
</code>```

Title: How to figure out (using terminal) which version of python pip is installing to (MacOS)

Body: Question in title. How do I figure out (using terminal) which version of python pip is installing to (Ex. Python 2.7 or Python 3.6). I am looking to use Terminal on MacOS.

Body:
Use

pip -V

which will tell you the PIP version and the python version. If you'd like to decide which python version to install to:

$ pip2.6 install otherpackage
$ pip2.7 install mybarpackage


问:
Implicit conversions in row.getAs[Long]
When I try to apply a filter function on a dataframe , I have met a confused problem.

If the fields of a row are null, isNotNull1 will be false, and isNotNull2 will be true. Here is the code:

```<code>      val res = df.filter(row => {
        val isNotNull1 = (row.getAs[Long]("video_id") != null)
        val videoId = row.getAs[Long]("video_id")
        val isNotNull2 = (videoId != null)
        isNotNull2
      })
</code>```

Idea debug result:

I can understand isNotNull2 is true, as the doc of getAs[T](fieldName: String) says For primitive types if value is null it returns 'zero value' specific for primitive.

Are there scala implicit conversions happened here? Thanks for you help.

答:
The Scala compiler can often infer the type of an expression so we don’t have to declare it explicitly.

While evaluating val isNotNull1 = (row.getAsLong != null) row.getAsLong is null and null != null is false.
While evaluating val videoId = row.getAsLong row.getAsLong will still be null however compiler infer it is a Long and null will be assign to 0 because primitive could not be null.

Also, in the below code, videoId_wrong will throw a compiler error it is a Long and has been explicitly inferred as String.

```<code>val res = df.filter(row => {
  val isNotNull1 = (row.getAs[Long]("video_id") != null)
  val videoId_wrong: String = row.getAs[Long]("video_id")
  val videoId = row.getAs[Long]("video_id")
  val isNotNull2 = (videoId != null)
  isNotNull2
})
</code>```

https://docs.scala-lang.org/tour/type-inference.html

Title: Implicit conversions in row.getAs[Long]

Body:
When I try to apply a filter function on a dataframe , I have met a confused problem.

If the fields of a row are null, isNotNull1 will be false, and isNotNull2 will be true. Here is the code:

      val res = df.filter(row => {
        val isNotNull1 = (row.getAs[Long]("video_id") != null)
        val videoId = row.getAs[Long]("video_id")
        val isNotNull2 = (videoId != null)
        isNotNull2
      })

Idea debug result:

I can understand isNotNull2 is true, as the doc of getAs[T](fieldName: String) says For primitive types if value is null it returns 'zero value' specific for primitive.

Are there scala implicit conversions happened here? Thanks for you help.

Body:
The Scala compiler can often infer the type of an expression so we don’t have to declare it explicitly.

While evaluating val isNotNull1 = (row.getAsLong != null) row.getAsLong is null and null != null is false.
While evaluating val videoId = row.getAsLong row.getAsLong will still be null however compiler infer it is a Long and null will be assign to 0 because primitive could not be null.

Also, in the below code, videoId_wrong will throw a compiler error it is a Long and has been explicitly inferred as String.

val res = df.filter(row => {
  val isNotNull1 = (row.getAs[Long]("video_id") != null)
  val videoId_wrong: String = row.getAs[Long]("video_id")
  val videoId = row.getAs[Long]("video_id")
  val isNotNull2 = (videoId != null)
  isNotNull2
})

https://docs.scala-lang.org/tour/type-inference.html


答:
Use this command to find out which version of pip is installed:</p>

```<code>pip list | grep pip
</code>```

Body:
Use this command to find out which version of pip is installed:

pip list | grep pip


问:
Passing JS variables/values of variables from a function in a first js file, to a second file
Is it possible to pass variables between two different JS files without using Node js, only with vanilla JS? I am only doing this on client side, I am not using a server or anything else.

In the first file (first.js) I have this (shortened) bit of code:

```<code>function appendImg(){
  var img = document.createElement('img');
  img.src = tempImg.src;
  document.body.appendChild(img);
  createImg(index++);

  img.onclick = function(event){
    window.location.href = "second.html";
    }
}
</code>```

Where "img" comes from a series of operations, src assigning, etc, from a given images array I wrote at the beginning of my file.

What I'm trying to do is, when I click a certain image, it redirects me to another HTML page, as you can see, where I would like to display the same image that was clicked.

I'm having trouble doing this, as my img variable is declared in a function, and the second JS file does not recognize it.

How could I change this?

答:
As @Keith said, you are reloading the page, so you lose all memory. Even if you put it in the global scope, where another function could read it, it is gone.

One approach you could use is to put some reference in the url parameters:

```<code>function appendImg(){
  var img
  img = document.createElement('img');
  img.src = tempImg.src;
  document.body.appendChild(img);
  createImg(index++);

  img.onclick = function(event){
    window.location.href = "second.html?img_src=" + tempImg.src;
    }
}
</code>```

Then in the second page you write code to examine the url parameters of the location.

Body:
Is it possible to pass variables between two different JS files without using Node js, only with vanilla JS? I am only doing this on client side, I am not using a server or anything else.

In the first file (first.js) I have this (shortened) bit of code:

function appendImg(){
  var img = document.createElement('img');
  img.src = tempImg.src;
  document.body.appendChild(img);
  createImg(index++);

  img.onclick = function(event){
    window.location.href = "second.html";
    }
}

Where "img" comes from a series of operations, src assigning, etc, from a given images array I wrote at the beginning of my file.

What I'm trying to do is, when I click a certain image, it redirects me to another HTML page, as you can see, where I would like to display the same image that was clicked.

I'm having trouble doing this, as my img variable is declared in a function, and the second JS file does not recognize it.

How could I change this?

Body:
As @Keith said, you are reloading the page, so you lose all memory. Even if you put it in the global scope, where another function could read it, it is gone.

One approach you could use is to put some reference in the url parameters:

function appendImg(){
  var img
  img = document.createElement('img');
  img.src = tempImg.src;
  document.body.appendChild(img);
  createImg(index++);

  img.onclick = function(event){
    window.location.href = "second.html?img_src=" + tempImg.src;
    }
}

Then in the second page you write code to examine the url parameters of the location.


问:
How to categorize a data set without the use of `case when`
Please have a look at my picture in which I have tried to explain what I want to achieve: each column should be the sum of values within the country and category.
How will you suggest I solve this problem? There must be a standard approach by SQL user that I have overlooked.

I know I can work my way around it by something like

case when category = 'CatA' then sum(value) as 'CatA' and then a group by

but when my categories are too many this solution will be messy I will avoid it.

I am using Oracle SQL and Toad

EDIT:
I have two answers but I think I have mis communicated what I whish. Basically what I wish to achieve is to avoid type in the categories manually.

答:
You can use PIVOT as following:

```<code>Select *
FROM (select country, category, value from your_table)
PIVOT
(sum(value) for
  category in ('CatA', 'CatB', 'CatC', ....your other categories like this...)
);
</code>```

Cheers!!

Body:
You can use PIVOT as following:

Select *
FROM (select country, category, value from your_table)
PIVOT
(sum(value) for
  category in ('CatA', 'CatB', 'CatC', ....your other categories like this...)
);

Cheers!!


问:
Arrays.asList returns false
I just wanna check if my String[] array contains "n" or "s".

```<code>String[] coordinatesExample = {"57.8136°s", "28.3496°e"};

private void isContains(String[] coordinates) {

    boolean contains = Arrays.asList(coordinates).contains("s");
        if (contains) {
            System.out.println("It works!");
        }else {
            System.out.println("RAKAMAKAFO");
        }
</code>```

So I expected: "It works!", but
in fact: "RAKAMAKAFO"

What I did wrong?

答:
Your current solution only works if you have a String Array like this:

```<code>String[] coordinatesExample = {"57.8136°s", "28.3496°e", "s"};
</code>```

Try this if you want to check if any String from your Array contains "n" or "s".

```<code>private static void isContains(String[] coordinates) {
    boolean contains = Arrays.stream(coordinates)
            .anyMatch(coordinate -> coordinate.contains("s") || coordinate.contains("n"));
    if (contains) {
        System.out.println("It works!");
    } else {
        System.out.println("RAKAMAKAFO");
    }
}
</code>```

Title: Arrays.asList returns false

Body:
I just wanna check if my String[] array contains "n" or "s".

String[] coordinatesExample = {"57.8136°s", "28.3496°e"};

private void isContains(String[] coordinates) {

    boolean contains = Arrays.asList(coordinates).contains("s");
        if (contains) {
            System.out.println("It works!");
        }else {
            System.out.println("RAKAMAKAFO");
        }

So I expected: "It works!", but
in fact: "RAKAMAKAFO"

What I did wrong?

Body:
Your current solution only works if you have a String Array like this:

String[] coordinatesExample = {"57.8136°s", "28.3496°e", "s"};

Try this if you want to check if any String from your Array contains "n" or "s".

private static void isContains(String[] coordinates) {
    boolean contains = Arrays.stream(coordinates)
            .anyMatch(coordinate -> coordinate.contains("s") || coordinate.contains("n"));
    if (contains) {
        System.out.println("It works!");
    } else {
        System.out.println("RAKAMAKAFO");
    }
}


答:
Contains only checks to see if the list contains one of the elements which s is not one.

From the JavaDoc for the List interface

boolean contains(Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that Objects.equals(o, e).

If you did the following, it would return print It works! because the first string in the list contained an s

```<code>private static void isContains(String[] coordinates) {

    boolean contains = Arrays.asList(coordinates).get(0).contains("s");
        if (contains) {
            System.out.println("It works!");
        }else {
            System.out.println("RAKAMAKAFO");
        }
    }
}
</code>```

Title: Arrays.asList returns false

Body:
Contains only checks to see if the list contains one of the elements which s is not one.

From the JavaDoc for the List interface

boolean contains(Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that Objects.equals(o, e).

If you did the following, it would return print It works! because the first string in the list contained an s

private static void isContains(String[] coordinates) {

    boolean contains = Arrays.asList(coordinates).get(0).contains("s");
        if (contains) {
            System.out.println("It works!");
        }else {
            System.out.println("RAKAMAKAFO");
        }
    }
}


问:
Spatial autocorrelation analysis withe several observations per location in R
I have data collected from several sampling sites across a landscape.
Each individual sample has a unique dependent variable (y) and explanatory variables shared with 9 other samples:

```<code>DependentVar<-rnorm(60,mean = 9.5,sd=.5)
Temperature<-rep(c(23.5,18,26.1,24.7,20.8,20),each=10)
SpatData<-data.frame(x = rep(runif(6,0,100),each=10), y = rep(runif(6,0,100),each=10))
SpatData$Temperature<-Temperature
SpatData$DependentVar<-DependentVar
</code>```

I have constructed a linear model to test the influence of temp. on the dependent variable:

```<code>SpatLM<-lm(DependentVar~Temperature,data = SpatData)
</code>```

Then I have tried to test for autocorrelation of the residuals like so:

```<code>library(DHARMa)
sims<-simulateResiduals(SpatLM)
testSpatialAutocorrelation(sims, x=SpatData$x,y=SpatData$y)
</code>```

The message I got was:

Error in testSpatialAutocorrelation(sims, x = SpatData$x, y = SpatData$y) :
    testing for spatial autocorrelation requires unique x,y values - if you have several observations per location, either use the recalculateResiduals function to aggregate residuals per location, or extract the residuals from the fitted object, and plot / test each of them independently for spatially repeated subgroups (a typical scenario would repeated spatial observation, in which case one could plot / test each time step separately for temporal autocorrelation). Note that the latter must be done by hand, outside testSpatialAutocorrelation.

Using recalculateResiduals() doesn't seem to work, with or without grouping:
simsrecalc<-recalculateResiduals(sims,group = SpatData$Temperature)

Anyone has an idea how to solve this?

答:
The answer is given in the error message. Look at your simulated data for SpatData$x:

```<code>SpatData$x
#>  [1] 14.65469 14.65469 14.65469 14.65469 14.65469 14.65469 14.65469 14.65469 14.65469 14.65469
#> [11] 55.59340 55.59340 55.59340 55.59340 55.59340 55.59340 55.59340 55.59340 55.59340 55.59340
#> [21] 88.07651 88.07651 88.07651 88.07651 88.07651 88.07651 88.07651 88.07651 88.07651 88.07651
#> [31] 58.31331 58.31331 58.31331 58.31331 58.31331 58.31331 58.31331 58.31331 58.31331 58.31331
#> [41] 30.44448 30.44448 30.44448 30.44448 30.44448 30.44448 30.44448 30.44448 30.44448 30.44448
#> [51] 53.43158 53.43158 53.43158 53.43158 53.43158 53.43158 53.43158 53.43158 53.43158 53.43158
</code>```

Every value repeats 10 times because of the way you have generated the random data. The same is true of the y values. You therefore only have 6 unique (x, y) co-ordinates in your data, and you are asking for a spatial autocorrelation when some of the samples are co-located. This is a bit like trying to analyse a time series of stock values when you have ten different values for the stock price at each point in time. It doesn't really make any sense.

If you create your test data frame using runif(60, 0, 100) for x and do the same for y, the problem disappears, because now you have 60 unique (x, y) co-ordinates.

Your description of your real data isn't really clear enough to know if this is a real problem or not. Assuming you do have several samples from each location, you need to decide what to do with them. If they are all different variables, then you just put them in different columns of your data frame. If they are multiple measurements of the same variable (as in your example), you need to decide whether you want to average them or (if they were taken at different times) whether you want to run a spatial autocorrelation at each time point.

Here is an example of taking the mean temperature at each point and using that for the spatial autocorrelation:

library(DHARMa)
library(dplyr)

SpatData <- data.frame(x = rep(runif(6, 0, 100), each = 10),
                       y = rep(runif(6, 0, 100), each = 10),
                       Temperature = rep(c(23.5, 18, 26.1, 24.7, 20.8, 20), each = 10),
                       DependentVar = rnorm(60, mean = 9.5, sd = 0.5))

MeanData <- SpatData %>%
  group_by(x, y)     %>%
  summarize(Temperature = mean(Temperature), DependentVar = mean(DependentVar))

SpatLM <- lm(DependentVar ~ Temperature, data = MeanData)
sims   <- simulateResiduals(SpatLM)
testSpatialAutocorrelation(sims, x = MeanData$x, y = MeanData$y)
```

<p><img src="https://i.imgur.com/pRPaecY.png" alt=""></p>

```#>
#>  DHARMa Moran's I test for spatial autocorrelation
#>
#> data:  sims
#> observed = -0.45465, expected = -0.20000, sd = 0.19274, p-value =
#> 0.1864
#> alternative hypothesis: Spatial autocorrelation
```

Created on 2020-02-18 by the reprex package (v0.3.0)

Body:
I have data collected from several sampling sites across a landscape.
Each individual sample has a unique dependent variable (y) and explanatory variables shared with 9 other samples:

DependentVar<-rnorm(60,mean = 9.5,sd=.5)
Temperature<-rep(c(23.5,18,26.1,24.7,20.8,20),each=10)
SpatData<-data.frame(x = rep(runif(6,0,100),each=10), y = rep(runif(6,0,100),each=10))
SpatData$Temperature<-Temperature
SpatData$DependentVar<-DependentVar

I have constructed a linear model to test the influence of temp. on the dependent variable:

SpatLM<-lm(DependentVar~Temperature,data = SpatData)

Then I have tried to test for autocorrelation of the residuals like so:

library(DHARMa)
sims<-simulateResiduals(SpatLM)
testSpatialAutocorrelation(sims, x=SpatData$x,y=SpatData$y)

The message I got was:

Error in testSpatialAutocorrelation(sims, x = SpatData$x, y = SpatData$y) :
    testing for spatial autocorrelation requires unique x,y values - if you have several observations per location, either use the recalculateResiduals function to aggregate residuals per location, or extract the residuals from the fitted object, and plot / test each of them independently for spatially repeated subgroups (a typical scenario would repeated spatial observation, in which case one could plot / test each time step separately for temporal autocorrelation). Note that the latter must be done by hand, outside testSpatialAutocorrelation.

Using recalculateResiduals() doesn't seem to work, with or without grouping:
simsrecalc<-recalculateResiduals(sims,group = SpatData$Temperature)

Anyone has an idea how to solve this?

Body:
The answer is given in the error message. Look at your simulated data for SpatData$x:

SpatData$x
#>  [1] 14.65469 14.65469 14.65469 14.65469 14.65469 14.65469 14.65469 14.65469 14.65469 14.65469
#> [11] 55.59340 55.59340 55.59340 55.59340 55.59340 55.59340 55.59340 55.59340 55.59340 55.59340
#> [21] 88.07651 88.07651 88.07651 88.07651 88.07651 88.07651 88.07651 88.07651 88.07651 88.07651
#> [31] 58.31331 58.31331 58.31331 58.31331 58.31331 58.31331 58.31331 58.31331 58.31331 58.31331
#> [41] 30.44448 30.44448 30.44448 30.44448 30.44448 30.44448 30.44448 30.44448 30.44448 30.44448
#> [51] 53.43158 53.43158 53.43158 53.43158 53.43158 53.43158 53.43158 53.43158 53.43158 53.43158

Every value repeats 10 times because of the way you have generated the random data. The same is true of the y values. You therefore only have 6 unique (x, y) co-ordinates in your data, and you are asking for a spatial autocorrelation when some of the samples are co-located. This is a bit like trying to analyse a time series of stock values when you have ten different values for the stock price at each point in time. It doesn't really make any sense.

If you create your test data frame using runif(60, 0, 100) for x and do the same for y, the problem disappears, because now you have 60 unique (x, y) co-ordinates.

Your description of your real data isn't really clear enough to know if this is a real problem or not. Assuming you do have several samples from each location, you need to decide what to do with them. If they are all different variables, then you just put them in different columns of your data frame. If they are multiple measurements of the same variable (as in your example), you need to decide whether you want to average them or (if they were taken at different times) whether you want to run a spatial autocorrelation at each time point.

Here is an example of taking the mean temperature at each point and using that for the spatial autocorrelation:

library(DHARMa)
library(dplyr)

SpatData <- data.frame(x = rep(runif(6, 0, 100), each = 10),
                       y = rep(runif(6, 0, 100), each = 10),
                       Temperature = rep(c(23.5, 18, 26.1, 24.7, 20.8, 20), each = 10),
                       DependentVar = rnorm(60, mean = 9.5, sd = 0.5))

MeanData <- SpatData %>%
  group_by(x, y)     %>%
  summarize(Temperature = mean(Temperature), DependentVar = mean(DependentVar))

SpatLM <- lm(DependentVar ~ Temperature, data = MeanData)
sims   <- simulateResiduals(SpatLM)
testSpatialAutocorrelation(sims, x = MeanData$x, y = MeanData$y)

#>
#>  DHARMa Moran's I test for spatial autocorrelation
#>
#> data:  sims
#> observed = -0.45465, expected = -0.20000, sd = 0.19274, p-value =
#> 0.1864
#> alternative hypothesis: Spatial autocorrelation

Created on 2020-02-18 by the reprex package (v0.3.0)


问:
Is there a bug in AWS .Net SDK for getting count of running EC2 instances?
Hi have 1 EC2 instance that is stopped. (Ubuntu Rails App Server (ami-e49e758d)) But when I run a sample from that comes with SDK, it shows me running instance as 1.  Whom should I trust. What I see on AWS Console or sdk sample output?</p>

答: In this case, 'Running' instances as reported by the API means 'Existing' - this is telling you how many instances are actually present (i.e. being 'run' by the Xen hipervisor). You can then interrogate each instance item to determine its' specific activity status (i.e. Stopped, Running, etc).</p>


问:
React - toggle class: useState hook form several button
I have some buttons and I'm trying to add active class for clicked button. But when I click one of the buttons, all buttons are getting active class.

```<code>const { useState } = React;
const { render } = ReactDOM;
const node = document.getElementById("root");

const Button = ({ message }) => {
  const [condition, setCondition] = useState(false);
  return (
    <div>
    {
    Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(!condition)}
     }}
     ))
      }
    </div>
  );
   //Updated
   Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(condition === "off" ? "on" : "off")}
     }}
     ))
      }
    </div>
  ); //This can be modified to work for button clicked. Because active class is added to all buttons, if one of them is clicked
};
render(<Button message="Click me if you dare!" />, node);
</code>```

This is working if I click the first button, but if I click again the same button, this active class should be removed

答:
You need to use a seperate state handler for each button:</p>

```<code>const Button = ({ message }) => {
 const [condition, setCondition] = useState(false);
 const [condition2, setCondition2] = useState(false);
  return (
    <div>
    <div
      onClick={() => setCondition(!condition)}
      className={condition ? "button toggled" : "button"}
    >
      {message}
    </div>
      <div
      onClick={() => setCondition(!condition2)}
      className={condition2 ? "button toggled" : "button"}
    >
      {message}
    </div>
    </div>
  );
};

render(<Button message="Click me if you dare!" />, node);
</code>```

Body:
I have some buttons and I'm trying to add active class for clicked button. But when I click one of the buttons, all buttons are getting active class.

const { useState } = React;
const { render } = ReactDOM;
const node = document.getElementById("root");

const Button = ({ message }) => {
  const [condition, setCondition] = useState(false);
  return (

    {
    Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(!condition)}
     }}
     ))
      }

  );
   //Updated
   Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(condition === "off" ? "on" : "off")}
     }}
     ))
      }

  ); //This can be modified to work for button clicked. Because active class is added to all buttons, if one of them is clicked
};
render(<Button message="Click me if you dare!" />, node);

This is working if I click the first button, but if I click again the same button, this active class should be removed

Body:
You need to use a seperate state handler for each button:

const Button = ({ message }) => {
 const [condition, setCondition] = useState(false);
 const [condition2, setCondition2] = useState(false);
  return (
    <div>
    <div
      onClick={() => setCondition(!condition)}
      className={condition ? "button toggled" : "button"}
    >
      {message}
    </div>
      <div
      onClick={() => setCondition(!condition2)}
      className={condition2 ? "button toggled" : "button"}
    >
      {message}
    </div>
    </div>
  );
};

render(<Button message="Click me if you dare!" />, node);


问:
Nested Masterpages and .FindControl
On one site, I'm only using a single level Masterpage and in a page using that master, I can do this.Master.FindControl("controlName") to access the control.  Works fine.

However, using the same code on a site with two masterpage levels.  MainMaster and SpecificMaster which has MainMaster as its Master.

So on the page which uses SpecificMaster, FindControl is returning null for the object.  The only difference I'm seeing is the nesting of the masterpages.

When I set breakpoint and look at page.Master, it's showing SpecificMaster and SpecificMaster is showing MainMaster as its master correctly, but FindControl is still failing.

When I view source in IE, the control is correctly named, no .NET munging going on.

Any thoughts here?

TIA!

答:
try this</p>

```<code>    string txt = ((TextBox)this.Master.FindControl("ContentIDName").FindControl("TextBox1")).Text;
</code>```

ContentLicense: CC BY-SA 2.5

Title: Nested Masterpages and .FindControl

Body:
try this

    string txt = ((TextBox)this.Master.FindControl("ContentIDName").FindControl("TextBox1")).Text;


问:
%%javascript does not work in Jupyter notebook at windows
In my own computer (Mac) I start like this in the Jupyter Notebook so it has some extensions that I like.

In other computer (Windows 7) it allows me to do that (i dont get any error) but nothing happens.

I searched in the internet and I couldnt find a good solution for this.

Maybe someone can point me in the right direction here

答: Are you sure on your Windows 7 computer, the set of community-contributed extensions is installed? See here for how to install it. Later in that document, you'll also see a couple of ways of how to enable them in a richer way that may provide more informative feedback on your Windows machine, see here. </p>


答:
The quickest way to accomplish this is to pass your image as a query string value. For example:

```<code> // Make the image name safe to include in a URL
 const imageUrl = encodeURIComponent(img.src);

 // Pass the image as a query string value
 window.location.href = `second.html?image=${imageUrl}`;
</code>```

In the JavaScript on second.html, you need to parse the query string to get your image path. See: How can I get query string values in JavaScript?

Title: Passing JS variables/values of variables from a function in a first js file, to a second file

Body:
The quickest way to accomplish this is to pass your image as a query string value. For example:

 // Make the image name safe to include in a URL
 const imageUrl = encodeURIComponent(img.src);

 // Pass the image as a query string value
 window.location.href = `second.html?image=${imageUrl}`;

In the JavaScript on second.html, you need to parse the query string to get your image path. See: How can I get query string values in JavaScript?


问:
How to use Highcharts.setOptions in react-highcharts?
I am using react-highcharts and trying to implement ReactHighstock. My charts are showing 'G' instead of 'B'(billions), to fix this I have to set numericSymbols in Highcharts.setOptions but I am not finding a way on how to implement it.

Thanks

答:
You can define Highcharts.setOptions just before coding the class component.

Demo: https://codesandbox.io/s/highcharts-react-demo-n3mes

```<code>Highcharts.setOptions({
  lang: {
    numericSymbols: ["k", "M", "B", "T", "P", "E"]
  }
});
</code>```

API: https://api.highcharts.com/highcharts/lang.numericSymbols

Body:
You can define Highcharts.setOptions just before coding the class component.

Demo: https://codesandbox.io/s/highcharts-react-demo-n3mes

Highcharts.setOptions({
  lang: {
    numericSymbols: ["k", "M", "B", "T", "P", "E"]
  }
});

API: https://api.highcharts.com/highcharts/lang.numericSymbols


问:
Problem with cross compiling icu
I am trying to cross compile the icu library for the iPhone. I downloaded a configure script wrapper from http://sites.google.com/site/michaelsafyan/coding/articles/iphone
When I execute it, I get the following error message:

```<code>checking wchar.h usability... no
checking wchar.h presence... yes
configure: WARNING: wchar.h: present but cannot be compiled
configure: WARNING: wchar.h:     check for missing prerequisite headers?
configure: WARNING: wchar.h: see the Autoconf documentation
configure: WARNING: wchar.h:     section "Present But Cannot Be Compiled"
configure: WARNING: wchar.h: proceeding with the preprocessor's result
configure: WARNING: wchar.h: in the future, the compiler will take precedence
checking for wchar.h... yes
checking for library containing wcscpy... none required
checking size of wchar_t... 0
configure: error: There is wchar.h but the size of wchar_t is 0
</code>```

Does anyone have a clue how I can fix this?

Thanks in advance

答:
in the platform.h you must define the size of wchar_t to the size of the actual platform. If you dont do this it does not work.

define U_SIZEOF_WCHAR_T 4 // macosx

Manfred

Title: Problem with cross compiling icu

Body:
I am trying to cross compile the icu library for the iPhone. I downloaded a configure script wrapper from http://sites.google.com/site/michaelsafyan/coding/articles/iphone
When I execute it, I get the following error message:

checking wchar.h usability... no
checking wchar.h presence... yes
configure: WARNING: wchar.h: present but cannot be compiled
configure: WARNING: wchar.h:     check for missing prerequisite headers?
configure: WARNING: wchar.h: see the Autoconf documentation
configure: WARNING: wchar.h:     section "Present But Cannot Be Compiled"
configure: WARNING: wchar.h: proceeding with the preprocessor's result
configure: WARNING: wchar.h: in the future, the compiler will take precedence
checking for wchar.h... yes
checking for library containing wcscpy... none required
checking size of wchar_t... 0
configure: error: There is wchar.h but the size of wchar_t is 0

Does anyone have a clue how I can fix this?

Thanks in advance


问:
'Build input file cannot be found' Swift 4.2, Xcode 10.0
I am getting the following error when building in Xcode 10.0 with swift 4.2:

答:
If your file(s) - that couldn't find - icon color is pale. And you right click on it and "Show in Finder" does not open Finder. It means your file name is not same as what you see in the Navigator.

to Solve it, go to where your file exist, and change its name to be same as what you see in the Navigator.


问:
Detect multiple expired Firebase Cloud Messaging Tokens
I'm aware that I can know if a token is expired as it's explained in Google Documentation:

https://developers.google.com/instance-id/reference/server#get_information_about_app_instances

The problem is that I have hundreds of tokens and I want to know every week if any of them is expired. Sending a request for every single token will not be really good. Is there anyway to send one single request with an array of those tokens or anything similar? Thanks!

答:
The common way to deal with expired tokens is to remove them when you get a "token expired" response when trying to send a message to them. And since you can send a message to many tokens at once, there is no need to perform a separate call for each token.

For a good example of how to do this, see this snippet from the Cloud Functions example of using FCM through the Admin SDK:

```<code> // Listing all tokens as an array.
  tokens = Object.keys(tokensSnapshot.val());
  // Send notifications to all tokens.
  const response = await admin.messaging().sendToDevice(tokens, payload);
  // For each message check if there was an error.
  const tokensToRemove = [];
  response.results.forEach((result, index) => {
    const error = result.error;
    if (error) {
      console.error('Failure sending notification to', tokens[index], error);
      // Cleanup the tokens who are not registered anymore.
      if (error.code === 'messaging/invalid-registration-token' ||
          error.code === 'messaging/registration-token-not-registered') {
        tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
      }
    }
  });
  return Promise.all(tokensToRemove);
</code>```

Body:
The common way to deal with expired tokens is to remove them when you get a "token expired" response when trying to send a message to them. And since you can send a message to many tokens at once, there is no need to perform a separate call for each token.

For a good example of how to do this, see this snippet from the Cloud Functions example of using FCM through the Admin SDK:

 // Listing all tokens as an array.
  tokens = Object.keys(tokensSnapshot.val());
  // Send notifications to all tokens.
  const response = await admin.messaging().sendToDevice(tokens, payload);
  // For each message check if there was an error.
  const tokensToRemove = [];
  response.results.forEach((result, index) => {
    const error = result.error;
    if (error) {
      console.error('Failure sending notification to', tokens[index], error);
      // Cleanup the tokens who are not registered anymore.
      if (error.code === 'messaging/invalid-registration-token' ||
          error.code === 'messaging/registration-token-not-registered') {
        tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
      }
    }
  });
  return Promise.all(tokensToRemove);


问:
merge and update not present values
I am trying to merge two dataframes such that if any not columns present in df1's variables source should take from df2's rows. I tried the merge below but no works. Please help.

```<code>df1 <- data.frame(source = c("Pr1", "Pr2","Pr3"),
                     date = c("Jan 2018","Feb 2018","Mar 2018"),
                     Freq = c(100,20,30))
df2 <- data.frame(source = c("Pr1","Pr2","Pr1"),
                     date = c("Sep 2018","Aug 2018","Jan 2018"),
                     Freq = c(0,0,0))

df <- merge(df1,df2,by = c("source","date"))
</code>```

Expected Output:

```<code>  source     date Freq
1    Pr1 Jan 2018  100
2    Pr2 Feb 2018   20
3    Pr3 Mar 2018   30
4    Pr1 Sep 2018    0
5    Pr2 Aug 2018    0
</code>```

答:
A full join is required</p>

```<code>df3 <- merge(df1, df2, by = c("source", "date"), all = TRUE, suffixes = c("", ".y"))
df3$Freq[is.na(df3$Freq)] <- df3$Freq.y[is.na(df3$Freq)]

  source     date Freq Freq.y
1    Pr1 Jan 2018  100      0
2    Pr1 Sep 2018    0      0
3    Pr2 Feb 2018   20     NA
4    Pr2 Aug 2018    0      0
5    Pr3 Mar 2018   30     NA
</code>```

Title: merge and update not present values

Body:
I am trying to merge two dataframes such that if any not columns present in df1's variables source should take from df2's rows. I tried the merge below but no works. Please help.

df1 <- data.frame(source = c("Pr1", "Pr2","Pr3"),
                     date = c("Jan 2018","Feb 2018","Mar 2018"),
                     Freq = c(100,20,30))
df2 <- data.frame(source = c("Pr1","Pr2","Pr1"),
                     date = c("Sep 2018","Aug 2018","Jan 2018"),
                     Freq = c(0,0,0))

df <- merge(df1,df2,by = c("source","date"))

Expected Output:

  source     date Freq
1    Pr1 Jan 2018  100
2    Pr2 Feb 2018   20
3    Pr3 Mar 2018   30
4    Pr1 Sep 2018    0
5    Pr2 Aug 2018    0

Body:
A full join is required

df3 <- merge(df1, df2, by = c("source", "date"), all = TRUE, suffixes = c("", ".y"))
df3$Freq[is.na(df3$Freq)] <- df3$Freq.y[is.na(df3$Freq)]

  source     date Freq Freq.y
1    Pr1 Jan 2018  100      0
2    Pr1 Sep 2018    0      0
3    Pr2 Feb 2018   20     NA
4    Pr2 Aug 2018    0      0
5    Pr3 Mar 2018   30     NA


问:
Return column name if result is true
I've got an Excel file that I need to manipulate in SQL. I've imported the file but need to show the primary key (MI_KEY) and the column name where the result is true/1.

My table is laid out like the below:

```<code>MI_KEY          TEST_1_FIELD          TEST_2_FIELD          TEST_3_FIELD          TEST_4_FIELD
123bg-fd23           1                     1                     0                     0
2873g-fht5           0                     0                     0                     0
23jdd-sd43           1                     0                     1                     1
23jfk-4kff           0                     1                     1                     1
</code>```

I want to return the MI_KEY and the column name where the result is true, for example;

```<code>  MI_KEY           ISSUE
123bg-fd23      TEST_1_FIELD
123bg-fd23      Test_2_FIELD
23jdd-sd43      TEST_1_FIELD
23jdd-sd43      TEST_3_FIELD
23jdd-sd43      TEST_4_FIELD
23jfk-4kff      TEST_2_FIELD
23jfk-4kff      TEST_3_FIELD
23jfk-4kff      TEST_4_FIELD
</code>```

It's probably important to let you know that this will need to be dynamic as different files could have different header names so I don't want to hard code if it can be helped.

答:
Using union all

```<code>select MI_KEYINT MI_KEY, "TEST_1_FIELD" as ISSUE from test_db.test_5 where  TEST_1_FIELD = 1
union all select MI_KEYINT MI_KEY, "TEST_2_FIELD" as ISSUE from test_db.test_5 where TEST_2_FIELD = 1
union all select MI_KEYINT MI_KEY, "TEST_3_FIELD"  as ISSUE from test_db.test_5 where TEST_3_FIELD = 1
union all select MI_KEYINT MI_KEY, "TEST_4_FIELD"  as ISSUE from test_db.test_5 where TEST_4_FIELD = 1
</code>```

Result

```<code>MI_KEY    |ISSUE       |
----------|------------|
123bg-fd23|TEST_1_FIELD|
23jdd-sd43|TEST_1_FIELD|
123bg-fd23|TEST_2_FIELD|
23jfk-4kff|TEST_2_FIELD|
23jdd-sd43|TEST_3_FIELD|
23jfk-4kff|TEST_3_FIELD|
23jdd-sd43|TEST_4_FIELD|
23jfk-4kff|TEST_4_FIELD|
</code>```

If it is to be dynamic then i assume your db creates a new column every time a field comes with a new column name, hence complexity

Title: Return column name if result is true

Body:
I've got an Excel file that I need to manipulate in SQL. I've imported the file but need to show the primary key (MI_KEY) and the column name where the result is true/1.

My table is laid out like the below:

MI_KEY          TEST_1_FIELD          TEST_2_FIELD          TEST_3_FIELD          TEST_4_FIELD
123bg-fd23           1                     1                     0                     0
2873g-fht5           0                     0                     0                     0
23jdd-sd43           1                     0                     1                     1
23jfk-4kff           0                     1                     1                     1

I want to return the MI_KEY and the column name where the result is true, for example;

  MI_KEY           ISSUE
123bg-fd23      TEST_1_FIELD
123bg-fd23      Test_2_FIELD
23jdd-sd43      TEST_1_FIELD
23jdd-sd43      TEST_3_FIELD
23jdd-sd43      TEST_4_FIELD
23jfk-4kff      TEST_2_FIELD
23jfk-4kff      TEST_3_FIELD
23jfk-4kff      TEST_4_FIELD

It's probably important to let you know that this will need to be dynamic as different files could have different header names so I don't want to hard code if it can be helped.

Body:
Using union all

select MI_KEYINT MI_KEY, "TEST_1_FIELD" as ISSUE from test_db.test_5 where  TEST_1_FIELD = 1
union all select MI_KEYINT MI_KEY, "TEST_2_FIELD" as ISSUE from test_db.test_5 where TEST_2_FIELD = 1
union all select MI_KEYINT MI_KEY, "TEST_3_FIELD"  as ISSUE from test_db.test_5 where TEST_3_FIELD = 1
union all select MI_KEYINT MI_KEY, "TEST_4_FIELD"  as ISSUE from test_db.test_5 where TEST_4_FIELD = 1

Result

MI_KEY    |ISSUE       |
----------|------------|
123bg-fd23|TEST_1_FIELD|
23jdd-sd43|TEST_1_FIELD|
123bg-fd23|TEST_2_FIELD|
23jfk-4kff|TEST_2_FIELD|
23jdd-sd43|TEST_3_FIELD|
23jfk-4kff|TEST_3_FIELD|
23jdd-sd43|TEST_4_FIELD|
23jfk-4kff|TEST_4_FIELD|

If it is to be dynamic then i assume your db creates a new column every time a field comes with a new column name, hence complexity


问:
ASP.NET MVC: Reuse of View by two controller actions
'Add' and 'Edit' views are typically more or less identical. How can I reuse a View so that Foos/Add and Foos/Edit/[Id] both use it? What would the actions look like?

Thanks

答:
I would use jQuery ajax. Clicking on Add or Edit would call serve action which will return the same PartialView (if you want to reuse it).
Then, in the success function of ajax call, you have just to put returned html (from that PartialView) into certain part of your page (or popup).

Nice and clean and no page reload...