问:
Angular 2 Animation - boolean trigger
I have a form with one field and if that field is incorrect I want to shake it using animations

```<code><form [formGroup]="subscribeFormGroup">
    <mat-form-field [@error]="isError" class="al-subscribe-form-field">
            <input formControlName="email" matInput type="email">
            <mat-icon class="al-subscribe-icon" svgIcon="mail" (click)="onSubscribeClick()"></mat-icon>
    </mat-form-field>
</form>

animations: [
    trigger('error', [
        transition('false <=> true', useAnimation(shake)),
    ]),
],

public onSubscribeClick(): void {
        if (this.subscribeFormGroup.invalid) {
            this.isError = true;
        }
    ...
}
</code>```

Now it triggers only at first time when I try to send incorrect data, if I click button the second time etc, the field is not shaking

答:
Another way -better than setTimeout- is use the animation callback done</p>

```<code><mat-form-field [@error]="isError"
                (@error.done)="isError = false"
                class="al-subscribe-form-field">
...
</mat-form>
</code>```

Title: Angular 2 Animation - boolean trigger

Body:
I have a form with one field and if that field is incorrect I want to shake it using animations

<form [formGroup]="subscribeFormGroup">
    <mat-form-field [@error]="isError" class="al-subscribe-form-field">
            <input formControlName="email" matInput type="email">
            <mat-icon class="al-subscribe-icon" svgIcon="mail" (click)="onSubscribeClick()"></mat-icon>
    </mat-form-field>
</form>

animations: [
    trigger('error', [
        transition('false <=> true', useAnimation(shake)),
    ]),
],

public onSubscribeClick(): void {
        if (this.subscribeFormGroup.invalid) {
            this.isError = true;
        }
    ...
}

Now it triggers only at first time when I try to send incorrect data, if I click button the second time etc, the field is not shaking

Body:
Another way -better than setTimeout- is use the animation callback done

<mat-form-field [@error]="isError"
                (@error.done)="isError = false"
                class="al-subscribe-form-field">
...
</mat-form>


来源: stackexchange

问:
Combining graphs: is there a TensorFlow import_graph_def equivalent for C++?
I need to extend exported models with a custom input and output layer. I have found out this can easily be done with:

```<code>with tf.Graph().as_default() as g1: # actual model
    in1 = tf.placeholder(tf.float32,name="input")
    ou1 = tf.add(in1,2.0,name="output")
with tf.Graph().as_default() as g2: # model for the new output layer
    in2 = tf.placeholder(tf.float32,name="input")
    ou2 = tf.add(in2,2.0,name="output")

gdef_1 = g1.as_graph_def()
gdef_2 = g2.as_graph_def()

with tf.Graph().as_default() as g_combined: #merge together
    x = tf.placeholder(tf.float32, name="actual_input") # the new input layer

    # Import gdef_1, which performs f(x).
    # "input:0" and "output:0" are the names of tensors in gdef_1.
    y, = tf.import_graph_def(gdef_1, input_map={"input:0": x},
                             return_elements=["output:0"])

    # Import gdef_2, which performs g(y)
    z, = tf.import_graph_def(gdef_2, input_map={"input:0": y},
                             return_elements=["output:0"])

sess = tf.Session(graph=g_combined)

print "result is: ", sess.run(z, {"actual_input:0":5}) #result is: 9
</code>```

this works fine.

However instead of passing a dataset in arbitrary shape, I need to give a pointer as network input. The problem is, I can't think of any solution for this inside python (defining and passing a pointer), and when developing a network with the C++ Api I can't find an equivalent to the tf.import_graph_def function.

Does this have a different name in C++ or is there an other way to merge two graphs/models in C++?

Thanks for any advice

答:
This can be achieved in C++ by directly manipulating the NodeDefs in the GraphDefs of the two Graphs to be combined.  The basic algorithm is to define the two GraphDefs, using Placeholders for the inputs to the second GraphDef and redirect them to the outputs from the first GraphDef.  This would be analogous to combining two electric circuits in series by connecting the inputs of the second circuit to the outputs of the first circuit.

First, the sample GraphDefs are defined, as well as a utility for observing the internals of the GraphDefs.  It is important to note that all nodes from both GraphDefs must have unique names.

```<code>Status Panel::SampleFirst(GraphDef *graph_def)
{
    Scope root = Scope::NewRootScope();
    Placeholder p1(root.WithOpName("p1"), DT_INT32);
    Placeholder p2(root.WithOpName("p2"), DT_INT32);
    Add add(root.WithOpName("add"), p1, p2);
    return root.ToGraphDef(graph_def);
}

Status Panel::SampleSecond(GraphDef *graph_def)
{
    Scope root = Scope::NewRootScope();
    Placeholder q1(root.WithOpName("q1"), DT_INT32);
    Placeholder q2(root.WithOpName("q2"), DT_INT32);
    Add sum(root.WithOpName("sum"), q1, q2);
    Multiply multiply(root.WithOpName("multiply"), sum, 4);
    return root.ToGraphDef(graph_def);
}

void Panel::ShowGraphDef(GraphDef &graph_def)
{
    for (int i = 0; i < graph_def.node_size(); i++) {
        NodeDef node_def = graph_def.node(i);
        cout << "NodeDef name is " << node_def.name() << endl;
        cout << "NodeDef op is " << node_def.op() << endl;
        for (const string& input : node_def.input()) {
            cout << "\t input: " << input << endl;
        }
    }
}
</code>```

Now the two GraphDefs are created and the inputs of the second GraphDef are connected to the outputs of the first GraphDef.  This is done by iterating over the nodes and identifying the first operational node, whose inputs are the Placeholders, and redirecting those inputs to the outputs of the first GraphDef.  The node is then added to the first GraphDef, as well as all subsequent nodes.  The result is the first GraphDef appended by the second GraphDef.

```<code>Status Panel::Append(vector<Tensor> *outputs)
{
    GraphDef graph_def_first;
    GraphDef graph_def_second;
    TF_RETURN_IF_ERROR(SampleFirst(&graph_def_first));
    TF_RETURN_IF_ERROR(SampleSecond(&graph_def_second));

    for (int i = 0; i < graph_def_second.node_size(); i++) {
        NodeDef node_def = graph_def_second.node(i);
        if (node_def.name() == "sum") {
            node_def.set_input(0, "p1");
            node_def.set_input(1, "add");
        }
        *graph_def_first.add_node() = node_def;
    }

    ShowGraphDef(graph_def_first);

    unique_ptr<Session> session(NewSession(SessionOptions()));
    TF_RETURN_IF_ERROR(session->Create(graph_def_first));

    Tensor t1(2);
    Tensor t2(3);
    vector<pair<string, Tensor>> inputs = {{"p1", t1}, {"p2", t2}};

    TF_RETURN_IF_ERROR(session->Run(inputs, {"multiply"}, {}, outputs));

    return Status::OK();
}
</code>```

This particular Graph will take two inputs, 2 and 3, and Add them together.  Then the sum of that (5) will be added again to the first input (2), then Multiply by 4 to obtain the result of 28.  ((2+3) + 2) * 4 = 28.

ContentLicense: CC BY-SA 3.0

Body:
I need to extend exported models with a custom input and output layer. I have found out this can easily be done with:

with tf.Graph().as_default() as g1: # actual model
    in1 = tf.placeholder(tf.float32,name="input")
    ou1 = tf.add(in1,2.0,name="output")
with tf.Graph().as_default() as g2: # model for the new output layer
    in2 = tf.placeholder(tf.float32,name="input")
    ou2 = tf.add(in2,2.0,name="output")

gdef_1 = g1.as_graph_def()
gdef_2 = g2.as_graph_def()

with tf.Graph().as_default() as g_combined: #merge together
    x = tf.placeholder(tf.float32, name="actual_input") # the new input layer

    # Import gdef_1, which performs f(x).
    # "input:0" and "output:0" are the names of tensors in gdef_1.
    y, = tf.import_graph_def(gdef_1, input_map={"input:0": x},
                             return_elements=["output:0"])

    # Import gdef_2, which performs g(y)
    z, = tf.import_graph_def(gdef_2, input_map={"input:0": y},
                             return_elements=["output:0"])

sess = tf.Session(graph=g_combined)

print "result is: ", sess.run(z, {"actual_input:0":5}) #result is: 9

this works fine.

However instead of passing a dataset in arbitrary shape, I need to give a pointer as network input. The problem is, I can't think of any solution for this inside python (defining and passing a pointer), and when developing a network with the C++ Api I can't find an equivalent to the tf.import_graph_def function.

Does this have a different name in C++ or is there an other way to merge two graphs/models in C++?

Thanks for any advice

Body:
This can be achieved in C++ by directly manipulating the NodeDefs in the GraphDefs of the two Graphs to be combined.  The basic algorithm is to define the two GraphDefs, using Placeholders for the inputs to the second GraphDef and redirect them to the outputs from the first GraphDef.  This would be analogous to combining two electric circuits in series by connecting the inputs of the second circuit to the outputs of the first circuit.

First, the sample GraphDefs are defined, as well as a utility for observing the internals of the GraphDefs.  It is important to note that all nodes from both GraphDefs must have unique names.

Status Panel::SampleFirst(GraphDef *graph_def)
{
    Scope root = Scope::NewRootScope();
    Placeholder p1(root.WithOpName("p1"), DT_INT32);
    Placeholder p2(root.WithOpName("p2"), DT_INT32);
    Add add(root.WithOpName("add"), p1, p2);
    return root.ToGraphDef(graph_def);
}

Status Panel::SampleSecond(GraphDef *graph_def)
{
    Scope root = Scope::NewRootScope();
    Placeholder q1(root.WithOpName("q1"), DT_INT32);
    Placeholder q2(root.WithOpName("q2"), DT_INT32);
    Add sum(root.WithOpName("sum"), q1, q2);
    Multiply multiply(root.WithOpName("multiply"), sum, 4);
    return root.ToGraphDef(graph_def);
}

void Panel::ShowGraphDef(GraphDef &graph_def)
{
    for (int i = 0; i < graph_def.node_size(); i++) {
        NodeDef node_def = graph_def.node(i);
        cout << "NodeDef name is " << node_def.name() << endl;
        cout << "NodeDef op is " << node_def.op() << endl;
        for (const string& input : node_def.input()) {
            cout << "\t input: " << input << endl;
        }
    }
}

Now the two GraphDefs are created and the inputs of the second GraphDef are connected to the outputs of the first GraphDef.  This is done by iterating over the nodes and identifying the first operational node, whose inputs are the Placeholders, and redirecting those inputs to the outputs of the first GraphDef.  The node is then added to the first GraphDef, as well as all subsequent nodes.  The result is the first GraphDef appended by the second GraphDef.

Status Panel::Append(vector<Tensor> *outputs)
{
    GraphDef graph_def_first;
    GraphDef graph_def_second;
    TF_RETURN_IF_ERROR(SampleFirst(&graph_def_first));
    TF_RETURN_IF_ERROR(SampleSecond(&graph_def_second));

    for (int i = 0; i < graph_def_second.node_size(); i++) {
        NodeDef node_def = graph_def_second.node(i);
        if (node_def.name() == "sum") {
            node_def.set_input(0, "p1");
            node_def.set_input(1, "add");
        }
        *graph_def_first.add_node() = node_def;
    }

    ShowGraphDef(graph_def_first);

    unique_ptr<Session> session(NewSession(SessionOptions()));
    TF_RETURN_IF_ERROR(session->Create(graph_def_first));

    Tensor t1(2);
    Tensor t2(3);
    vector<pair<string, Tensor>> inputs = {{"p1", t1}, {"p2", t2}};

    TF_RETURN_IF_ERROR(session->Run(inputs, {"multiply"}, {}, outputs));

    return Status::OK();
}

This particular Graph will take two inputs, 2 and 3, and Add them together.  Then the sum of that (5) will be added again to the first input (2), then Multiply by 4 to obtain the result of 28.  ((2+3) + 2) * 4 = 28.

ContentLicense: CC BY-SA 4.0


问:
How to group by a formatted string field?
I have an issue that want your help . Following is my issue :
I have a table

```<code>id     | total
1_2    |  12
1_2_3  |  13
1_2    |  14
1_2_5  |  14
1_1_1  |  14
</code>```

Normal group by id will result

```<code>SELECT id , sum(total)                        id    | total
FROM mybucket                    ->           1_2   | 26
GROUP BY id                                   1_2_3 | 13
                                              1_2_5 | 14
                                              1_1_1 | 14
</code>```

But i want group by id that format field id . Example i split 1_2_3 to 1_2 and 1_2_4 to 1_2
And final result

```<code>    id    | total
    1_2   | 26 +13+14 = 43
    1_1_1 | 14
</code>```

How can I group by such method?

答:
Assume you want group until second underscore. You get two groups 1_2, 1_1 (NOT 1_1_1)</p>

```<code>SELECT nid AS id, SUM(total) AS total
FROM mybucket
LET nid = CASE WHEN ARRAY_LENGTH(SPLIT(id, "_")) > 2 THEN CONCAT(SPLIT(id, "_")[0],"_",SPLIT(id, "_")[1]) ELSE id END;
GROUP BY nid ;
</code>```

Body:
I have an issue that want your help . Following is my issue :
I have a table

id     | total
1_2    |  12
1_2_3  |  13
1_2    |  14
1_2_5  |  14
1_1_1  |  14

Normal group by id will result

SELECT id , sum(total)                        id    | total
FROM mybucket                    ->           1_2   | 26
GROUP BY id                                   1_2_3 | 13
                                              1_2_5 | 14
                                              1_1_1 | 14

But i want group by id that format field id . Example i split 1_2_3 to 1_2 and 1_2_4 to 1_2
And final result

    id    | total
    1_2   | 26 +13+14 = 43
    1_1_1 | 14

How can I group by such method?

Body:
Assume you want group until second underscore. You get two groups 1_2, 1_1 (NOT 1_1_1)

SELECT nid AS id, SUM(total) AS total
FROM mybucket
LET nid = CASE WHEN ARRAY_LENGTH(SPLIT(id, "_")) > 2 THEN CONCAT(SPLIT(id, "_")[0],"_",SPLIT(id, "_")[1]) ELSE id END;
GROUP BY nid ;


问:
Add an Intro page to exam in R/exams
I am using R/exams to generate Moodle exams (Thanks Achim and team). I would like to make an introductory page to set the scenario for the exam. Is there a way to do it? (Now, I am generating a schoice with answerlist blank.)
Thanks!
João Marôco

答:
Usually, I wouldn't do this "inside" the exam but "outside". In Moodle you can include a "Description" in the "General Settings" when editing the quiz. This is where I would put all the general information so that students read this before starting with the actual questions.

If you want to include R-generated content (R output, graphics, data, ...) in this description I would usually include this in "Question 1" rather than as a "Question 0" without any actual questions.

The "description" question type could be used for the latter, though. However, it is currently not supported in exams2moodle() (I'll put it on the wishlist). You could manually work around this in the following steps:

Create a string question with the desired content and set the associated expoints to 0.

Generate the Moodle XML output as usual with exams2moodle().

Open the XML file in a text editor or simply within RStudio and replace <question type="shortanswer"> with <question type="description"> for the relevant questions.

In the XML file omit the <answer>...</answer> for the relevant questions.

Caveat: As you are aware it is technically possible to share the same data across subsequent exercises within the same exam. If .Rnw exercises are used, all variables from the exercises are created in the global environment (.GlobalEnv) and can be easily accessed anyway. If .Rmd exercises are used, it is necessary to set the envir argument to a dedicated shared environment (e.g., .GlobalEnv or a new.env()) in exams2moodle(..., envir = ...). However, if this is done then no random exercises must be drawn in Moodle because this would break up the connections between the exercises (i.e., the first replication in Question 1 is not necessarily followed by by the first replication in Question 2). Instead you have to put together tests with a fixed selection of exercises (i.e., always the first replication for all questions or the second replication for all questions, ...).

Title: Add an Intro page to exam in R/exams


问:
symfony 5 - disable subscriber
I am using bugsnag in a symfony 5 project to keep track of exeptions. I also use symfony messenger with rabbit for heavy processing.

Everything works fine overall, except the fact that in some cases, inside a messenger middleware (RejectRedeliveredMessageMiddleware) an exception is thrown in some particular cases in order to trigger a message reque while avoiding a possible infinite loop (RejectRedeliveredMessageException).

The exception should be there, and the behavior is correct. For example if a process stopped unexpectedly (a hard reboot or a kill), the message is requed. The logic works well, autorecovery works perfectly.

The only problem is that bugsnag registers itself as a subscriber for all kernel events, treated or not (code below)

```<code>$listeners = [
    KernelEvents::REQUEST => ['onKernelRequest', 256],
    KernelEvents::EXCEPTION => ['onKernelException', 128],
</code>```

];

Normally exceptions are caught in our app before getting to the general event dispatcher and so they are not reported if they shouldn't. But, because that is in the middleware, and an event is risen it gets reported even though is already treated by the autoretry mechanism and because of that it generates a lot of noise and fake positives.

What I would need to do is unsubscribe for a particular event, but since I can't touch the 3rd party code (bugsnag and messenger) I can't find a way to do it.

Is there a way to programatically remove an event from a subscriber?

答: Inject EventDispatcherInterface and use removeSubscriber() method. You can do this in you custom middleware https://symfony.com/doc/current/messenger.html#middleware

Title: symfony 5 - disable subscriber

Body:
I am using bugsnag in a symfony 5 project to keep track of exeptions. I also use symfony messenger with rabbit for heavy processing.

Everything works fine overall, except the fact that in some cases, inside a messenger middleware (RejectRedeliveredMessageMiddleware) an exception is thrown in some particular cases in order to trigger a message reque while avoiding a possible infinite loop (RejectRedeliveredMessageException).

The exception should be there, and the behavior is correct. For example if a process stopped unexpectedly (a hard reboot or a kill), the message is requed. The logic works well, autorecovery works perfectly.

The only problem is that bugsnag registers itself as a subscriber for all kernel events, treated or not (code below)

$listeners = [
    KernelEvents::REQUEST => ['onKernelRequest', 256],
    KernelEvents::EXCEPTION => ['onKernelException', 128],

];

Normally exceptions are caught in our app before getting to the general event dispatcher and so they are not reported if they shouldn't. But, because that is in the middleware, and an event is risen it gets reported even though is already treated by the autoretry mechanism and because of that it generates a lot of noise and fake positives.

What I would need to do is unsubscribe for a particular event, but since I can't touch the 3rd party code (bugsnag and messenger) I can't find a way to do it.

Is there a way to programatically remove an event from a subscriber?


问:
MySQL licensing and GPL
As far as I know, when I build a desktop/server app using any GPL code like MySQL I will have to release the source code of my software under the GPL.

If I want to develop a web-app using MySQL, my code will link against the MySQL libraries. Must I release the sourcecode of my webapp in this situation to be in accordance with the GPL?

答:
First, I am not a lawyer. Talk with one before taking any advice here.

Beyond that, if you do not distribute your web app, you likely do not need to release your changes. You can still make your web app available to be used by others if you host the web app.

ContentLicense: CC BY-SA 2.5

Title: MySQL licensing and GPL

LastEditorDisplayName: Roger Pate

OwnerDisplayName: Scott Bevington


问:
WS in TIBCO BW or in Java
I see it is a lot faster developing a WS in TIBCO compared to coding in Java.

Is it wise investment to use TIBCO as your WS Service Provider & Service Requester?

Also both previous question for developing a JMS consumer & publisher.

How would my Server-side Java code use/listen to the BW Process? So far I read about TIBCO Adapters to do that with a lot of features like monitoring, but would this be just an overhead? Is it better to just code your WS & JMS codes in your Java app?

How do you decide if you would implement a functionality in Java or in TIBCO (e.g. send a Mail, Logging, etc.)?

Thanks a lot!
Thirdy

答:
Using TIBCO Business Works to implement your SOAP Web Services and to invoke SOAP Web Services will certainly save you a lot of time compared to creating them in Java.

Whether it's a "wise investment" really depends on the amount of development your doing. The TIBCO BW licenses are not cheap, but with a large development team and a large body of development work, you can get a return on investment very quickly. If you've got just one project and only a couple of developers, you might not see a return on investment (i.e., the license cost could be more than the cost of developing the project in Java).

Your Server-side Java code would use/listen to BW by simply invoking the web services. Axis 2 will make your life easier in this regard.

In terms of deciding what you would develop in Java and what you would develop in TIBCO BW, I would answer everything you can in TIBCO BW, with some custom java where you need it. BW is Java based, so it's trivially easy to add Java code to any project.

Title: WS in TIBCO BW or in Java


问:
Chrome Driver and version Chrome version83
I have been trying to scrape some information for google when I have got this error:

```<code>SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 80
</code>```

I would have two questions:

is there any chance to have a new version of driver = webdriver.Chrome that can work with this new version?

and/or

is there any chance to downgrade Google Chrome?

This is the module that I am currently using:

```<code>driver = webdriver.Chrome('path/chromedriver')
driver.get('https://www.google.com')
</code>```

答:
So this issue appears because there is an inconsistency between versions of chrome and ChromeDriver.
First thing I suggest is checking your chrome version by going to Help -> About Google Chrome and check the version. So let's say it's 83.something

Then download the Chrome Webdriver with the appropriate version here Download ChromeDriver and you should be good to go.

Hope this helped!

Body:
I have been trying to scrape some information for google when I have got this error:

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 80

I would have two questions:

is there any chance to have a new version of driver = webdriver.Chrome that can work with this new version?

and/or

is there any chance to downgrade Google Chrome?

This is the module that I am currently using:

driver = webdriver.Chrome('path/chromedriver')
driver.get('https://www.google.com')


问:
Why am I getting this? "NameError: name 'Response' is not defined"
I'm trying to get data from another of my servers. The other server is just an html file with "Hello World" I can reach my homepage fine, but when I go to /farmdata, I get this error:

NameError: name 'Response' is not defined"

```<code>from flask import Flask, render_template
import requests

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/farmdata')
def farmdata():
    r = requests.get('http://74.114.75.91:8080')
    r.url
    r.encoding
    return Response(
        r.text,
        status=r.status_code,
        content_type=r.headers['content-type'],
    )

if __name__== '__main__':
    app.run(debug=True, port=80, host='0.0.0.0')
</code>```

Edit - to anyone else with the problem, this was the solution.

```<code>from flask import Flask, render_template, Response
</code>```

答: Is there not a " ," too much before closing the brackets of the response?</p>

Body:
I'm trying to get data from another of my servers. The other server is just an html file with "Hello World" I can reach my homepage fine, but when I go to /farmdata, I get this error:

NameError: name 'Response' is not defined"

from flask import Flask, render_template
import requests

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/farmdata')
def farmdata():
    r = requests.get('http://74.114.75.91:8080')
    r.url
    r.encoding
    return Response(
        r.text,
        status=r.status_code,
        content_type=r.headers['content-type'],
    )

if __name__== '__main__':
    app.run(debug=True, port=80, host='0.0.0.0')

Edit - to anyone else with the problem, this was the solution.

from flask import Flask, render_template, Response


问:
Log failed login attempts with Laravel 5.2
How would I log failed login attempts with laravel 5.2 I have the auth scaffolding installed.

I have added the following to my EventsServiceProvider.php

```<code> protected $listen = [
    'Illuminate\Auth\Events\Attempting' => [
        'App\Listeners\LogAuthenticationAttempt',
    ],

    'Illuminate\Auth\Events\Login' => [
        'App\Listeners\LogSuccessfulLogin',
    ],

    'Illuminate\Auth\Events\Logout' => [
        'App\Listeners\LogSuccessfulLogout',
    ],

    'Illuminate\Auth\Events\Lockout' => [
        'App\Listeners\LogLockout',
    ],
];
</code>```

And in my app/Listeners/LogAuthenticationAttempt.php

I have

```<code>    $log = new Access_Log();
    $log->ip_address = Request::getClientIp();
    $log->is_success = 0;
    $log->save();
</code>```

But this just logs that an login attempt has been made> I can log a successful login attempt using the LogSuccessfulLogin Listener but I cant see how to log a failed login attempt.

It has occurred to me that I could just update the is_success value on the log entry in the LogSuccessfulLogin Listener but what can I use to persist between LogAuthenticationAttempt and LogSuccessfulLogin to identify this as the same login attempt?

答:
You have to first check if the user exists, e.g if($event->user != null){
...then log
}</p>

Body:
How would I log failed login attempts with laravel 5.2 I have the auth scaffolding installed.

I have added the following to my EventsServiceProvider.php

 protected $listen = [
    'Illuminate\Auth\Events\Attempting' => [
        'App\Listeners\LogAuthenticationAttempt',
    ],

    'Illuminate\Auth\Events\Login' => [
        'App\Listeners\LogSuccessfulLogin',
    ],

    'Illuminate\Auth\Events\Logout' => [
        'App\Listeners\LogSuccessfulLogout',
    ],

    'Illuminate\Auth\Events\Lockout' => [
        'App\Listeners\LogLockout',
    ],
];

And in my app/Listeners/LogAuthenticationAttempt.php

I have

    $log = new Access_Log();
    $log->ip_address = Request::getClientIp();
    $log->is_success = 0;
    $log->save();

But this just logs that an login attempt has been made> I can log a successful login attempt using the LogSuccessfulLogin Listener but I cant see how to log a failed login attempt.

It has occurred to me that I could just update the is_success value on the log entry in the LogSuccessfulLogin Listener but what can I use to persist between LogAuthenticationAttempt and LogSuccessfulLogin to identify this as the same login attempt?


问:
Get month name from number
How can I get the month name from the month number?

For instance, if I have 3, I want to return march

```<code>date.tm_month()
</code>```

How to get the string march?

答:
Some good answers already make use of calendar but the effect of setting the locale hasn't been mentioned yet.

Calendar set month names according to the current locale, for exemple in French:

import locale
import calendar

locale.setlocale(locale.LC_ALL, 'fr_FR')

assert calendar.month_name[1] == 'janvier'
assert calendar.month_abbr[1] == 'jan'
```

If you plan on using setlocale in your code, make sure to read the tips and caveats and extension writer sections from the documentation. The example shown here is not representative of how it should be used. In particular, from these two sections:

It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program […]

Extension modules should never call setlocale() […]

Title: Get month name from number

Body:
How can I get the month name from the month number?

For instance, if I have 3, I want to return march

date.tm_month()

How to get the string march?

Body:
Some good answers already make use of calendar but the effect of setting the locale hasn't been mentioned yet.

Calendar set month names according to the current locale, for exemple in French:

import locale
import calendar

locale.setlocale(locale.LC_ALL, 'fr_FR')

assert calendar.month_name[1] == 'janvier'
assert calendar.month_abbr[1] == 'jan'

If you plan on using setlocale in your code, make sure to read the tips and caveats and extension writer sections from the documentation. The example shown here is not representative of how it should be used. In particular, from these two sections:

It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program […]

Extension modules should never call setlocale() […]


问:
Trouble Installing Selenium RC Java Client Driver
I'm trying to set up Selenium RC with Eclipse, but when I download the .zip from the Selenium HQ website it comes with several files included. Which is the Java Client Driver that I need to include in my project?</p>

答: The client driver is selenium-java-2.0b3.jar if you are using the one that is on the SeleniumHQ site. I'd recommend downloading the release candidate here, which is a more recent version. (It probably hasn't made it to the main site yet because it was uploaded only 4 hours ago.)


问:
Gray square around disabled radio button
buttons on IEI have created radio buttons in ASP.NET using bootstrap.  These buttons are supposed to be disabled which works fine in chrome but in Internet explorer, it creates a gray square around the buttons.  I've been able to get it removed on IE by wrapping the input tag with a div disabled tag.  However, this does not work in chrome.  So I can't get one to work without messing up the other.  The code I have included is the one that works with chrome.

input[disabled] {
    cursor: not-allowed;
    background-color: #cfcfcf;
}

input[type="radio"], input[type="checkbox"] {
    box-sizing: border-box;
    padding: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-check">
       <input disabled="disabled" checked="checked" class="form-check-input" id="Male" name="GenderSelection" type="radio" value="Y">
       </div>
        <label for="Male">Male</label></code>```

]2

答:
the issue is with the css.

```<code>input[disabled] {background-color:#cfcfcf;}
</code>```

remove that and it works.

Thanks!

Body:
buttons on IEI have created radio buttons in ASP.NET using bootstrap.  These buttons are supposed to be disabled which works fine in chrome but in Internet explorer, it creates a gray square around the buttons.  I've been able to get it removed on IE by wrapping the input tag with a div disabled tag.  However, this does not work in chrome.  So I can't get one to work without messing up the other.  The code I have included is the one that works with chrome.

input[disabled] {
    cursor: not-allowed;
    background-color: #cfcfcf;
}

input[type="radio"], input[type="checkbox"] {
    box-sizing: border-box;
    padding: 0;
}

       <input disabled="disabled" checked="checked" class="form-check-input" id="Male" name="GenderSelection" type="radio" value="Y">

        Male

]2

Body:
the issue is with the css.

input[disabled] {background-color:#cfcfcf;}

remove that and it works.

Thanks!


问:
"bash: pip: command not found" when using "pip install ..."
On Linux Ubuntu with python 3.6.9

When i try to download pip, it says i already have it. So when i try to pip install ... it gives me error "bash: pip: command not found".

When i type "which pip" in the terminal it gives me nothing and creates a new line.

(While also it doesn't work in the normal terminal) I should also say I'm trying to do this in a virualenv. It gives the same errors when  trying to install pip (I already have it) and when trying to use pip ("bash: pip: command not found")

echo $PATH output: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

sorry if this doesn't make sense, kinda a noob

答:
Try the following:

python -m pip install ....

python3 -m pip install ....

py3 -m pip install ....

As @S3DEV commented, there could be a problem with your path variables, so trying python before pip could solve. Those other variations (python3 and py) can also work.


问:
Numpy: concat/expand 2D arrays based on matches in a column. How to eliminate for loop?
I'm looking for a more "Numpy" way to perform an operation to expand and concatenate data from one array to another with repeating terms.

Example Data

I want a and b to look like c in the end:

```<code>a = np.array(((0, 13), (0, 14), (1, 15), (1, 16), (2, 17)))
b = np.array(((0, 415, 666), (1, 286, 583), (2, 777, 32), (3, 663, 12)))

c = np.array(((0, 13, 415, 666), (0, 14, 415, 666), (1, 15, 286, 583), (1, 16, 286, 583), (2, 17, 777, 32)))
</code>```

In my example data, note that the first column is an "index" of sorts with multiple repetitions for some in array a.  Also note that b contains unused indices.

MWE of working code

I am currently performing this task with a combination of np.repeat and np.tileinside afor`` loop.  However, this is inefficient:

```<code>c = np.empty((0, 4))
for i in np.unique(a[:, 0]):
    foo = a[np.where(a[:, 0] == i)]
    bar = b[np.where(b[:, 0] == i)]
    output = np.vstack((output, np.column_stack((np.repeat(foo, np.size(bar, 0), 0), np.tile(bar, (np.size(foo, 0), 1))))))
</code>```

The Question

Is there a way to perform this task using pure Numpy which eliminates the for loop and performs more quickly on large datasets?

答:
you could try to use the column 0 of a to index b values (sorry not sure of the term here) and then use hstack like:

```<code>c = np.hstack([a, b[a[:, 0], 1:]])
print (c)
[[  0  13 415 666]
 [  0  14 415 666]
 [  1  15 286 583]
 [  1  16 286 583]
 [  2  17 777  32]]
</code>```

Body:
I'm looking for a more "Numpy" way to perform an operation to expand and concatenate data from one array to another with repeating terms.

Example Data

I want a and b to look like c in the end:

a = np.array(((0, 13), (0, 14), (1, 15), (1, 16), (2, 17)))
b = np.array(((0, 415, 666), (1, 286, 583), (2, 777, 32), (3, 663, 12)))

c = np.array(((0, 13, 415, 666), (0, 14, 415, 666), (1, 15, 286, 583), (1, 16, 286, 583), (2, 17, 777, 32)))

In my example data, note that the first column is an "index" of sorts with multiple repetitions for some in array a.  Also note that b contains unused indices.

MWE of working code

I am currently performing this task with a combination of np.repeat and np.tileinside afor`` loop.  However, this is inefficient:

c = np.empty((0, 4))
for i in np.unique(a[:, 0]):
    foo = a[np.where(a[:, 0] == i)]
    bar = b[np.where(b[:, 0] == i)]
    output = np.vstack((output, np.column_stack((np.repeat(foo, np.size(bar, 0), 0), np.tile(bar, (np.size(foo, 0), 1))))))

The Question

Is there a way to perform this task using pure Numpy which eliminates the for loop and performs more quickly on large datasets?

Body:
you could try to use the column 0 of a to index b values (sorry not sure of the term here) and then use hstack like:

c = np.hstack([a, b[a[:, 0], 1:]])
print (c)
[[  0  13 415 666]
 [  0  14 415 666]
 [  1  15 286 583]
 [  1  16 286 583]
 [  2  17 777  32]]


问:
Quickfix/n QuickFix.FieldConvertError: Could not convert field: Could not convert string to int (N)
I am getting the below error and can't figure out why (there are no other errors):

```<code>    QuickFix.FieldConvertError: Could not convert field: Could not convert string to int (N): The first character must be a digit or a minus sign
    at QuickFix.Fields.Converters.IntConverter.Convert(String i)
    at QuickFix.FieldMap.GetInt(Int32 tag)
    at QuickFix.DataDictionary.DataDictionary.CheckGroupCount(IField field, FieldMap map, String msgType)
    at QuickFix.DataDictionary.DataDictionary.Iterate(FieldMap map, String msgType)
    at QuickFix.DataDictionary.DataDictionary.Validate(Message message, DataDictionary sessionDataDict, DataDictionary appDataDict, String beginString, String msgType)
    at QuickFix.Session.Next(MessageBuilder msgBuilder)
    at QuickFix.Session.NextMessage(String msgStr)
    at QuickFix.SocketInitiatorThread.ProcessStream()
    at QuickFix.SocketInitiatorThread.Read()
</code>```

I am sending this message to my application (it is much longer but I removed a lot of the message to try to find the tag with the issue and reduced the message to the below remaining tags, but it looks like the issue is not with the message itself):

```<code>     8=FIX.4.49=342135=CG49=SENDER34=352=20200513-19:34:28.76856=528357=TARGET1510=11505=11511=01513=50
</code>```

This is part of my data dictionary:

```<code> <message name="ParticipantList" msgtype="CG" msgcat="app">
  <field name="PartyDetailsListReportID" required="Y"/>
  <field name="PartyDetailsListRequestID" required="Y"/>
  <field name="PartyDetailsRequestResult" required="Y"/>
  <field name="Text" required="N"/>
  <field name="NoPartyList" required="N"/>
  <group name="LastFragment" required="N">
    <field name="PartyID" required="N"/>
    <field name="PartyIDSource" required="N"/>
    <field name="PartyRole" required="N"/>
    <field name="PartyName" required="N"/>
    <field name="AccountStatus" required="N"/>
    <field name="MobileAccess" required="N"/>
    <field name="SMAGroupingName" required="N"/>
    <field name="SMAGroupMargin" required="N"/>
    <field name="SMAGroupCurrency" required="N"/>
    <group name="NoClrDetails" required="N">
      <field name="ClrHouseCode" required="N"/>
      <field name="RIMnemonic" required="N"/>
      <field name="LIFFERIMnemonic" required="N"/>
      <field name="IFADRIMnemonic" required="N"/>
      <field name="AccountCode" required="N"/>
      <field name="CTICode" required="N"/>
      <field name="RiskLimitAmount" required="N"/>
      <field name="Currency" required="N"/>
    </group>
    <group name="NoPartySubIDs" required="N">
      <field name="PartySubID" required="N"/>
      <field name="PartySubIDType" required="N"/>
    </group>
    <group name="NoAccountLimits" required="N">
       <field name="SecurityID" required="N"/>
       <field name="PhysicalCode" required="N"/>
       <field name="UnderlyingSecurityExchange" required="N"/>
       <field name="FloatBuyLotsBid" required="N"/>
       <field name="FloatSellLotsOffer" required="N"/>
       <field name="MaxTradeBuyLotsLong" required="N"/>
       <field name="MaxTradeSellLotsShort" required="N"/>
       <field name="AbsBuyLimitAbsLong" required="N"/>
       <field name="AbsSellLimitAbsShort" required="N"/>
       <field name="TradeNetLotsBalance" required="N"/>
       <field name="SpreadBuyLimit" required="N"/>
       <field name="SpreadSellLimit" required="N"/>
       <field name="ProductAccountCode" required="N"/>
       <field name="BlockLimit" required="N"/>
       <field name="StrategyBlockLimit" required="N"/>
     </group>
  </group>
</message>
</code>```

I have already tried switching types for the tags from "int" to "string" and still get that error. I am baffled.

I am using QuickFix v1.9.0.0. My application is written in C#, but that does not really matter because the incoming message isn't even hitting my code.

Any advice/suggestions are greatly appreciated.

答: Thanks for the suggestions! It looks like the issue was on their side and with their provided specs as well. My data dictionary was correct from the beginning. What I posted in the question above is what the exchange suggested. However the correct data dictionary is where LastFragment is before the NoPartyList group. The exchange must send the message with tags in that order as well or there will be errors.</p>

Body:
I am getting the below error and can't figure out why (there are no other errors):

    QuickFix.FieldConvertError: Could not convert field: Could not convert string to int (N): The first character must be a digit or a minus sign
    at QuickFix.Fields.Converters.IntConverter.Convert(String i)
    at QuickFix.FieldMap.GetInt(Int32 tag)
    at QuickFix.DataDictionary.DataDictionary.CheckGroupCount(IField field, FieldMap map, String msgType)
    at QuickFix.DataDictionary.DataDictionary.Iterate(FieldMap map, String msgType)
    at QuickFix.DataDictionary.DataDictionary.Validate(Message message, DataDictionary sessionDataDict, DataDictionary appDataDict, String beginString, String msgType)
    at QuickFix.Session.Next(MessageBuilder msgBuilder)
    at QuickFix.Session.NextMessage(String msgStr)
    at QuickFix.SocketInitiatorThread.ProcessStream()
    at QuickFix.SocketInitiatorThread.Read()

I am sending this message to my application (it is much longer but I removed a lot of the message to try to find the tag with the issue and reduced the message to the below remaining tags, but it looks like the issue is not with the message itself):

     8=FIX.4.49=342135=CG49=SENDER34=352=20200513-19:34:28.76856=528357=TARGET1510=11505=11511=01513=50

This is part of my data dictionary:

 <message name="ParticipantList" msgtype="CG" msgcat="app">
  <field name="PartyDetailsListReportID" required="Y"/>
  <field name="PartyDetailsListRequestID" required="Y"/>
  <field name="PartyDetailsRequestResult" required="Y"/>
  <field name="Text" required="N"/>
  <field name="NoPartyList" required="N"/>
  <group name="LastFragment" required="N">
    <field name="PartyID" required="N"/>
    <field name="PartyIDSource" required="N"/>
    <field name="PartyRole" required="N"/>
    <field name="PartyName" required="N"/>
    <field name="AccountStatus" required="N"/>
    <field name="MobileAccess" required="N"/>
    <field name="SMAGroupingName" required="N"/>
    <field name="SMAGroupMargin" required="N"/>
    <field name="SMAGroupCurrency" required="N"/>
    <group name="NoClrDetails" required="N">
      <field name="ClrHouseCode" required="N"/>
      <field name="RIMnemonic" required="N"/>
      <field name="LIFFERIMnemonic" required="N"/>
      <field name="IFADRIMnemonic" required="N"/>
      <field name="AccountCode" required="N"/>
      <field name="CTICode" required="N"/>
      <field name="RiskLimitAmount" required="N"/>
      <field name="Currency" required="N"/>
    </group>
    <group name="NoPartySubIDs" required="N">
      <field name="PartySubID" required="N"/>
      <field name="PartySubIDType" required="N"/>
    </group>
    <group name="NoAccountLimits" required="N">
       <field name="SecurityID" required="N"/>
       <field name="PhysicalCode" required="N"/>
       <field name="UnderlyingSecurityExchange" required="N"/>
       <field name="FloatBuyLotsBid" required="N"/>
       <field name="FloatSellLotsOffer" required="N"/>
       <field name="MaxTradeBuyLotsLong" required="N"/>
       <field name="MaxTradeSellLotsShort" required="N"/>
       <field name="AbsBuyLimitAbsLong" required="N"/>
       <field name="AbsSellLimitAbsShort" required="N"/>
       <field name="TradeNetLotsBalance" required="N"/>
       <field name="SpreadBuyLimit" required="N"/>
       <field name="SpreadSellLimit" required="N"/>
       <field name="ProductAccountCode" required="N"/>
       <field name="BlockLimit" required="N"/>
       <field name="StrategyBlockLimit" required="N"/>
     </group>
  </group>
</message>

I have already tried switching types for the tags from "int" to "string" and still get that error. I am baffled.

I am using QuickFix v1.9.0.0. My application is written in C#, but that does not really matter because the incoming message isn't even hitting my code.

Any advice/suggestions are greatly appreciated.


问:
How to get data out of an Arraylist
So in a previous quesiton I asked how i could merge multiple array list into one array list.

This answer worked (also listed below). However, I am having issues getting the records out.  How do I get the data out of this multi dimensional arraylist.  For example, what if I wanted to get just address out?

```<code>ArrayList Names = new ArrayList();
ArrayList Phone = new ArrayList();
ArrayList Address = new ArrayList();
ArrayList res = new ArrayList();
for(int i=0; i<Names.Count; i++)
{
  res.Add(new string[]{Names[i].ToString(), Phone[i].ToString(), Address[i].ToString()});
}
</code>```

答:
You could do something like the following ... I want to make sure and I note that you might want to come up with better data structures or container classes if you can.

```<code>string someAddress = ((string[])res[0])[2];
</code>```

In this instance we are taking the object (string array) at the first index of res and then indexing into the string array where the address was stored.

You could consider a something like the following though to contain your data with a typed list..

```<code>public class Person
{
    public string Name { get; set; }
    public string Phone { get; set; }
    public string Address { get; set; }
}
</code>```

...

```<code>List<Person> people = new List<Person>();
people.Add(new Person() { Name = "Not Me", Phone = "(555) 212-1234", Address = "123 Fake St." });

string address = people[0].Address;
</code>```

Title: How to get data out of an Arraylist

Body:
So in a previous quesiton I asked how i could merge multiple array list into one array list.

This answer worked (also listed below). However, I am having issues getting the records out.  How do I get the data out of this multi dimensional arraylist.  For example, what if I wanted to get just address out?

ArrayList Names = new ArrayList();
ArrayList Phone = new ArrayList();
ArrayList Address = new ArrayList();
ArrayList res = new ArrayList();
for(int i=0; i<Names.Count; i++)
{
  res.Add(new string[]{Names[i].ToString(), Phone[i].ToString(), Address[i].ToString()});
}

Body:
You could do something like the following ... I want to make sure and I note that you might want to come up with better data structures or container classes if you can.

string someAddress = ((string[])res[0])[2];

In this instance we are taking the object (string array) at the first index of res and then indexing into the string array where the address was stored.

You could consider a something like the following though to contain your data with a typed list..

public class Person
{
    public string Name { get; set; }
    public string Phone { get; set; }
    public string Address { get; set; }
}

...

List<Person> people = new List<Person>();
people.Add(new Person() { Name = "Not Me", Phone = "(555) 212-1234", Address = "123 Fake St." });

string address = people[0].Address;


问:
Recurring payments using Stripe and Django
I'm still pretty new to Django and am trying to set up recurring payments via Stripe. I'm using Django 2.0 and have successfully set up a single charge test case. However, I'm unfamiliar with how to create recurring payments, and require it for the project I'm working on.

For the single payment, I have the following:

 Views

```<code>stripe.api_key = settings.STRIPE_SECRET_KEY

def checkout(request):
    """Stripe check out"""

    new_tier = models.PaymentTier(
        level = "Tier 3",
        year = 2018
    )

    if request.method == "POST":
        token = request.POST.get("stripeToken")
    try:
        charge = stripe.Charge.create(
            amount = 2000,
            currency = "usd",
            source = token,
            description = "Tier 3 subscription for Elite Fitness"
        )

        new_tier.charge_id = charge.id

    except stripe.error.CardError as ce:
        return False, ce

    else:
        new_tier.save()
        return redirect("thank_you_page")

def payment_form(request):
    """Render stripe payment form template"""

    context = {"stripe_key": settings.STRIPE_PUBLIC_KEY}
    return render(request, "stripe-template.html", context)

def thank_you_page(request):
    """Successful payment processed"""

    return render(request,'thank_you_page.html')
</code>```

 stripe-template.html

```<code><form action="checkout/" method="POST"> {% csrf_token %}
    <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
        data-key={{stripe_key}} # Make sure to wrap the variable name with double {}
        data-amount="2000"
        data-name="company name here"
        data-description="Elite Fitness Subscription"
        data-image="picture.png"
        data-currency="usd">
    </script>
</form>
</code>```

I've had a difficult time finding anything online which covers recurring payments specifically. If anybody knows how to set them up (even through dj-stripe or pinax) any help will be very greatly appreciated.

答:
As of 2020 it's actually recommended to use PaymentIntents for this. Stripe has an excellent guide for how to do this in their docs now that walks through the whole flow and covers things like 3D-secure as well.

For a longer treatment on the topic specific to Django, see this article: How to Create a Subscription SaaS Application with Django and Stripe

Body:
I'm still pretty new to Django and am trying to set up recurring payments via Stripe. I'm using Django 2.0 and have successfully set up a single charge test case. However, I'm unfamiliar with how to create recurring payments, and require it for the project I'm working on.

For the single payment, I have the following:

 Views

stripe.api_key = settings.STRIPE_SECRET_KEY

def checkout(request):
    """Stripe check out"""

    new_tier = models.PaymentTier(
        level = "Tier 3",
        year = 2018
    )

    if request.method == "POST":
        token = request.POST.get("stripeToken")
    try:
        charge = stripe.Charge.create(
            amount = 2000,
            currency = "usd",
            source = token,
            description = "Tier 3 subscription for Elite Fitness"
        )

        new_tier.charge_id = charge.id

    except stripe.error.CardError as ce:
        return False, ce

    else:
        new_tier.save()
        return redirect("thank_you_page")

def payment_form(request):
    """Render stripe payment form template"""

    context = {"stripe_key": settings.STRIPE_PUBLIC_KEY}
    return render(request, "stripe-template.html", context)

def thank_you_page(request):
    """Successful payment processed"""

    return render(request,'thank_you_page.html')

 stripe-template.html

<form action="checkout/" method="POST"> {% csrf_token %}

</form>

I've had a difficult time finding anything online which covers recurring payments specifically. If anybody knows how to set them up (even through dj-stripe or pinax) any help will be very greatly appreciated.


问:
CreateJS MovieClip performance issue
I'm using Adobe Animate HTML5 to create a board game to run on Smart TV (low-performance machine).

All my previous games were done using AS3.
I quickly found there is no way to create a Sprite anymore (A movie clips with only 1 frame).
After creating my board game (no code yet just elements) which is basically movie clips inside other movie clips. All single frame.

I checked the FPS on LG TV and so it is done from 60 to 20. On a static image.
After research, I found that is the advance method in MovieClip class there is a constant check to update the frame.
I added a change to check if the MovieClip class total frame is equal to 1 to change it the mode of the MovieClip to a single frame. This increases performance back to 60 FPS.

Who do I go to, to check and maybe fix/"add a feature" to the code of createjs

Thanks

答: code issues or suggestions can be logged here https://github.com/CreateJS/EaselJS/issues for CreateJS.  All the best.</p>

Title: CreateJS MovieClip performance issue


问:
Apollo-client update cache variable: orderby name doesn't work
I have a mutation of new product. I update cache with cache.writeQuery and I want to order the product by name. My code doesn't work, always the new product is the last item (see the picture) . I can see the error. Could you help me? What is wrong?

COMPONENT NEW PRODUCT

```<code>import { gql, useMutation } from '@apollo/client'

const NEW_PRODUCT = gql`
mutation newProduct($input: ProductInput) {
  newProduct(input:$input) {
    id
    name
    stock
    price
    date_creation
  }
}`

const GET_PRODUCTS = gql`
  query getProducts{
  getProducts{
    id
    name
    stock
    price
  }
}`

const NouProducte = () => {

  const [newProduct] = useMutation(NEW_PRODUCT, {
    update(cache, { data: { newProduct } }) {
      const { getProducts } = cache.readQuery({ query: GET_PRODUCTS })
      cache.writeQuery({
        query: GET_PRODUCTS,
        data: {
          getProducts: [...getProducts, newProduct],
          variables: { orderBy: name }
        }
      })
    }
  })
}
</code>```

答:
I am not sure if you can order-by on local cache with apollo. However, this is how I would resolve the issue:

```<code>  data: {
          getProducts: [...getProducts, newProduct]
        }
</code>```

In this line of code you are adding all the original products, then the new product to the end of the array that you are writing to your cache.

A quick way to fix this is sort the array before writing it to the cache. The following compare sorts arrays by objects name attribute

```<code>  function compare(a, b) {
    // Use toUpperCase() to ignore character casing
    const productA = a.name.toUpperCase();
    const productB = b.name.toUpperCase();

    let comparison = 0;
    if (productA > productB) {
      comparison = 1;
    } else if (productA < productB) {
      comparison = -1;
    }
    return comparison;
  }
</code>```

Then use it on your array to sort.

```<code>  data: {
          getProducts: [...getProducts, newProduct].sort(compare)
        }
</code>```

Body:
I have a mutation of new product. I update cache with cache.writeQuery and I want to order the product by name. My code doesn't work, always the new product is the last item (see the picture) . I can see the error. Could you help me? What is wrong?

COMPONENT NEW PRODUCT

import { gql, useMutation } from '@apollo/client'

const NEW_PRODUCT = gql`
mutation newProduct($input: ProductInput) {
  newProduct(input:$input) {
    id
    name
    stock
    price
    date_creation
  }
}`

const GET_PRODUCTS = gql`
  query getProducts{
  getProducts{
    id
    name
    stock
    price
  }
}`

const NouProducte = () => {

  const [newProduct] = useMutation(NEW_PRODUCT, {
    update(cache, { data: { newProduct } }) {
      const { getProducts } = cache.readQuery({ query: GET_PRODUCTS })
      cache.writeQuery({
        query: GET_PRODUCTS,
        data: {
          getProducts: [...getProducts, newProduct],
          variables: { orderBy: name }
        }
      })
    }
  })
}

Body:
I am not sure if you can order-by on local cache with apollo. However, this is how I would resolve the issue:

  data: {
          getProducts: [...getProducts, newProduct]
        }

In this line of code you are adding all the original products, then the new product to the end of the array that you are writing to your cache.

A quick way to fix this is sort the array before writing it to the cache. The following compare sorts arrays by objects name attribute

  function compare(a, b) {
    // Use toUpperCase() to ignore character casing
    const productA = a.name.toUpperCase();
    const productB = b.name.toUpperCase();

    let comparison = 0;
    if (productA > productB) {
      comparison = 1;
    } else if (productA < productB) {
      comparison = -1;
    }
    return comparison;
  }

Then use it on your array to sort.

  data: {
          getProducts: [...getProducts, newProduct].sort(compare)
        }


问:
update null column from select
I have the below table, approx 3 million rows.

```<code>at_id  a.at_type_cd
  1      red
  2      blue
  3      yellow
</code>```

I want to add a column, so I did the below.

```<code>alter table ship.alt
add (src_ind char(1) null)
</code>```

Now I have the below table:

```<code>at_id    at_type_cd   src_ind
  1      red           (null)
  2      blue          (null)
  3      yellow        (null)
</code>```

All values in the src_ind are null. I want to add values to the src_ind based of a select from another table.

```<code>merge into &tableschema..alt dest
using (select /* parallel(a,16) */
    x.at_id,
    x.src_ind
    from (select
          a.at_id,
          case
          when alt.tracks_t is null
          then 'H'
          when alt.tracks_at = 1
          then 'B'
          else 'x'
          end src_ind
          from &tableschema..alt a
          left join (select
                     alt.at_type,
                     alt.tracks_at
                     from &tableschema..at_tys@db alt
                     where alt.tracks_at <> 0) alt
                     on a.at_type_cd = alt.at_type
                     where 1=1)x ) src
                     on (src.at_id = dest.at_id)
when matched then
 update set
 dest.src_ind = src.src_ind
when not matched then
insert (src_ind)
values (src.src_ind)
</code>```

This takes over two hours on my end. I'm not sure this is correct, using the eyeball test, is there a more efficient way to add column values based on a select?

update vs insert vs merge

Maybe a insert with a where exist?

答:
Please use below query,</p>

```<code>merge into &tableschema..alt dest
using (select
x.at_id,
x.src_ind
from (select /* parallel(a,16) */
      a.at_id,
      case
      when alt.tracks_t is null
      then 'H'
      when alt.tracks_at = 1
      then 'B'
      else 'x'
      end src_ind
      from &tableschema..alt a
      left join (select  /* parallel(a,16) */
                 alt.at_type,
                 alt.tracks_at
                 from &tableschema..at_tys@db alt
                 where alt.tracks_at <> 0) alt
                 on a.at_type_cd = alt.at_type
                 where 1=1)x ) src
                 on (src.at_id = dest.at_id)
when matched then
 update set
 dest.src_ind = src.src_ind
 when not matched then
insert (src_ind)
values (src.src_ind) ;
</code>```

Title: update null column from select

Body:
I have the below table, approx 3 million rows.

at_id  a.at_type_cd
  1      red
  2      blue
  3      yellow

I want to add a column, so I did the below.

alter table ship.alt
add (src_ind char(1) null)

Now I have the below table:

at_id    at_type_cd   src_ind
  1      red           (null)
  2      blue          (null)
  3      yellow        (null)

All values in the src_ind are null. I want to add values to the src_ind based of a select from another table.

merge into &tableschema..alt dest
using (select /* parallel(a,16) */
    x.at_id,
    x.src_ind
    from (select
          a.at_id,
          case
          when alt.tracks_t is null
          then 'H'
          when alt.tracks_at = 1
          then 'B'
          else 'x'
          end src_ind
          from &tableschema..alt a
          left join (select
                     alt.at_type,
                     alt.tracks_at
                     from &tableschema..at_tys@db alt
                     where alt.tracks_at <> 0) alt
                     on a.at_type_cd = alt.at_type
                     where 1=1)x ) src
                     on (src.at_id = dest.at_id)
when matched then
 update set
 dest.src_ind = src.src_ind
when not matched then
insert (src_ind)
values (src.src_ind)

This takes over two hours on my end. I'm not sure this is correct, using the eyeball test, is there a more efficient way to add column values based on a select?

update vs insert vs merge

Maybe a insert with a where exist?

Body:
Please use below query,

merge into &tableschema..alt dest
using (select
x.at_id,
x.src_ind
from (select /* parallel(a,16) */
      a.at_id,
      case
      when alt.tracks_t is null
      then 'H'
      when alt.tracks_at = 1
      then 'B'
      else 'x'
      end src_ind
      from &tableschema..alt a
      left join (select  /* parallel(a,16) */
                 alt.at_type,
                 alt.tracks_at
                 from &tableschema..at_tys@db alt
                 where alt.tracks_at <> 0) alt
                 on a.at_type_cd = alt.at_type
                 where 1=1)x ) src
                 on (src.at_id = dest.at_id)
when matched then
 update set
 dest.src_ind = src.src_ind
 when not matched then
insert (src_ind)
values (src.src_ind) ;


问:
How do you set the title color for the new Toolbar?
I'm using the new v7 Toolbar and for the life of me can't figure out how to change the color of the title.  I've set the @style of the Toolbar to a style declared in styles.xml and applied a titleTextStyle with a textColor.  Am I missing something?  I'm coding for Lollipop but testing currently on a Kitkat device.

styles.xml

```<code><resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="@style/Theme.AppCompat.Light">
        <item name="android:windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
    </style>

    <style name="ActionBar" parent="Theme.AppCompat">
        <item name="android:background">@color/actionbar_background</item>
        <item name="android:titleTextStyle">@style/ActionBar.TitleTextStyle</item>
    </style>

    <style name="ActionBar.TitleTextStyle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
        <item name="android:textColor">@color/actionbar_title_text</item>
    </style>

</resources>
</code>```

actionbar.xml:

```<code><android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar_actionbar"
    android:layout_width="match_parent"
    android:layout_height="?actionBarSize"
    style="@style/ActionBar"/>
</code>```

答:
With the Material Components Library you can use the app:titleTextColor attribute.

In the layout you can use something like:

```<code><com.google.android.material.appbar.MaterialToolbar
    app:titleTextColor="@color/...."
    .../>
</code>```

You can also use a custom style:

```<code><com.google.android.material.appbar.MaterialToolbar
     style="@style/MyToolbarStyle"
    .../>
</code>```

with (extending the Widget.MaterialComponents.Toolbar.Primary style) :

```<code>  <style name="MyToolbarStyle" parent="Widget.MaterialComponents.Toolbar.Primary">
       <item name="titleTextColor">@color/....</item>
  </style>
</code>```

or (extending the Widget.MaterialComponents.Toolbar style) :

```<code>  <style name="MyToolbarStyle" parent="Widget.MaterialComponents.Toolbar">
       <item name="titleTextColor">@color/....</item>
  </style>
</code>```

You can also override the color defined by the style using the android:theme attribute (using the Widget.MaterialComponents.Toolbar.Primary style):

```<code>    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar.Primary"
        android:theme="@style/MyThemeOverlay_Toolbar"
        />
</code>```

with:

```<code>  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is also used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/...</item>
  </style>
</code>```

or (using the Widget.MaterialComponents.Toolbar style):

```<code>    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar"
        android:theme="@style/MyThemeOverlay_Toolbar2"
</code>```

with:

```<code>  <style name="MyThemeOverlay_Toolbar3" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is used by title -->
    <item name="android:textColorPrimary">@color/white</item>

    <!-- This attributes is used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/secondaryColor</item>
  </style>
</code>```

Body:
I'm using the new v7 Toolbar and for the life of me can't figure out how to change the color of the title.  I've set the @style of the Toolbar to a style declared in styles.xml and applied a titleTextStyle with a textColor.  Am I missing something?  I'm coding for Lollipop but testing currently on a Kitkat device.

styles.xml

<resources>

</resources>

actionbar.xml:

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar_actionbar"
    android:layout_width="match_parent"
    android:layout_height="?actionBarSize"
    style="@style/ActionBar"/>

Body:
With the Material Components Library you can use the app:titleTextColor attribute.

In the layout you can use something like:

<com.google.android.material.appbar.MaterialToolbar
    app:titleTextColor="@color/...."
    .../>

You can also use a custom style:

<com.google.android.material.appbar.MaterialToolbar
     style="@style/MyToolbarStyle"
    .../>

with (extending the Widget.MaterialComponents.Toolbar.Primary style) :

  <style name="MyToolbarStyle" parent="Widget.MaterialComponents.Toolbar.Primary">
       <item name="titleTextColor">@color/....</item>
  </style>

or (extending the Widget.MaterialComponents.Toolbar style) :

  <style name="MyToolbarStyle" parent="Widget.MaterialComponents.Toolbar">
       <item name="titleTextColor">@color/....</item>
  </style>

You can also override the color defined by the style using the android:theme attribute (using the Widget.MaterialComponents.Toolbar.Primary style):

    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar.Primary"
        android:theme="@style/MyThemeOverlay_Toolbar"
        />

with:

  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is also used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/...</item>
  </style>

or (using the Widget.MaterialComponents.Toolbar style):

    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar"
        android:theme="@style/MyThemeOverlay_Toolbar2"

with:

  <style name="MyThemeOverlay_Toolbar3" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is used by title -->
    <item name="android:textColorPrimary">@color/white</item>

    <!-- This attributes is used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/secondaryColor</item>
  </style>


问:
How can I bind an object to a SelectItem component?
Can anyone please help me on this? I'm using UI-Kitten's select and selectiem components, and I need to know how can I bind an object to a SelectedItem component?

I would like to pass some value as a binding object:

```<code>data={
 (['OPT1', 'Option 1'],
  ['OPT2', 'Option 2'],
  ['OPT3', 'Option 3'],
  ['OPT4', 'Option 4'],
  ['OPT5', 'Option 5'])
}
</code>```

Then, I'll like to render each select's option with something like this:

```<code>const renderOption = (title: string, key: string) => (
     <SelectItem title={title} key={key} />
  );
</code>```

This option could be populated with a map function:

```<code><Select
  style={styles.inputSetting}
  textAlign="right"
  size="small"
  placeholder={placeholder}
  value={value}>
  {data && data.map(renderOption)}
</Select>
</code>```

This won't work because map function expects (value: never, index: number), and SelectItem component doesn't have a "key" prop.

I would need to get the key value and not the display value.

Any help pointing me to the correct direction would be appreciated.

答:
you can use index as key like this

```<code><Select
  style={styles.inputSetting}
  textAlign="right"
  size="small"
  placeholder={placeholder}
  value={value}>
  {data && data.map((dataItem,index)=>renderOption({title:dataItem,key:index}))}
</Select>
</code>```

Body:
Can anyone please help me on this? I'm using UI-Kitten's select and selectiem components, and I need to know how can I bind an object to a SelectedItem component?

I would like to pass some value as a binding object:

data={
 (['OPT1', 'Option 1'],
  ['OPT2', 'Option 2'],
  ['OPT3', 'Option 3'],
  ['OPT4', 'Option 4'],
  ['OPT5', 'Option 5'])
}

Then, I'll like to render each select's option with something like this:

const renderOption = (title: string, key: string) => (
     <SelectItem title={title} key={key} />
  );

This option could be populated with a map function:

<Select
  style={styles.inputSetting}
  textAlign="right"
  size="small"
  placeholder={placeholder}
  value={value}>
  {data && data.map(renderOption)}
</Select>

This won't work because map function expects (value: never, index: number), and SelectItem component doesn't have a "key" prop.

I would need to get the key value and not the display value.

Any help pointing me to the correct direction would be appreciated.

Body:
you can use index as key like this

<Select
  style={styles.inputSetting}
  textAlign="right"
  size="small"
  placeholder={placeholder}
  value={value}>
  {data && data.map((dataItem,index)=>renderOption({title:dataItem,key:index}))}
</Select>


问:
Django - Filter queryset by another queryset through related field
Suppose I have the two models below and I want to get a queryset of all developers that have games where the platform field matches a certain value. How would I go about that?

```<code>class Developer(models.Model):
    name = models.CharField(max_length=100, default="Unknown")

class Game(models.Model):
    name = models.CharField(max_length=300)
    developer = models.ForeignKey(Developer, related_name="games", on_delete=models.CASCADE)
    platform = models.CharField(max_length=40)
</code>```

I tried a few approached but can't seem to figure anything out that works.

答:
You can query this with:

```<code>Developer.objects.filter(<b>games__platform=<i>'name-of-platform'</i></b>).distinct()</code>```

Without the .distinct() [Django-doc], the same developer will be returned multiple times, if they developed multiple Games for the same platform. If that is not a problem, you can of course omit the .distinct().

Body:
Suppose I have the two models below and I want to get a queryset of all developers that have games where the platform field matches a certain value. How would I go about that?

class Developer(models.Model):
    name = models.CharField(max_length=100, default="Unknown")

class Game(models.Model):
    name = models.CharField(max_length=300)
    developer = models.ForeignKey(Developer, related_name="games", on_delete=models.CASCADE)
    platform = models.CharField(max_length=40)

I tried a few approached but can't seem to figure anything out that works.

Body:
You can query this with:

Developer.objects.filter(games__platform='name-of-platform').distinct()

Without the .distinct() [Django-doc], the same developer will be returned multiple times, if they developed multiple Games for the same platform. If that is not a problem, you can of course omit the .distinct().


问:
Liquibase doesn't fill contexts column in changelog table
I'm using liquiBase 3.8.0 in springBoot. My tree of changelog files is like this:

```<code>changelog-master.xml
--changelog-test.xml
----changelog-1.0.0
----changelog-1.1.0
--changelog-prod.xml
----changelog-1.0.0
----changelog-1.1.0
</code>```

I try to use contexts and I find strange behaviour -- if I use context in changelog-master.xml or changelog-test.xml like this (parents changelog files):

```<code> <include file="test/changelog-test.xml" relativeToChangelogFile="true" context="!prod"/>
</code>```

then liquibase doesn't fill contexts column in changelog table and contexts column is null.

But if I add attribute 'context' to 'changeSet'

```<code><changeSet id="changelog_in_test_section" author="author@mail.ru" logicalFilePath="changelog-1.0.0" context="test">
</code>```

After that the contexts column is filled with '!prod AND test'

I want that the contexts column is alwayes filled (if I use context attribute in parent changelog).

答:
I would add this to the github issues list.  Or better yet, if you have a code fix add it as a pull request.
https://github.com/liquibase/liquibase/issues</p>

Body:
I'm using liquiBase 3.8.0 in springBoot. My tree of changelog files is like this:

changelog-master.xml
--changelog-test.xml
----changelog-1.0.0
----changelog-1.1.0
--changelog-prod.xml
----changelog-1.0.0
----changelog-1.1.0

I try to use contexts and I find strange behaviour -- if I use context in changelog-master.xml or changelog-test.xml like this (parents changelog files):

 <include file="test/changelog-test.xml" relativeToChangelogFile="true" context="!prod"/>

then liquibase doesn't fill contexts column in changelog table and contexts column is null.

But if I add attribute 'context' to 'changeSet'

<changeSet id="changelog_in_test_section" author="author@mail.ru" logicalFilePath="changelog-1.0.0" context="test">

After that the contexts column is filled with '!prod AND test'

I want that the contexts column is alwayes filled (if I use context attribute in parent changelog).


问:
How do you run a SQL Server query from PowerShell?
Is there a way to execute an arbitrary query on a SQL Server using Powershell on my local machine?</p>

答:
To avoid SQL Injection with varchar parameters you could use</p>
```<code>function sqlExecuteRead($connectionString, $sqlCommand, $pars) {

    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
    $connection.Open()
    $command = new-object system.data.sqlclient.sqlcommand($sqlCommand, $connection)

    if ($pars -and $pars.Keys) {
        foreach($key in $pars.keys) {
            # avoid injection in varchar parameters
            $par = $command.Parameters.Add("@$key", [system.data.SqlDbType]::VarChar, 512);
            $par.Value = $pars[$key];
        }
    }

    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataset) | Out-Null
    $connection.Close()
    return $dataset.tables[0].rows

}

$connectionString = "connectionstringHere"
$sql = "select top 10 Message, TimeStamp, Level from dbo.log " +
    "where Message = @MSG and Level like @LEVEL"
$pars = @{
    MSG = 'this is a test from powershell'
    LEVEL = 'aaa%'
};
sqlExecuteRead $connectionString $sql $pars
</code>```

Body:
To avoid SQL Injection with varchar parameters you could use

function sqlExecuteRead($connectionString, $sqlCommand, $pars) {

    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
    $connection.Open()
    $command = new-object system.data.sqlclient.sqlcommand($sqlCommand, $connection)

    if ($pars -and $pars.Keys) {
        foreach($key in $pars.keys) {
            # avoid injection in varchar parameters
            $par = $command.Parameters.Add("@$key", [system.data.SqlDbType]::VarChar, 512);
            $par.Value = $pars[$key];
        }
    }

    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataset) | Out-Null
    $connection.Close()
    return $dataset.tables[0].rows

}

$connectionString = "connectionstringHere"
$sql = "select top 10 Message, TimeStamp, Level from dbo.log " +
    "where Message = @MSG and Level like @LEVEL"
$pars = @{
    MSG = 'this is a test from powershell'
    LEVEL = 'aaa%'
};
sqlExecuteRead $connectionString $sql $pars


问:
Error inflating class com.google.android.gms.ads.AdView in android studio
I am trying to add an admod to a fragment. After adding the dependency in build.gradle, I still cannot inflating the admod class and display the admod on my XML. Any idea of what I have done wrong? Am I missing any setting?

Error message

```<code>android.view.InflateException: Binary XML file line #1095 in com.centslife.development:layout/mockup_spotreceiptdetail: Binary XML file line #1095 in com.centslife.development:layout/mockup_spotreceiptdetail: Error inflating class com.google.android.gms.ads.AdView
    Caused by: android.view.InflateException: Binary XML file line #1095 in com.centslife.development:layout/mockup_spotreceiptdetail: Error inflating class com.google.android.gms.ads.AdView
</code>```

build.gradle

```<code>implementation 'com.google.android.gms:play-services-ads:10.2.1'
</code>```

XML

```<code>        <com.google.android.gms.ads.AdView
            xmlns:ads="http://schemas.android.com/apk/res-auto"
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            ads:adSize="BANNER"
            ads:adUnitId="@string/banner_ad_unit_id"></com.google.android.gms.ads.AdView>
</code>```

Update

```<code>apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.centslife.development"
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.Home.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

        }
    }
    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.vectordrawable:vectordrawable:1.0.1'
    implementation 'androidx.navigation:navigation-fragment:2.0.0'
    implementation 'androidx.navigation:navigation-ui:2.0.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.firebase:firebase-firestore:17.1.2'
    testImplementation 'junit:junit:4.12'
    implementation "androidx.cardview:cardview:1.0.0"
    def roomVersion = "2.2.5"
    def archLifecycleVersion = '2.2.0'
    def coreTestingVersion = '2.1.0'
    implementation "androidx.room:room-runtime:$roomVersion"
    annotationProcessor "androidx.room:room-compiler:$roomVersion"
    androidTestImplementation "androidx.room:room-testing:$roomVersion"
    implementation "androidx.lifecycle:lifecycle-extensions:$archLifecycleVersion"
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:$archLifecycleVersion"
    androidTestImplementation "androidx.arch.core:core-testing:$coreTestingVersion"
    implementation 'com.facebook.shimmer:shimmer:0.5.0'
    implementation 'com.google.android.gms:play-services-ads:10.2.1'

}

</code>```

Update2 Full XML

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#00FFFFFF"
                app:srcCompat="@drawable/sample"
                tools:visibility="visible" />
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <com.google.android.gms.ads.AdView
            xmlns:ads="http://schemas.android.com/apk/res-auto"
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            ads:adSize="BANNER"
            ads:adUnitId="@string/banner_ad_unit_id">
            </com.google.android.gms.ads.AdView>

    </LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

答:
You are using very old version of ads sdk.Change it with the latest.

implementation  'com.google.android.gms:play-services-ads:19.1.0'
Also you have to add meta data in your manifest file's application tags

```<code><meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
</code>```

You can try like this

```<code><com.google.android.gms.ads.AdView

        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id"/>
</code>```

Body:
I am trying to add an admod to a fragment. After adding the dependency in build.gradle, I still cannot inflating the admod class and display the admod on my XML. Any idea of what I have done wrong? Am I missing any setting?

Error message

android.view.InflateException: Binary XML file line #1095 in com.centslife.development:layout/mockup_spotreceiptdetail: Binary XML file line #1095 in com.centslife.development:layout/mockup_spotreceiptdetail: Error inflating class com.google.android.gms.ads.AdView
    Caused by: android.view.InflateException: Binary XML file line #1095 in com.centslife.development:layout/mockup_spotreceiptdetail: Error inflating class com.google.android.gms.ads.AdView

build.gradle

implementation 'com.google.android.gms:play-services-ads:10.2.1'

XML

        <com.google.android.gms.ads.AdView
            xmlns:ads="http://schemas.android.com/apk/res-auto"
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            ads:adSize="BANNER"
            ads:adUnitId="@string/banner_ad_unit_id"></com.google.android.gms.ads.AdView>

Update

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.centslife.development"
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.Home.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

        }
    }
    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.vectordrawable:vectordrawable:1.0.1'
    implementation 'androidx.navigation:navigation-fragment:2.0.0'
    implementation 'androidx.navigation:navigation-ui:2.0.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.firebase:firebase-firestore:17.1.2'
    testImplementation 'junit:junit:4.12'
    implementation "androidx.cardview:cardview:1.0.0"
    def roomVersion = "2.2.5"
    def archLifecycleVersion = '2.2.0'
    def coreTestingVersion = '2.1.0'
    implementation "androidx.room:room-runtime:$roomVersion"
    annotationProcessor "androidx.room:room-compiler:$roomVersion"
    androidTestImplementation "androidx.room:room-testing:$roomVersion"
    implementation "androidx.lifecycle:lifecycle-extensions:$archLifecycleVersion"
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:$archLifecycleVersion"
    androidTestImplementation "androidx.arch.core:core-testing:$coreTestingVersion"
    implementation 'com.facebook.shimmer:shimmer:0.5.0'
    implementation 'com.google.android.gms:play-services-ads:10.2.1'

}

Update2 Full XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#00FFFFFF"
                app:srcCompat="@drawable/sample"
                tools:visibility="visible" />
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <com.google.android.gms.ads.AdView
            xmlns:ads="http://schemas.android.com/apk/res-auto"
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            ads:adSize="BANNER"
            ads:adUnitId="@string/banner_ad_unit_id">
            </com.google.android.gms.ads.AdView>

    </LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Body:
You are using very old version of ads sdk.Change it with the latest.

implementation  'com.google.android.gms:play-services-ads:19.1.0'
Also you have to add meta data in your manifest file's application tags

<meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>

You can try like this

<com.google.android.gms.ads.AdView

        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id"/>


答:
Why do you ever expected sorting?

You're using a low level access to cache then you're responsible for providing data in the same shape as expected from remote source.

In this case if source data was sorted you have to pass sorted data to be written. Just get getProducts, push newProduct into the array, sort it and finally use sorted array in writeQuery.

Title: Apollo-client update cache variable: orderby name doesn't work


问:
method in class cannot be applied to given types. Can you see what I have to change?
enter image description here

and

this is all of my code formats. Can you see what I have to change?

```<code>import java.util.Random;

public class Human
{
    private int xPos;  // x-position of the ball
    private int yPos;  // y-position of the ball
    private int size;  // size of the ball

public Human(int size)
{
    this.size = size;
}

public void setPos(int x, int y)
{
    xPos = x;
    yPos = y;
}

public void show()
{
    Canvas cv = Canvas.getCanvas();
    cv.drawCircle(xPos, yPos, size);
}

public void moveRandom()
{
    Canvas cv = Canvas.getCanvas();
    int cvWidth = cv.getWidth();
    int cvHeight = cv.getHeight();

    Random r = new Random();
    int x, y;

    while (true)
    {
        x = r.nextInt(cvWidth);   // 0..cvWidth-1
        y = r.nextInt(cvHeight);  // 0..cvHeight-1
        setPos(x, y);

        cv.clear();
        show();
        pause(50);
    }
}

private void pause(long timeMillis)
{
    long timeStart = System.currentTimeMillis();

    while (System.currentTimeMillis() < timeStart + timeMillis)
        ;
}
</code>```

}

答:
So, the error message in your screenshot says

method drawCircle in class cannot be applied to given types;

required: int, int, java.lang.String, int

found: int, int, int

You are trying to call the method with three integers `cv.drawCircle(xPos, yPos, size);, whereas you need to input int, int, String and int. Maybe changing the variable size to type String helps.

Body:
enter image description here

and

this is all of my code formats. Can you see what I have to change?

import java.util.Random;

public class Human
{
    private int xPos;  // x-position of the ball
    private int yPos;  // y-position of the ball
    private int size;  // size of the ball

public Human(int size)
{
    this.size = size;
}

public void setPos(int x, int y)
{
    xPos = x;
    yPos = y;
}

public void show()
{
    Canvas cv = Canvas.getCanvas();
    cv.drawCircle(xPos, yPos, size);
}

public void moveRandom()
{
    Canvas cv = Canvas.getCanvas();
    int cvWidth = cv.getWidth();
    int cvHeight = cv.getHeight();

    Random r = new Random();
    int x, y;

    while (true)
    {
        x = r.nextInt(cvWidth);   // 0..cvWidth-1
        y = r.nextInt(cvHeight);  // 0..cvHeight-1
        setPos(x, y);

        cv.clear();
        show();
        pause(50);
    }
}

private void pause(long timeMillis)
{
    long timeStart = System.currentTimeMillis();

    while (System.currentTimeMillis() < timeStart + timeMillis)
        ;
}

}


问:
Spring Batch output format of the file?
In spring batch samples, there are lot of examples of copying data from csv format to db table, db table to csv etc. I wanted to know is there a way in which the user can select a particular job for example copy data from a csv file and also specify the destination format i.e. excel, db , pdf. Thus the destination format of the job is dependent on the user input.?

Thanks!
Tarun Sapra

答:
Given that Spring Batch is a batch framework that does not deal with user input, I'm not sure you're working with the right scenario here.  However, there are a few different options here:

Use a job parameter and a decision step to direct to the correct combination of ItemReader/ItemWriter.  The disadvantage of this is that you would need to define a step per implementation (one to handle PDF, one for Excel, etc), however since the choice would be done only once per run of the job it would have less of an impact on performance.

A cleaner approach would still use a job parameter, however it would use the ClassifierCompositeItemWriter to delegate to the appropriate writer.  This ItemWriter would be configured with one ItemWriter delegate per implementation type (PDF, Excel, etc) and would dictate to them based upon the implementation of the Classifier interface you configure.  While this is a cleaner approach from a configuration standpoint, it has the disadvantage of evaluating each of the individual items for which ItemWriter to processs (it's a disadvantage assuming that the entire run is intended to send all of the items to the same ItemWriter per run).

Finally, I would think that you should be able to, in theory, use Spring's bean factory concepts to inject an ItemWriter when the job starts.  For the record, this is purely speculation and I have not actually tried this.

Michael T Minella

Author of Pro Spring Batch

Title: Spring Batch output format of the file?


问:
Tcp Spurious retransmissions after modification via netfilter hook
I used a small python script(from github) to test netfilter hooks and used scapy for sniffing packets.

You can check the script on below link https://gist.github.com/eXenon/85a3eab09fefbb3bee5d#file-scapy_bridge-py

The script modifies payload length and checksum at tcp and ip layers before relaying it but it also causes Spurious transmission when checked in wireshark.

Can someone help me figure out the reason for Spurious retransmission in this case?

答: The answer lies within the following comment Howto intercept tcp packet and modify in the fly?. It is the kernel that detects the packet alteration and treats it as a packet loss. Therefore, it's more suitable/easier to use your script as a transparent proxy rather than doing tweaks at kernel level.</p>


问:
Docusign authentication type for polling
I am using an authorization code grant to create envelopes and listen events from webhook.
But I would like to use polling too.

Is the code grant Authentification a good solution to perform polling or I need to implement a JWT grant in addition?

答:
Polling is usually not a good idea.
It's an inefficient use of resources.
If you poll too frequently, you may be making thousands of unnecessary API calls.
If you poll less frequently, your app may not be freshly updated.
It is therefore a better idea to use a webhook.
DocuSign Connect can be used to inform your app when something happened. For example, an envelope was signed. And this way, you will be updated momentarily, and you wouldn't have to make any additional API calls.
More information here:
https://developers.docusign.com/esign-rest-api/guides/connect

Now since I didn't really answer your question (for a good reason). You can do polling with Auth Code Grant or JWT etc. doesn't matter.
you may run into issues when you try to go-live though, so again, see my recommendation above.


问:
Python scripts don't work without python -m
I'm extremely sorry for asking this question, but I'm absolutely clueless

I just migrated to a Mac, got python set up through brew, and everything works fine, except for the fact that I can't open up Jupyter notebooks, or access pip, without the

```<code>python3 -m pip
</code>```

or

```<code>python3 -m jupyterlab
</code>```

command

This has never happened to me before on Linux or on Windows, and I even double checked my path to make sure the python directories are included. Is it just that I have to create an alias, or am I missing something else here?

答:
If you have installed packages intact (e.g. you didn't remove the bin dir by accident), you can always find the binary path missing in your PATH env var by doing the following. Run

```<code>python3 -m pip show -f jupyterlab
</code>```

This will output the list of files belonging to the installed package jupyterlab.

Now go through the list of files and look for the executable you're missing. Let this be jupyter-lab for the sake of example:

```<code>$ python -m pip show -f jupyterlab
Name: jupyterlab
...
Files:
../../../bin/jupyter-lab
...
</code>```

Note the relative path. Now find the path in the Location line:

```<code>$ python -m pip show -f jupyterlab
Name: jupyterlab
...
Location: /tmp/myenv/lib/python3.8/site-packages
...
</code>```

Resolve the path of the executable against the location to get the absolute path:

```<code>$ readlink -f /tmp/myenv/lib/python3.8/site-packages/../../../bin/jupyter-lab
/tmp/myenv/bin/jupyter-lab
</code>```

This is the path to your executable. Invoking it should work:

```<code>$ /tmp/myenv/bin/jupyter-lab -V
2.1.3
</code>```

Now add the parent dir of the executable to PATH and check whether jupyter-lab is found now:

```<code>$ export PATH=$PATH:$(dirname /tmp/myenv/bin/jupyter-lab)
$ jupyter-lab -V
2.1.3
</code>```

Once it works, you can persist the PATH changes to your shell profile (e.g. ~/.zprofile for zsh on recent MacOS).

This approach is OS agnostic and will work the same on MacOS, Linux or Windows.

Body:
I'm extremely sorry for asking this question, but I'm absolutely clueless

I just migrated to a Mac, got python set up through brew, and everything works fine, except for the fact that I can't open up Jupyter notebooks, or access pip, without the

python3 -m pip

or

python3 -m jupyterlab

command

This has never happened to me before on Linux or on Windows, and I even double checked my path to make sure the python directories are included. Is it just that I have to create an alias, or am I missing something else here?

Body:
If you have installed packages intact (e.g. you didn't remove the bin dir by accident), you can always find the binary path missing in your PATH env var by doing the following. Run

python3 -m pip show -f jupyterlab

This will output the list of files belonging to the installed package jupyterlab.

Now go through the list of files and look for the executable you're missing. Let this be jupyter-lab for the sake of example:

$ python -m pip show -f jupyterlab
Name: jupyterlab
...
Files:
../../../bin/jupyter-lab
...

Note the relative path. Now find the path in the Location line:

$ python -m pip show -f jupyterlab
Name: jupyterlab
...
Location: /tmp/myenv/lib/python3.8/site-packages
...

Resolve the path of the executable against the location to get the absolute path:

$ readlink -f /tmp/myenv/lib/python3.8/site-packages/../../../bin/jupyter-lab
/tmp/myenv/bin/jupyter-lab

This is the path to your executable. Invoking it should work:

$ /tmp/myenv/bin/jupyter-lab -V
2.1.3

Now add the parent dir of the executable to PATH and check whether jupyter-lab is found now:

$ export PATH=$PATH:$(dirname /tmp/myenv/bin/jupyter-lab)
$ jupyter-lab -V
2.1.3

Once it works, you can persist the PATH changes to your shell profile (e.g. ~/.zprofile for zsh on recent MacOS).

This approach is OS agnostic and will work the same on MacOS, Linux or Windows.