问:
Async method in an ASP.NET Web Form
I have to use a third-party library in a ASP.NET web forms app.

The third-party method I have to use is an async one.

Since I have to call it in a page click event handler, I have 2 options:

Declare every page that has to use this method as <%@ Page Async="true" ... %>

Invoke the method synchronously.

FIRST QUESTION

Does it make sense to declare all the website pages async only for this method (potentially can be invoked on every page)?

SECOND QUESTION

The second question is about invoking the async method synchronously.

Having to invoke the following method

```<code>async Task<bool> MyMethodAsync()
{
    ...
}
</code>```

Which is the difference between the next 3 invocations?

```<code>Task.Run(async () => await MyMethodAsync()).GetAwaiter().GetResult();
Task.Run(() => MyMethodAsync()).GetAwaiter().GetResult();
MyMethodAsync().GetAwaiter().GetResult();
</code>```

I cannot see any difference during execution…

Thanks!

答:
Task.Run(async () => await MyMethodAsync()).GetAwaiter().GetResult();

This starts a task to run on a threadpool thread that runs the method asynchronously. Then the main thread sits there and waits for the threadpool thread task to finish.

Task.Run(() => MyMethodAsync()).GetAwaiter().GetResult();

This is the same as above, but the main function "continues" before the method fully completes.

MyMethodAsync().GetAwaiter().GetResult();

This at least avoids using an extra thread to stall the main thread anyway.

Edit: I didn't see this question:

Does it make sense to declare all the website pages async only for this method (potentially can be invoked on every page)?

Depends what kind of async. If they'd still return void, you're gaining nothing, you're just breaking your code base. If you're returning an actual Task, then sure. In fact that's how ASP.Net Core works.

Title: Async method in an ASP.NET Web Form

Body:
I have to use a third-party library in a ASP.NET web forms app.

The third-party method I have to use is an async one.

Since I have to call it in a page click event handler, I have 2 options:

Declare every page that has to use this method as <%@ Page Async="true" ... %>

Invoke the method synchronously.

FIRST QUESTION

Does it make sense to declare all the website pages async only for this method (potentially can be invoked on every page)?

SECOND QUESTION

The second question is about invoking the async method synchronously.

Having to invoke the following method

async Task<bool> MyMethodAsync()
{
    ...
}

Which is the difference between the next 3 invocations?

Task.Run(async () => await MyMethodAsync()).GetAwaiter().GetResult();
Task.Run(() => MyMethodAsync()).GetAwaiter().GetResult();
MyMethodAsync().GetAwaiter().GetResult();

I cannot see any difference during execution…

Thanks!


来源: stackexchange

问:
Google SignIn SDK is failing by throwing error, A non-recoverable sign in failure occurred -catch error: React Native
I have been trying to integrate Social login in my react native project in which I was able to do facebook login successfully but it is failing to signin to google. react-native-google-signin library is used for google.

The code I have used.

```<code>componentDidMount() {
GoogleSignin.hasPlayServices({ autoResolve: true }).then(() => {
// play services are available. can now configure library
}).catch((err) => {

console.log("Play services error", err.code, err.message);
})
GoogleSignin.configure({
scopes: ["https://www.googleapis.com/auth/drive.readonly"], // what API you want to access on behalf of the user, default is email and profile
// iosClientId: <FROM DEVELOPER CONSOLE>, // only for iOS
webClientId: "xxx", // client ID of type WEB for your server (needed to verify user ID and offline access)
// offlineAccess: true // if you want to access Google API on behalf of the user FROM YOUR SERVER
//hostedDomain: '' // specifies a hosted domain restriction
//forceConsentPrompt: true // [Android] if you want to show the authorization prompt at each login
//accountName: '' // [Android] specifies an account name on the device that should be used
})
.then(() => {
// you can now call currentUserAsync()
});
    _signIn = async () => {

        try {

            await GoogleSignin.hasPlayServices(

              )

          const userInfo = await GoogleSignin.signIn();
          console.log('User Info --> ', userInfo);
          this.setState({ userInfo });
        } catch (error) {

          console.log('Message', error.message);
          if (error.code ===  statusCodes.SIGN_IN_CANCELLED) {
            console.log('User Cancelled the Login Flow');
          } else if (error.code === statusCodes.IN_PROGRESS) {
            console.log('Signing In');
          } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
            console.log('Play Services Not Available or Outdated');
          } else {
            console.log('Some Other Error Happened');
          }
        }
      };
</code>```

The error response:

```<code>Message: A non-recoverable sign in failure occurred -catch error
</code>```

答: run gradlew signingReport in the android folder and check all the sha1 listed and if you are using firebase then make sure that all the distinct sha1 found in the list is added to the firebase project then download the google-services.json again replace it with the old one in you project and run cd android && gradlew clean and build your project again

ContentLicense: CC BY-SA 4.0

Body:
I have been trying to integrate Social login in my react native project in which I was able to do facebook login successfully but it is failing to signin to google. react-native-google-signin library is used for google.

The code I have used.

componentDidMount() {
GoogleSignin.hasPlayServices({ autoResolve: true }).then(() => {
// play services are available. can now configure library
}).catch((err) => {

console.log("Play services error", err.code, err.message);
})
GoogleSignin.configure({
scopes: ["https://www.googleapis.com/auth/drive.readonly"], // what API you want to access on behalf of the user, default is email and profile
// iosClientId: <FROM DEVELOPER CONSOLE>, // only for iOS
webClientId: "xxx", // client ID of type WEB for your server (needed to verify user ID and offline access)
// offlineAccess: true // if you want to access Google API on behalf of the user FROM YOUR SERVER
//hostedDomain: '' // specifies a hosted domain restriction
//forceConsentPrompt: true // [Android] if you want to show the authorization prompt at each login
//accountName: '' // [Android] specifies an account name on the device that should be used
})
.then(() => {
// you can now call currentUserAsync()
});
    _signIn = async () => {

        try {

            await GoogleSignin.hasPlayServices(

              )

          const userInfo = await GoogleSignin.signIn();
          console.log('User Info --> ', userInfo);
          this.setState({ userInfo });
        } catch (error) {

          console.log('Message', error.message);
          if (error.code ===  statusCodes.SIGN_IN_CANCELLED) {
            console.log('User Cancelled the Login Flow');
          } else if (error.code === statusCodes.IN_PROGRESS) {
            console.log('Signing In');
          } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
            console.log('Play Services Not Available or Outdated');
          } else {
            console.log('Some Other Error Happened');
          }
        }
      };

The error response:

Message: A non-recoverable sign in failure occurred -catch error


问:
Jenkins Kubernetes: Mount subpath of volume
As far as i understood, the kubernetes api allows one to mount a subpath of a pvc into the container in the volumeMounts spec.

In my example i want to mount the pvc my-pvc, but in the subdirectory /my-subpath to /my-mount.

So the directory /my-subpath on my-pvc would be mounted in the container under /my-mount.

When using Kubernetes normally, this would look like follows if i understood the docs:

```<code>volumeMounts:
- mountPath: /my-mount
      name: my-pvc
      subPath: "my-subpath"
</code>```

My problem now is, that in the jenkins kubernetes plugin this doesn't seem to be possible.

If i understood the docs correctly, it seems that it is only possible to mount the root directory, i.e. /, of the pvc my-pvc to /my-mount in the container, since there is no subPath option:

Is there something i am missing, or is it just not possible to do this?

答:
It is not possible by available options of Jenkins Kubernetes plugin ATM. But still, you can achieve this by applying a raw pod template in Kubernetes cloud pod configuration.

Sample output

```<code>Started by user admin
Replayed #11
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] podTemplate
[Pipeline] {
[Pipeline] node
Still waiting to schedule task
‘hello-docker-j0rk6’ is offline
Agent hello-docker-j0rk6 is provisioned from template hello-docker
---
apiVersion: "v1"
kind: "Pod"
metadata:
  annotations: {}
  labels:
    run: "hello-docker"
    jenkins: "slave"
    jenkins/label: "hello-docker"
  name: "hello-docker-j0rk6"
spec:
  containers:
  - command:
    - "cat"
    image: "jenkins/jnlp-slave:3.27-1-alpine"
    name: "hello-docker"
    resources: {}
    tty: true
    volumeMounts:
    - mountPath: "/app/logs"
      name: "tmp"
      subPath: "logs"
    - mountPath: "/home/jenkins/agent"
      name: "workspace-volume"
      readOnly: false
</code>```

Body:
As far as i understood, the kubernetes api allows one to mount a subpath of a pvc into the container in the volumeMounts spec.

In my example i want to mount the pvc my-pvc, but in the subdirectory /my-subpath to /my-mount.

So the directory /my-subpath on my-pvc would be mounted in the container under /my-mount.

When using Kubernetes normally, this would look like follows if i understood the docs:

volumeMounts:
- mountPath: /my-mount
      name: my-pvc
      subPath: "my-subpath"

My problem now is, that in the jenkins kubernetes plugin this doesn't seem to be possible.

If i understood the docs correctly, it seems that it is only possible to mount the root directory, i.e. /, of the pvc my-pvc to /my-mount in the container, since there is no subPath option:

Is there something i am missing, or is it just not possible to do this?

Body:
It is not possible by available options of Jenkins Kubernetes plugin ATM. But still, you can achieve this by applying a raw pod template in Kubernetes cloud pod configuration.

Sample output

Started by user admin
Replayed #11
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] podTemplate
[Pipeline] {
[Pipeline] node
Still waiting to schedule task
‘hello-docker-j0rk6’ is offline
Agent hello-docker-j0rk6 is provisioned from template hello-docker
---
apiVersion: "v1"
kind: "Pod"
metadata:
  annotations: {}
  labels:
    run: "hello-docker"
    jenkins: "slave"
    jenkins/label: "hello-docker"
  name: "hello-docker-j0rk6"
spec:
  containers:
  - command:
    - "cat"
    image: "jenkins/jnlp-slave:3.27-1-alpine"
    name: "hello-docker"
    resources: {}
    tty: true
    volumeMounts:
    - mountPath: "/app/logs"
      name: "tmp"
      subPath: "logs"
    - mountPath: "/home/jenkins/agent"
      name: "workspace-volume"
      readOnly: false


问:
TypeError: Cannot read property 'forEach' of undefined Javascript
Following is the code in which I am getting Cannot read property 'forEach' of undefined.

const print2 = function(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )```
</div>
</div>
</p>

<p>Let me know what I am doing wrong here, though if I do -</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function print2(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )</code>```

this is working fine.

答:
I think, rather than [1,2,3,4].forEach( x => print2(x, 20) ), you should use a variable like array.forEach(x => print2(x, 20));

For example code given below:

```<code>let array = [1,2,3,4];
const print2 = function(x, y) {
    console.log(x*y);
};

array.forEach( x => print2(x, 20) );
</code>```

Body:
Following is the code in which I am getting Cannot read property 'forEach' of undefined.

const print2 = function(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )

Let me know what I am doing wrong here, though if I do -

function print2(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )

this is working fine.

Body:
I think, rather than [1,2,3,4].forEach( x => print2(x, 20) ), you should use a variable like array.forEach(x => print2(x, 20));

For example code given below:

let array = [1,2,3,4];
const print2 = function(x, y) {
    console.log(x*y);
};

array.forEach( x => print2(x, 20) );


问:
Nullable in objective c
Is there a way to make nullable struct in objective C like in C# you can use Nullable<T>?

I need a CGPoint to be null when there is no applicable value. I cannot allocate a random invalid value for this like (-5000, -5000) because all values are valid for this.

答: CGPoint is a enum, not an object. You can use CGPointZero, or you can wrap all of your points inside of NSValue, which are objects and can be nil.</p>

ContentLicense: CC BY-SA 3.0

Title: Nullable in objective c


问:
Use the modified admin template only for one Image app
Django 3.0.6

For one model I need a modified admin site template.

Namely, I want to modify this template:

```<code>admin/includes/fieldset.html
</code>```

I have copied the fieldset.html from Django package directory and placed it like this:

```<code>/my_project/image/templates/admin/includes/fieldset.html
</code>```

Here image is my application. It is this application that needs a modified admin template.

The problem is that all other models also get this template. And the used template filters don't receive necessary params and explode.

Documentation: https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#set-up-your-projects-admin-template-directories

Well, I got confused and fail to organize the necessary directories structure.

How can I use the modified template only for one Image app?

答:
You have a couple of issues. Firstly, only the following templates can be overridden per-app or per-model:

actions.html

app_index.html

change_form.html

change_form_object_tools.html

change_list.html

change_list_object_tools.html

change_list_results.html

date_hierarchy.html

delete_confirmation.html

object_history.html

pagination.html

popup_response.html

prepopulated_fields_js.html

search_form.html

submit_line.html

fieldset.html isn't in there, so you'll need to see if the including template(s) is in this list, and if it is, replace this template and use it to include your own version of fieldset.html.

Also, your location (slightly modified since can't override included templates per-app): /my_project/image/templates/admin/template.html isn't quite right. This will overwrite that template for every app. To do it per-app, you need a further subdirectory under admin:

```<code>/my_project/image/templates/admin/image/template.html
</code>```

The reason for this is that templates don't really care about which app they're in, so the fact that the template lives in your image app doesn't mean anything to Django, the convention of putting them in your app's sub-directory is solely to avoid overriding templates that you don't intend to.

Body:
Django 3.0.6

For one model I need a modified admin site template.

Namely, I want to modify this template:

admin/includes/fieldset.html

I have copied the fieldset.html from Django package directory and placed it like this:

/my_project/image/templates/admin/includes/fieldset.html

Here image is my application. It is this application that needs a modified admin template.

The problem is that all other models also get this template. And the used template filters don't receive necessary params and explode.

Documentation: https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#set-up-your-projects-admin-template-directories

Well, I got confused and fail to organize the necessary directories structure.

How can I use the modified template only for one Image app?

Body:
You have a couple of issues. Firstly, only the following templates can be overridden per-app or per-model:

actions.html

app_index.html

change_form.html

change_form_object_tools.html

change_list.html

change_list_object_tools.html

change_list_results.html

date_hierarchy.html

delete_confirmation.html

object_history.html

pagination.html

popup_response.html

prepopulated_fields_js.html

search_form.html

submit_line.html

fieldset.html isn't in there, so you'll need to see if the including template(s) is in this list, and if it is, replace this template and use it to include your own version of fieldset.html.

Also, your location (slightly modified since can't override included templates per-app): /my_project/image/templates/admin/template.html isn't quite right. This will overwrite that template for every app. To do it per-app, you need a further subdirectory under admin:

/my_project/image/templates/admin/image/template.html

The reason for this is that templates don't really care about which app they're in, so the fact that the template lives in your image app doesn't mean anything to Django, the convention of putting them in your app's sub-directory is solely to avoid overriding templates that you don't intend to.


问:
Psalm error for TwigFilter callable parameter
I get this error from psalm for a twig extension:

ERROR: InvalidArgument - src/Twig/CartExtension.php:44:17 - Argument 2
of Twig\TwigFilter::__construct expects callable|null,
array{App\Twig\CartExtension&static, string(getOfferDate)} provided

The code in question is:

```<code>public function getFilters(): array
{
    return [
        new TwigFilter(
            'get_offer_date',
            [$this, 'getOfferDate']
        ),
    ];
}
</code>```

And the TwigFilter signature is

```<code>/**
 * @param callable|null $callable A callable implementing the filter. If null, you need to overwrite the "node_class" option to customize compilation.
 */
public function __construct(string $name, $callable = null, array $options = [])

...
</code>```

The twig docs recommend this format

[$this, 'getOfferDate']

for the callable: https://symfony.com/doc/current/templating/twig_extension.html

How can i fix this psalm error or tell psalm to accept it?

答: Method getOfferDate() should be created inside of class. In your case, inside of class CartExtension.

Body:
I get this error from psalm for a twig extension:

ERROR: InvalidArgument - src/Twig/CartExtension.php:44:17 - Argument 2
of Twig\TwigFilter::__construct expects callable|null,
array{App\Twig\CartExtension&static, string(getOfferDate)} provided

The code in question is:

public function getFilters(): array
{
    return [
        new TwigFilter(
            'get_offer_date',
            [$this, 'getOfferDate']
        ),
    ];
}

And the TwigFilter signature is

/**
 * @param callable|null $callable A callable implementing the filter. If null, you need to overwrite the "node_class" option to customize compilation.
 */
public function __construct(string $name, $callable = null, array $options = [])

...

The twig docs recommend this format

[$this, 'getOfferDate']

for the callable: https://symfony.com/doc/current/templating/twig_extension.html

How can i fix this psalm error or tell psalm to accept it?


问:
selectInput that is dependent on another selectInput
I have some data below that I'm using to create a donut chart in R shiny, where date is a character. I want to be able to select the email whose score I want to view, but then in the second dropdown selection only see the dates for which that email has activity.

For example, if I select email = xxxx in the first dropdown, I want to see only 'no activity' in the date selection field. And for email = yyyy, I want to see only 6/17/14, 6/18/14, 6/19/14 as selections.

I've tried a sort of nested subsetting in the ui. Example:

```<code>> ui <- shinyUI(fluidPage(
+   sidebarLayout(
+     sidebarPanel(
+       selectInput('Select', 'Customer:', choices = unique(as.character(dat5$email))),
+       selectInput("User", "Date:", choices = dat5[dat5$email==input$Select,date])
+     ),
+     mainPanel(plotOutput("distPlot"))
+   )
+ ))
</code>```

But this still shows all possible date selections

DATA

```<code>email   date        variable    value   ymin    ymax
xxxx    no activity e_score         0   0       0
xxxx    no activity diff            1   0       1
yyyy    6/17/14     e_score    0.7472   0       0.7472
yyyy    6/17/14     diff       0.2528   0.7472  1
yyyy    6/18/14     e_score    0.373    0       0.373
yyyy    6/18/14     diff       0.627    0.373   1
yyyy    6/19/14     e_score    0.533    0       0.533
yyyy    6/19/14     diff       0.467    0.533   1
</code>```

My code so far:

app.R

```<code>library(shiny)
library(shinydashboard)

ui <- shinyUI(fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput('Select', 'Customer:', choices = unique(as.character(dat5$email))),
      selectInput("User", "Date:", choices = unique(dat5$date) )
    ),
    mainPanel(plotOutput("distPlot"))
  )
))

server <- function(input, output) {
  output$distPlot <- renderPlot({
    ggplot(data = subset(dat5, (email %in% input$Select & date %in% input$User)), aes(fill=variable, ymax = ymax, ymin = ymin, xmax = 4, xmin = 3)) +
      geom_rect(colour = "grey30", show_guide = F) +
      coord_polar(theta = "y") +
      geom_text(aes(x = 0, y = 0,label = round(value[1]*100))) +
      xlim(c(0, 4)) +
      theme_bw() +
      theme(panel.grid=element_blank()) +
      theme(axis.text=element_blank()) +
      theme(axis.ticks=element_blank()) +
      xlab("") +
      ylab("") +
      scale_fill_manual(values=c('#33FF00','#CCCCCC'))

  })
}
  shinyApp(ui = ui, server = server)
</code>```

答:
You can also do it without changing ui.R. Adding this to server.R has the same effect.

    observe({
          updateSelectInput(session, "User", choices = as.character(dat5[dat5$email==input$Select, date]))
    })
```

Though it is a useful and powerful tool, I find it "cleaner" to get by without renderUI. It keeps the UI in the UI and the server in the server. But that is just a matter of taste, I suppose.

Body:
I have some data below that I'm using to create a donut chart in R shiny, where date is a character. I want to be able to select the email whose score I want to view, but then in the second dropdown selection only see the dates for which that email has activity.

For example, if I select email = xxxx in the first dropdown, I want to see only 'no activity' in the date selection field. And for email = yyyy, I want to see only 6/17/14, 6/18/14, 6/19/14 as selections.

I've tried a sort of nested subsetting in the ui. Example:

> ui <- shinyUI(fluidPage(
+   sidebarLayout(
+     sidebarPanel(
+       selectInput('Select', 'Customer:', choices = unique(as.character(dat5$email))),
+       selectInput("User", "Date:", choices = dat5[dat5$email==input$Select,date])
+     ),
+     mainPanel(plotOutput("distPlot"))
+   )
+ ))

But this still shows all possible date selections

DATA

email   date        variable    value   ymin    ymax
xxxx    no activity e_score         0   0       0
xxxx    no activity diff            1   0       1
yyyy    6/17/14     e_score    0.7472   0       0.7472
yyyy    6/17/14     diff       0.2528   0.7472  1
yyyy    6/18/14     e_score    0.373    0       0.373
yyyy    6/18/14     diff       0.627    0.373   1
yyyy    6/19/14     e_score    0.533    0       0.533
yyyy    6/19/14     diff       0.467    0.533   1

My code so far:

app.R

library(shiny)
library(shinydashboard)

ui <- shinyUI(fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput('Select', 'Customer:', choices = unique(as.character(dat5$email))),
      selectInput("User", "Date:", choices = unique(dat5$date) )
    ),
    mainPanel(plotOutput("distPlot"))
  )
))

server <- function(input, output) {
  output$distPlot <- renderPlot({
    ggplot(data = subset(dat5, (email %in% input$Select & date %in% input$User)), aes(fill=variable, ymax = ymax, ymin = ymin, xmax = 4, xmin = 3)) +
      geom_rect(colour = "grey30", show_guide = F) +
      coord_polar(theta = "y") +
      geom_text(aes(x = 0, y = 0,label = round(value[1]*100))) +
      xlim(c(0, 4)) +
      theme_bw() +
      theme(panel.grid=element_blank()) +
      theme(axis.text=element_blank()) +
      theme(axis.ticks=element_blank()) +
      xlab("") +
      ylab("") +
      scale_fill_manual(values=c('#33FF00','#CCCCCC'))

  })
}
  shinyApp(ui = ui, server = server)

Body:
You can also do it without changing ui.R. Adding this to server.R has the same effect.

    observe({
          updateSelectInput(session, "User", choices = as.character(dat5[dat5$email==input$Select, date]))
    })

Though it is a useful and powerful tool, I find it "cleaner" to get by without renderUI. It keeps the UI in the UI and the server in the server. But that is just a matter of taste, I suppose.


问:
Java - Generic Drools rule
I would like to create my rule more Generic format which mean it should be validate the fields and values. Following my POJO structure.

```<code> public class RulesModel
private String field;
private List<String> values;
// other stuff
</code>```

And my rule

```<code>rule "sample"
when
    $rule : RulesModel( field == "source", values contains "facebook", values contains "youtube", value not contains "instagram" )
then
    // actions
end
</code>```

It's working fine to validate single field, but i want to validate the multiple fields of RulesModel.
So i desire to create the POJO

```<code>public class RulesModelList {

    private List<RulesModel> ruleList;
    // Getter & Setter
}
</code>```

So now when i pass the list of RulesModel by using RulesModelList class the rule should be validate like below

```<code>$rule : RulesModel( field == "source", values contains "facebook") && $rule : RulesModel( field == "createdBy", values contains "admin")
</code>```

How to validate that in Drools?

Thanks in advance.

答:
You can analyze collection of elements using forAll and accumulate</p>

```<code>RulesModelList($ruleList: ruleList)
$matchingList: List() from accumulate (
    $model: RulesModel(field == "source", values contains "facebook", values contains "youtube", value not contains "instagram") from $ruleList,
    accumulateList($model)
)
</code>```

Title: Java - Generic Drools rule

Body:
I would like to create my rule more Generic format which mean it should be validate the fields and values. Following my POJO structure.

 public class RulesModel
private String field;
private List<String> values;
// other stuff

And my rule

rule "sample"
when
    $rule : RulesModel( field == "source", values contains "facebook", values contains "youtube", value not contains "instagram" )
then
    // actions
end

It's working fine to validate single field, but i want to validate the multiple fields of RulesModel.
So i desire to create the POJO

public class RulesModelList {

    private List<RulesModel> ruleList;
    // Getter & Setter
}

So now when i pass the list of RulesModel by using RulesModelList class the rule should be validate like below

$rule : RulesModel( field == "source", values contains "facebook") && $rule : RulesModel( field == "createdBy", values contains "admin")

How to validate that in Drools?

Thanks in advance.

Body:
You can analyze collection of elements using forAll and accumulate

RulesModelList($ruleList: ruleList)
$matchingList: List() from accumulate (
    $model: RulesModel(field == "source", values contains "facebook", values contains "youtube", value not contains "instagram") from $ruleList,
    accumulateList($model)
)


问:
How do I run specific functions based on tags in C++?
I am writing a test framework that will run hundreds of tests.  Each of these tests has been written as an independent function.  Currently, I have my main function run each of these tests one-by-one.  What I would like to make is a system that uses tags.  For example, I want to be able to run all the tests with the 'WiFi' tag or run all the tests that have a 'notifications' tag.

I have tried looking up how to do this, but all I can find are articles that talk about tag dispatching which doesn't help me.  Maybe a tag isn't what I need here?

Not sure if this matters but I'm writing in c++11 on a Mac, and I'm using VS Code.

btw I'm new to stack overflow, so sorry if I messed anything up.  Thanks in advance!

Edit:
I would use multiple tags per function. For example, there is a function that would need 'WiFi' and 'Network' tags, and another that would need 'Haptic', 'Notification', and 'Network' tags.

答:
The reason your research has gone badly is that "tag" is a very broad, general term that doesn't really describe what you're doing.

Fundamentally, you're trying to map two pieces of data together; that's it really. Doesn't matter whether one of those pieces (your "tag") is an integer, an enum member, a string, a class instance or anything else.

You've said "I would need a new map for each tag", but I don't agree. You only need a multimap from "tag" to functions (and, at worst, another multimap from functions to "tag" if you need reverse lookup too). These are pretty trivial.

```<code>enum class Tag
{
   WiFi,
   Haptic,
   Network,
   Notification
};

using Function = std::function<void()>;  // or whatever it is

std::multimap<Tag, Function> tagLookup;

void BindTag(const Tag tag, Function func)
{
   tagLookup.emplace(tag, std::move(func));  // I'm using move out of habit
}

void RunFuncsForTag(const Tag tag)
{
   auto [start, end] = tagLookup.equal_range(tag);
   for (auto it = start; it != end; ++it)
   {
      const Function& func = it->second;
      func();
   }
}

int main()
{
   BindTag(...);
   BindTag(...);

   RunFuncsForTag(tag);
}
</code>```

Admittedly, if you don't want lots of copies of your std::function, there's some more work to do (you could store them in another container and have some other mapping to do that lookup to each function stored once), but the basic data storage principle here is fairly simple.

Body:
The reason your research has gone badly is that "tag" is a very broad, general term that doesn't really describe what you're doing.

Fundamentally, you're trying to map two pieces of data together; that's it really. Doesn't matter whether one of those pieces (your "tag") is an integer, an enum member, a string, a class instance or anything else.

You've said "I would need a new map for each tag", but I don't agree. You only need a multimap from "tag" to functions (and, at worst, another multimap from functions to "tag" if you need reverse lookup too). These are pretty trivial.

enum class Tag
{
   WiFi,
   Haptic,
   Network,
   Notification
};

using Function = std::function<void()>;  // or whatever it is

std::multimap<Tag, Function> tagLookup;

void BindTag(const Tag tag, Function func)
{
   tagLookup.emplace(tag, std::move(func));  // I'm using move out of habit
}

void RunFuncsForTag(const Tag tag)
{
   auto [start, end] = tagLookup.equal_range(tag);
   for (auto it = start; it != end; ++it)
   {
      const Function& func = it->second;
      func();
   }
}

int main()
{
   BindTag(...);
   BindTag(...);

   RunFuncsForTag(tag);
}

Admittedly, if you don't want lots of copies of your std::function, there's some more work to do (you could store them in another container and have some other mapping to do that lookup to each function stored once), but the basic data storage principle here is fairly simple.


问:
How to open script inside Windows Terminal
I have shortcut which under the hood performs something like that:

C:\Windows\System32\cmd.exe /C "powershell D:\ssh.ps1"

it executes ssh.ps1 script which inside opens SSH to ssh user@$ip where $ip comes from variable

but it executes inside cmd, meanwhile I'd want to start it inside Windows Terminal - how can I achieve that?

答:
Assuming you have Window Terminal installed to the default location, it will be located here where USERNAME is your username:
C:\Users\USERNAME\AppData\Local\Microsoft\WindowsApps\wt.exe

Create your shortcut with the starting location set to something like this:
C:\Users\USERNAME\AppData\Local\Microsoft\WindowsApps\wt.exe powershell.exe -ExecutionPolicy Bypass -File D:\ssh.ps1


问:
Invalid character error when inserting data with select statement in Oracle
I am trying to insert a data from another table using below query

```<code>cmd_write = new OracleCommand(@"insert into table1 (f_id, f_name, s_id, r_id,
       t_date, t_type, sys_entry_date, parent_sys_id, sys_f_source)
      select
          f_id, f_name, s_id, r_id,
          t_date, 1, sysdate, sys_id, sys_file_source
      from table2
      where sys_id = :sy_id
      returning sys_id
        into :sys_get_id ", ora_con);

cmd_write.Parameters.Add(new OracleParameter("sy_id", sys_id));

OracleParameter sys_get_id = new OracleParameter("sys_get_id", OracleDbType.Int64);
sys_get_id.Direction = ParameterDirection.Output;
cmd_write.Parameters.Add(sys_get_id);
cmd_write.CommandTimeout = 0;

cmd_write.ExecuteNonQuery();
</code>```

I get this error:

ORA-00911: invalid character

答:
It looks like this is not possible.
I tried this

create table A (c1 varchar(10) null);

declare
   x varchar2(10);
   TYPE myType IS TABLE OF A.c1%TYPE INDEX BY BINARY_INTEGER;
   vData myType;
begin
   insert into A select dummy from dual returning c1 bulk collect into vData;
   -- null;
end;
/
```

To no avail. Then I found this

Body:
I am trying to insert a data from another table using below query

cmd_write = new OracleCommand(@"insert into table1 (f_id, f_name, s_id, r_id,
       t_date, t_type, sys_entry_date, parent_sys_id, sys_f_source)
      select
          f_id, f_name, s_id, r_id,
          t_date, 1, sysdate, sys_id, sys_file_source
      from table2
      where sys_id = :sy_id
      returning sys_id
        into :sys_get_id ", ora_con);

cmd_write.Parameters.Add(new OracleParameter("sy_id", sys_id));

OracleParameter sys_get_id = new OracleParameter("sys_get_id", OracleDbType.Int64);
sys_get_id.Direction = ParameterDirection.Output;
cmd_write.Parameters.Add(sys_get_id);
cmd_write.CommandTimeout = 0;

cmd_write.ExecuteNonQuery();

I get this error:

ORA-00911: invalid character

Body:
It looks like this is not possible.
I tried this

create table A (c1 varchar(10) null);

declare
   x varchar2(10);
   TYPE myType IS TABLE OF A.c1%TYPE INDEX BY BINARY_INTEGER;
   vData myType;
begin
   insert into A select dummy from dual returning c1 bulk collect into vData;
   -- null;
end;
/

To no avail. Then I found this


问:
pip uses incorrect cached package version, instead of the user-specified version
I need to install psycopg2 v2.4.1 specifically. I accidentally did:

```<code> pip install psycopg2
</code>```

Instead of:

```<code> pip install psycopg2==2.4.1
</code>```

That installs 2.4.4 instead of the earlier version.

Now even after I pip uninstall psycopg2 and attempt to reinstall with the correct version, it appears that pip is re-using the cache it downloaded the first time.

How can I force pip to clear out its download cache and use the specific version I'm including in the command?

答:
A better way to do it is to delete the cache and rebuild it. In this way, if you install it again for other virtualenv, it will use the cache instead of building every time when you install it.

For example, when you install it, it will say it uses cached wheel,

Processing <some_prefix>/Library/Caches/pip/wheels/d0/c4/e4/e49fd07bca8dda00dd6b4bbc606aa05a25aacb00d45747a47a/horovod-0.19.3-cp37-cp37m-macosx_10_9_x86_64.wh
```

Just delete that one and restart your install.

Body:
I need to install psycopg2 v2.4.1 specifically. I accidentally did:

 pip install psycopg2

Instead of:

 pip install psycopg2==2.4.1

That installs 2.4.4 instead of the earlier version.

Now even after I pip uninstall psycopg2 and attempt to reinstall with the correct version, it appears that pip is re-using the cache it downloaded the first time.

How can I force pip to clear out its download cache and use the specific version I'm including in the command?

Body:
A better way to do it is to delete the cache and rebuild it. In this way, if you install it again for other virtualenv, it will use the cache instead of building every time when you install it.

For example, when you install it, it will say it uses cached wheel,

Processing <some_prefix>/Library/Caches/pip/wheels/d0/c4/e4/e49fd07bca8dda00dd6b4bbc606aa05a25aacb00d45747a47a/horovod-0.19.3-cp37-cp37m-macosx_10_9_x86_64.wh

Just delete that one and restart your install.


问:
difference between a pointer and reference parameter?
Are these the same:

```<code>int foo(bar* p) {
  return p->someInt();
}
</code>```

and

```<code>int foo(bar& r) {
  return r.someInt();
}
</code>```

Ignore the null pointer potential. Are these two functions functionally identical no matter if someInt() is virtual or if they are passed a bar or a subclass of bar?

Does this slice anything:

```<code>bar& ref = *ptr_to_bar;
</code>```

答:
Ignoring every syntactic sugar and possibilities that can be done with the one and not with the other and difference between pointers and references explained in other answers (to other questions) ... Yeah those two are functionally exactly the same! Both call the function and both handle virtual functions equally well.

And no, your line does not slice. It's just binding the reference directly to the object pointed to by a pointer.

Some questions on why you would want to use one over the other:

Difference between pointer and reference

Are there any benefits of passing by pointer over reference?

Pointer vs. Reference

Instead of trying to come up with differences myself, i delegate you to those in case you want to know.

Body:
Are these the same:

int foo(bar* p) {
  return p->someInt();
}

and

int foo(bar& r) {
  return r.someInt();
}

Ignore the null pointer potential. Are these two functions functionally identical no matter if someInt() is virtual or if they are passed a bar or a subclass of bar?

Does this slice anything:

bar& ref = *ptr_to_bar;

OwnerDisplayName: litb

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: litb


问:
Mips address out of range Runtime Exception
I was trying the answer from the post 2D Array in MIPS , which provides a complete coded solution for Row major matrix as user input.

```<code>    .data
read_row_matrix_prompt_p:   .asciiz "Enter an integer: "
###########################################################

.text
read_row_matrix:
        li $t3, 0               # initialize outer-loop counter to 0
    li $t2, 3
    li $t1, 3
read_row_matrix_loop_outer:
        bge $t3, $t1, read_row_matrix_loop_outer_end
        li $t4, 0               # initialize inner-loop counter to 0

read_row_matrix_loop_inner:
        bge $t4, $t2, read_row_matrix_loop_inner_end
        mul $t5, $t3, $t2       # $t5 <-- width * i
        add $t5, $t5, $t4       # $t5 <-- width * i + j
    sll $t5, $t5, 2         # $t5 <-- 2^2 * (width * i + j)
        add $t5, $t0, $t5       # $t5 <-- base address + (2^2 * (width * i + j))

        li $v0, 4               # prompt for number
        la $a0, read_row_matrix_prompt_p
        syscall

        li $v0, 5               # read a integer number
        syscall

        sw $v0, 0($t5)          # store input number into array <--- ""Error""
        addiu $t4, $t4, 1       # increment inner-loop counter
        b read_row_matrix_loop_inner    # branch unconditionally back to beginning of the inner loop

read_row_matrix_loop_inner_end:
        addiu $t3, $t3, 1       # increment outer-loop counter
        b read_row_matrix_loop_outer    # branch unconditionally back to beginning of the outer loop

read_row_matrix_loop_outer_end:
</code>```

and I have run into the following error :

```<code> line 28: Runtime exception at 0x00400048: address out of range 0x00000000
</code>```

Similar error has been posted in many questions, but each scenario seems to be local.

I realize that #t5 would actually start from $t0 to begin with, since all the initialization make it Zero. I tried to start with 1 as well for the counters and still faced the same Error.

What could be the issue here?

答:
Adding this part of the code before executing the procedure helped me initialize the array and it worked fine</p>

```<code>    mul $a0, $t1, $t2 #multiply to get the 2d array size and store in a0 register
    sll $a0, $a0, 2 #multiply the resulting output with 2^2 = 4 for integers address size location

    li  $v0, 9 #allocate address with memory size as in a0
    syscall
    move $t0,$v0 #resulting memory stored in t0 register
</code>```

Body:
I was trying the answer from the post 2D Array in MIPS , which provides a complete coded solution for Row major matrix as user input.

    .data
read_row_matrix_prompt_p:   .asciiz "Enter an integer: "
###########################################################

.text
read_row_matrix:
        li $t3, 0               # initialize outer-loop counter to 0
    li $t2, 3
    li $t1, 3
read_row_matrix_loop_outer:
        bge $t3, $t1, read_row_matrix_loop_outer_end
        li $t4, 0               # initialize inner-loop counter to 0

read_row_matrix_loop_inner:
        bge $t4, $t2, read_row_matrix_loop_inner_end
        mul $t5, $t3, $t2       # $t5 <-- width * i
        add $t5, $t5, $t4       # $t5 <-- width * i + j
    sll $t5, $t5, 2         # $t5 <-- 2^2 * (width * i + j)
        add $t5, $t0, $t5       # $t5 <-- base address + (2^2 * (width * i + j))

        li $v0, 4               # prompt for number
        la $a0, read_row_matrix_prompt_p
        syscall

        li $v0, 5               # read a integer number
        syscall

        sw $v0, 0($t5)          # store input number into array <--- ""Error""
        addiu $t4, $t4, 1       # increment inner-loop counter
        b read_row_matrix_loop_inner    # branch unconditionally back to beginning of the inner loop

read_row_matrix_loop_inner_end:
        addiu $t3, $t3, 1       # increment outer-loop counter
        b read_row_matrix_loop_outer    # branch unconditionally back to beginning of the outer loop

read_row_matrix_loop_outer_end:

and I have run into the following error :

 line 28: Runtime exception at 0x00400048: address out of range 0x00000000

Similar error has been posted in many questions, but each scenario seems to be local.

I realize that #t5 would actually start from $t0 to begin with, since all the initialization make it Zero. I tried to start with 1 as well for the counters and still faced the same Error.

What could be the issue here?

Body:
Adding this part of the code before executing the procedure helped me initialize the array and it worked fine

    mul $a0, $t1, $t2 #multiply to get the 2d array size and store in a0 register
    sll $a0, $a0, 2 #multiply the resulting output with 2^2 = 4 for integers address size location

    li  $v0, 9 #allocate address with memory size as in a0
    syscall
    move $t0,$v0 #resulting memory stored in t0 register


问:
Tensorflow - ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed
I am struggling to utilise TensorFlow within Jupyter notebook. I have installed TensorFlow via Anaconda Prompt (running as admin). But when I go to call it in my notebook I get the following error string (sorry this is long).

Any help or thoughts would be welcomed here - should I run a full uninstall and try again?

kind regards
Jack

I am running:

```<code>from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
</code>```

The error message is as follows (there are a number of others but this is the first and the rest have similar issue):

Traceback (most recent call last):
  File "C:\Users\jjcon\Anaconda3\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\jjcon\Anaconda3\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\jjcon\Anaconda3\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\jjcon\Anaconda3\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\jjcon\Anaconda3\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.

During handling of the above exception, another exception occurred:

答:
You have to install the Microsoft Visual C++ 2015-2019 Redistributable (x64) from here.

If you are facing any other issues possible reasons are

Your CPU does not support AVX2 instructions

Your CPU/Python is on 32 bits

There is a library that is in a different location/not installed on your system that cannot be loaded.

Please refer tested build configurations for windows CPU and GPU.

Body:
I am struggling to utilise TensorFlow within Jupyter notebook. I have installed TensorFlow via Anaconda Prompt (running as admin). But when I go to call it in my notebook I get the following error string (sorry this is long).

Any help or thoughts would be welcomed here - should I run a full uninstall and try again?

kind regards
Jack

I am running:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

The error message is as follows (there are a number of others but this is the first and the rest have similar issue):

Traceback (most recent call last):
  File "C:\Users\jjcon\Anaconda3\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\jjcon\Anaconda3\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\jjcon\Anaconda3\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\jjcon\Anaconda3\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\jjcon\Anaconda3\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.

During handling of the above exception, another exception occurred:


问:
What is the tidiest way to add a legend to ggplot with multiple geom_step?
I consider the following plot.

```<code>d=data.frame(x=c(1,2,4,5,7,8,9), y=c(0,2,3,5,6,7,9))
d2=data.frame(x=c(1,2,3.5,7.2,9), y=c(0,3,7,1.5,4))
ggplot() + geom_step(data=d, mapping=aes(x=x, y=y)) + geom_step(data=d2, mapping=aes(x=x, y=y), color=2)
</code>```

We have a plot with multiple (here two) step functions that have different number and location of change points on x. So I cannot directly add them to the same data.frame without more data manipulation. What would be the best option to add a legend to this plot?

答:
Here you go, name the geom with a string inside the aes, then use a named vector for the colors using those names.</p>

```<code>  ggplot() +
      geom_step(data=d, mapping=aes(x=x, y=y, color = "name1")) + #name the layer
      geom_step(data=d2, mapping=aes(x=x, y=y, color= "name2")) +
      scale_color_manual(name = "legend title",
                         values = c("name1" = "black", #match the name of the element to the name in the aes
                                    "name2" = "red"))
</code>```

Body:
I consider the following plot.

d=data.frame(x=c(1,2,4,5,7,8,9), y=c(0,2,3,5,6,7,9))
d2=data.frame(x=c(1,2,3.5,7.2,9), y=c(0,3,7,1.5,4))
ggplot() + geom_step(data=d, mapping=aes(x=x, y=y)) + geom_step(data=d2, mapping=aes(x=x, y=y), color=2)

We have a plot with multiple (here two) step functions that have different number and location of change points on x. So I cannot directly add them to the same data.frame without more data manipulation. What would be the best option to add a legend to this plot?

Body:
Here you go, name the geom with a string inside the aes, then use a named vector for the colors using those names.

  ggplot() +
      geom_step(data=d, mapping=aes(x=x, y=y, color = "name1")) + #name the layer
      geom_step(data=d2, mapping=aes(x=x, y=y, color= "name2")) +
      scale_color_manual(name = "legend title",
                         values = c("name1" = "black", #match the name of the element to the name in the aes
                                    "name2" = "red"))


问:
React native call function every time directed to a screen
My app has a page to fetch and display data from API, a DrawerItem will direct the user to this page. In this page, there are three buttons, each of them fetch different data from the API when clicked, by default, the first button is clicked when the user is directed to this page every time. When the other buttons are clicked, the data on the screen will be cleared and fetched again.

In this ShowDataScreen.js

```<code>const ShowDataScreen = props => {
    const [records, setRecords] = useState([]);

    // call this every time when this screen is focused
    useFocusEffect(
        React.useCallback(()=>{
            const fetchData = async(type) => {...fetch data and setRecords};
            fetchData('1'); // get type 1 data
        })
    )

    // call this when buttons are clicked
    const fetchData = async(type) => {
        if(type=='1'){ setTypeOneSelected(true); //set other false }
        if(type=='2'){ setTypeTwoSelected(true); //set other false }
        if(type=='3'){ setTypeThreeSelected(true); //set other false }

        // get data from api and update the screen by setRecords
        setRecords(result)
    }

    return(
        <View>
            <TouchableOpacity style={typeOneSelected?styles.selected: styles.notSelected} title="datatype1" onPress={fetchData('1')}> 1 </TouchableOpacity>
            <TouchableOpacity style={typeTwoSelected?styles.selected: styles.notSelected} title="datatype2" onPress={fetchData('2')}> 2 </TouchableOpacity>
            <TouchableOpacity style={typeThreeSelected?styles.selected: styles.notSelected} title="datatype3" onPress={fetchData('3')}> 3 </TouchableOpacity>
            <FlatList data={records}>
            // fetched data shown here
            </FlatList>
        </View>
        )
}
</code>```

Every time the user go to this page should see the type 1 data and style. If Other buttons are clicked should update the screen accordingly. How do I update the data and style correctly?

答:
As per your comment it might be the useeffect hook running continuously. You can check this sample for a working version. I've mocked the async call using a common api. This works according to the requirement.</p>

```<code>function ProfileScreen() {
  const [records, setRecords] = React.useState('');
  const [type, setType] = React.useState(1);

  useFocusEffect(
    React.useCallback(() => {
      console.log('Screen was focused');
      fetchData(1);
    }, [])
  );

  const fetchData = async (type) => {
    console.log(type);
    const data = await fetch('https://jsonplaceholder.typicode.com/todos/' + type);
    const json = await data.json();
    setRecords(json);
    setType(type);
  };

  return (
    <View>
      <TouchableOpacity
        style={type === 1 ? styles.selected : styles.notSelected}
        title="datatype1"
        onPress={() => fetchData(1)}>
        <Text>1</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={type === 2 ? styles.selected : styles.notSelected}
        title="datatype2"
        onPress={() => fetchData(2)}>
        <Text>2</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={type === 3 ? styles.selected : styles.notSelected}
        title="datatype3"
        onPress={() => fetchData(3)}>
        <Text>3</Text>
      </TouchableOpacity>
      <Text>{JSON.stringify(records)}</Text>
      <Text>{type}</Text>
    </View>
  );
}
</code>```

Body:
My app has a page to fetch and display data from API, a DrawerItem will direct the user to this page. In this page, there are three buttons, each of them fetch different data from the API when clicked, by default, the first button is clicked when the user is directed to this page every time. When the other buttons are clicked, the data on the screen will be cleared and fetched again.

In this ShowDataScreen.js

const ShowDataScreen = props => {
    const [records, setRecords] = useState([]);

    // call this every time when this screen is focused
    useFocusEffect(
        React.useCallback(()=>{
            const fetchData = async(type) => {...fetch data and setRecords};
            fetchData('1'); // get type 1 data
        })
    )

    // call this when buttons are clicked
    const fetchData = async(type) => {
        if(type=='1'){ setTypeOneSelected(true); //set other false }
        if(type=='2'){ setTypeTwoSelected(true); //set other false }
        if(type=='3'){ setTypeThreeSelected(true); //set other false }

        // get data from api and update the screen by setRecords
        setRecords(result)
    }

    return(
        <View>
            <TouchableOpacity style={typeOneSelected?styles.selected: styles.notSelected} title="datatype1" onPress={fetchData('1')}> 1 </TouchableOpacity>
            <TouchableOpacity style={typeTwoSelected?styles.selected: styles.notSelected} title="datatype2" onPress={fetchData('2')}> 2 </TouchableOpacity>
            <TouchableOpacity style={typeThreeSelected?styles.selected: styles.notSelected} title="datatype3" onPress={fetchData('3')}> 3 </TouchableOpacity>
            <FlatList data={records}>
            // fetched data shown here
            </FlatList>
        </View>
        )
}

Every time the user go to this page should see the type 1 data and style. If Other buttons are clicked should update the screen accordingly. How do I update the data and style correctly?

Body:
As per your comment it might be the useeffect hook running continuously. You can check this sample for a working version. I've mocked the async call using a common api. This works according to the requirement.

function ProfileScreen() {
  const [records, setRecords] = React.useState('');
  const [type, setType] = React.useState(1);

  useFocusEffect(
    React.useCallback(() => {
      console.log('Screen was focused');
      fetchData(1);
    }, [])
  );

  const fetchData = async (type) => {
    console.log(type);
    const data = await fetch('https://jsonplaceholder.typicode.com/todos/' + type);
    const json = await data.json();
    setRecords(json);
    setType(type);
  };

  return (
    <View>
      <TouchableOpacity
        style={type === 1 ? styles.selected : styles.notSelected}
        title="datatype1"
        onPress={() => fetchData(1)}>
        <Text>1</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={type === 2 ? styles.selected : styles.notSelected}
        title="datatype2"
        onPress={() => fetchData(2)}>
        <Text>2</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={type === 3 ? styles.selected : styles.notSelected}
        title="datatype3"
        onPress={() => fetchData(3)}>
        <Text>3</Text>
      </TouchableOpacity>
      <Text>{JSON.stringify(records)}</Text>
      <Text>{type}</Text>
    </View>
  );
}


问:
Passing a variable to setIntervall function
i am calling a jQuery plugin every 5 seconds with the following code

```<code>    var now = new Date();

    setInterval('$("#id").myplugin(now)', 1000);
</code>```

The Plugin looks like this so far:

```<code>    (function( $ ){
    $.fn.myplugin = function(now) {
        return this.each(function() {
            alert(now.getTime());
        });
    }
   })( jQuery );
</code>```

However I get the error:

Uncaught ReferenceError: now is not defined

  plugins.js:30 Uncaught TypeError: Cannot call method 'getTime' of undefined

So it looks as if the now time object doenst get passed to the plugin function and is not even defined in the setInterval method. I could probably call var now = new Date(); every time in the plugin function ... but I want to know, why it doenst work like that and how to make it work ;). thx alot.

答:
Use this instead:</p>

```<code>setInterval(function(){$("#id").myplugin(now)}, 1000);
</code>```

Body:
i am calling a jQuery plugin every 5 seconds with the following code

    var now = new Date();

    setInterval('$("#id").myplugin(now)', 1000);

The Plugin looks like this so far:

    (function( $ ){
    $.fn.myplugin = function(now) {
        return this.each(function() {
            alert(now.getTime());
        });
    }
   })( jQuery );

However I get the error:

Uncaught ReferenceError: now is not defined

  plugins.js:30 Uncaught TypeError: Cannot call method 'getTime' of undefined

So it looks as if the now time object doenst get passed to the plugin function and is not even defined in the setInterval method. I could probably call var now = new Date(); every time in the plugin function ... but I want to know, why it doenst work like that and how to make it work ;). thx alot.

Body:
Use this instead:

setInterval(function(){$("#id").myplugin(now)}, 1000);


问:
perform execution of function with multicore on nodejs
I'm trying to convert a video folder but it takes too long. This code converts one by one of the videos. I want to convert those videos in parallel without blocking the computer and reduce the time of conversion. The current code is

const exec = require('child_process').exec;
const glob = require('glob');
const fs = require('fs');

const STORAGE_PATH = './converted';
const PATH_TO_VIDEOS='./video';
const videos = glob.sync(`${PATH_TO_VIDEOS}/*.mp4`); //videos is an array of paths for each video on some folder

async function createDir(dir) {
 if (dir && !fs.existsSync(dir)) {
   await fs.mkdirSync(dir, {
     recursive: true,
   });
 }
}
async function convertVideos() {
 const starttime = new Date();
 await new Promise(async (resolve) => {

   console.log('>>>Starting conversion of', videos.length, 'files!!!');

   createDir(STORAGE_PATH);
   for (let i = 0; i < videos.length; i++) {

     let video = videos[i];

     var command = `ffmpeg -i ${video} -c:v libx264 -vf scale=1920:1080 -r 60 -c:a aac -ar 48000 -b:a 160k -strict experimental -f mp4 ${STORAGE_PATH}/${i}.mp4`;

     await new Promise((resolve) => {
       exec(command, (error, stdout, stderr) => {
         if (error) {
           console.warn(error);
         }
         resolve(stdout ? stdout : stderr);
         console.log('Video converted');
       });
     });
   }
   resolve();
 }).then(async () => await console.log('Conversion finished!!!', '\n Time of convertion', new Date() - starttime))
}

convertVideos();
```

Could you help?

答:
What you can try to do is to process the video-conversions in parallel by using Promise.all(). Something like this:

```<code>async function createDir(dir) {
    if (dir && !fs.existsSync(dir)) {
        await fs.promises.mkdir(dir, {
            recursive: true,
        });
    }
}

async function convertVideos() {

    return new Promise((resolve) => {
        console.log('>>>Starting conversion of', videos.length, 'files!!!');

        await createDir(STORAGE_PATH);
        const conversionPromises = [];
        for (let i = 0; i < videos.length; i++) {

            const video = videos[i];

            const command = `ffmpeg -i ${video} -c:v libx264 -vf scale=1920:1080 -r 60 -c:a aac -ar 48000 -b:a 160k -strict experimental -f mp4 ${STORAGE_PATH}/${i}.mp4`;

            conversionPromises.push(new Promise((resolve) => {
                    exec(command, (error, stdout, stderr) => {
                        if (error) {
                            console.warn(error);
                        }
                        resolve(stdout ? stdout : stderr);
                        console.log('Video converted');
                    });
                }));
        }
        await Promise.all(conversionPromises);
        resolve();
    }));

}

(async () => {
    const starttime = new Date();
    await convertVideos();
    console.log('Conversion finished!!!', '\n Time of convertion', new Date() - starttime)
})();
</code>```

Body:
I'm trying to convert a video folder but it takes too long. This code converts one by one of the videos. I want to convert those videos in parallel without blocking the computer and reduce the time of conversion. The current code is

const exec = require('child_process').exec;
const glob = require('glob');
const fs = require('fs');

const STORAGE_PATH = './converted';
const PATH_TO_VIDEOS='./video';
const videos = glob.sync(`${PATH_TO_VIDEOS}/*.mp4`); //videos is an array of paths for each video on some folder

async function createDir(dir) {
 if (dir && !fs.existsSync(dir)) {
   await fs.mkdirSync(dir, {
     recursive: true,
   });
 }
}
async function convertVideos() {
 const starttime = new Date();
 await new Promise(async (resolve) => {

   console.log('>>>Starting conversion of', videos.length, 'files!!!');

   createDir(STORAGE_PATH);
   for (let i = 0; i < videos.length; i++) {

     let video = videos[i];

     var command = `ffmpeg -i ${video} -c:v libx264 -vf scale=1920:1080 -r 60 -c:a aac -ar 48000 -b:a 160k -strict experimental -f mp4 ${STORAGE_PATH}/${i}.mp4`;

     await new Promise((resolve) => {
       exec(command, (error, stdout, stderr) => {
         if (error) {
           console.warn(error);
         }
         resolve(stdout ? stdout : stderr);
         console.log('Video converted');
       });
     });
   }
   resolve();
 }).then(async () => await console.log('Conversion finished!!!', '\n Time of convertion', new Date() - starttime))
}

convertVideos();

Could you help?

Body:
What you can try to do is to process the video-conversions in parallel by using Promise.all(). Something like this:

async function createDir(dir) {
    if (dir && !fs.existsSync(dir)) {
        await fs.promises.mkdir(dir, {
            recursive: true,
        });
    }
}

async function convertVideos() {

    return new Promise((resolve) => {
        console.log('>>>Starting conversion of', videos.length, 'files!!!');

        await createDir(STORAGE_PATH);
        const conversionPromises = [];
        for (let i = 0; i < videos.length; i++) {

            const video = videos[i];

            const command = `ffmpeg -i ${video} -c:v libx264 -vf scale=1920:1080 -r 60 -c:a aac -ar 48000 -b:a 160k -strict experimental -f mp4 ${STORAGE_PATH}/${i}.mp4`;

            conversionPromises.push(new Promise((resolve) => {
                    exec(command, (error, stdout, stderr) => {
                        if (error) {
                            console.warn(error);
                        }
                        resolve(stdout ? stdout : stderr);
                        console.log('Video converted');
                    });
                }));
        }
        await Promise.all(conversionPromises);
        resolve();
    }));

}

(async () => {
    const starttime = new Date();
    await convertVideos();
    console.log('Conversion finished!!!', '\n Time of convertion', new Date() - starttime)
})();


问:
I get an Uncaught Invariant Violation: could not find react-redux context value; even if my app is wrapped in a Provider
So I get the error :

Uncaught Invariant Violation: could not find react-redux context value; please ensure the component is wrapped in a Provider

With this error block right under:

```<code>The above error occurred in the <_default> component:
  in _default (created by Context.Consumer)
  in Route (created by App)
  in Switch (created by App)
  in div (created by DevMenu)
  in DevMenu (created by App)
  in Router (created by BrowserRouter)
  in BrowserRouter (created by App)
  in Suspense (created by App)
  in App (created by Root)
  in Provider (created by Root)
  in Root
</code>```

So we can see that my component Route is wrapped in the Provider. Why does the error appear!?

I dont have any idea what more I can do. Any suggestion?

When I run yarn list react-redux I get:

```<code>├─ @uma/web-assembler@0.5.0
│  └─ react-redux@7.2.0
└─ react-redux@7.1.0
</code>```

答:
That was it!

I had 2 different version of react-redux in my different package! I made sure to have the same one everywhere, and it look like it worked!

Thanks!

Body:
So I get the error :

Uncaught Invariant Violation: could not find react-redux context value; please ensure the component is wrapped in a Provider

With this error block right under:

The above error occurred in the <_default> component:
  in _default (created by Context.Consumer)
  in Route (created by App)
  in Switch (created by App)
  in div (created by DevMenu)
  in DevMenu (created by App)
  in Router (created by BrowserRouter)
  in BrowserRouter (created by App)
  in Suspense (created by App)
  in App (created by Root)
  in Provider (created by Root)
  in Root

So we can see that my component Route is wrapped in the Provider. Why does the error appear!?

I dont have any idea what more I can do. Any suggestion?

When I run yarn list react-redux I get:

├─ @uma/web-assembler@0.5.0
│  └─ react-redux@7.2.0
└─ react-redux@7.1.0


问:
Why do I have to state 'atomic=False' when I change model name in Django?
Okay so I was following Django 2.0 tutorial on the official documentation
when I realized I named a model 'Questions' instead of 'Question'. (I'm new to Django)

I already did

```<code>$ python manage.py makemigrations polls
$ python manage.py migrate
</code>```

so I thought I could just repeat this to apply the change.

Django asked me if I wanted to rename so I said yes.

```<code>(venv) H:\PycharmProjects\django_tutorials\mysite>python manage.py makemigrations
Did you rename the polls.Questions model to Question? [y/N] y
Migrations for 'polls':
  polls\migrations\0002_auto_20180804_0935.py
    - Rename model Questions to Question
</code>```

But when I tried to migrate, Django wouldn't run the migration and showed me this error.

```<code>(venv) H:\PycharmProjects\django_tutorials\mysite>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Applying polls.0001_initial... OK
  Applying polls.0002_auto_20180804_0935...Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle
    fake_initial=fake_initial,
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\db\migrations\migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\db\migrations\operations\models.py", line 330, in database_forwards
    new_model._meta.db_table,
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\db\backends\sqlite3\schema.py", line 84, in alter_db_table
    ) % old_db_table)
django.db.utils.NotSupportedError: Renaming the 'polls_questions' table while in a transaction is not supported on SQLite because it would break referential integrity. Try adding `atomic = False` to the Migration class.
</code>```

I googled and one Stackoverflow question said I should add atomic=False but he never explained why.

I also googled the official documentation for 'Non-atomic migrations' but still don't see why it's needed for a simple model name change. (It's rather hard to understand what it is for me to be honest.)

Is it really supposed to be like this to change a model name? Is there anything I'm doing wrong?

Non-atomic migrations

On databases that support DDL transactions
  (SQLite and PostgreSQL), migrations will run inside a transaction by
  default. For use cases such as performing data migrations on large
  tables, you may want to prevent a migration from running in a
  transaction by setting the atomic attribute to False:

答:
Short answer:

Yes, this is the way to change the model name. You are doing it right, just as it is explained in non-atomic migrations you mentioned.

Long answer:

From SQLite Tutorial:

SQLite is a transactional database that all changes and queries are
  atomic, consistent, isolated, and durable (ACID).

Atomic means that when you commit a transaction, either the entire
  transaction is applied or not.

By default, SQLite operates in auto-commit mode. It means that for
  each command, SQLite starts, processes, and commits the transaction
  automatically.

Now imagine you have several tables in database and you decided to rename one of them. SQLite starts automatically a transaction and within this transaction it tries to rename your table. However, your table is referenced by other tables, for ex., and so an exception is raised (as you can see from the code that was presented earlier by @EunChong Lee).

```<code>if self.connection.in_atomic_block:
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # if checked atomic, raise NotSupportedError
        raise NotSupportedError((
            'Renaming the %r table while in a transaction is not '
            'supported on SQLite because it would break referential '
            'integrity. Try adding `atomic = False` to the Migration class.'
        ) % old_db_table)
</code>```

So, when you use in you migration file the line atomic = False:

```<code>from django.db import migrations

class Migration(migrations.Migration):
    atomic = False
</code>```

you skip this exception and then you proceed with renaming your table, yeah, doesn't look all that great to me, but well.

What is happening behind the curtain is not clear for me either, I guess one should look more into the code from django\db\backends\sqlite3\schema.py to get a deeper understanding of how references are fixed with atomic=False and at what moment we should be more careful while implementing the change.

Body:
Okay so I was following Django 2.0 tutorial on the official documentation
when I realized I named a model 'Questions' instead of 'Question'. (I'm new to Django)

I already did

$ python manage.py makemigrations polls
$ python manage.py migrate

so I thought I could just repeat this to apply the change.

Django asked me if I wanted to rename so I said yes.

(venv) H:\PycharmProjects\django_tutorials\mysite>python manage.py makemigrations
Did you rename the polls.Questions model to Question? [y/N] y
Migrations for 'polls':
  polls\migrations\0002_auto_20180804_0935.py
    - Rename model Questions to Question

But when I tried to migrate, Django wouldn't run the migration and showed me this error.

(venv) H:\PycharmProjects\django_tutorials\mysite>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Applying polls.0001_initial... OK
  Applying polls.0002_auto_20180804_0935...Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle
    fake_initial=fake_initial,
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\db\migrations\migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\db\migrations\operations\models.py", line 330, in database_forwards
    new_model._meta.db_table,
  File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\db\backends\sqlite3\schema.py", line 84, in alter_db_table
    ) % old_db_table)
django.db.utils.NotSupportedError: Renaming the 'polls_questions' table while in a transaction is not supported on SQLite because it would break referential integrity. Try adding `atomic = False` to the Migration class.

I googled and one Stackoverflow question said I should add atomic=False but he never explained why.

I also googled the official documentation for 'Non-atomic migrations' but still don't see why it's needed for a simple model name change. (It's rather hard to understand what it is for me to be honest.)

Is it really supposed to be like this to change a model name? Is there anything I'm doing wrong?

Non-atomic migrations

On databases that support DDL transactions
  (SQLite and PostgreSQL), migrations will run inside a transaction by
  default. For use cases such as performing data migrations on large
  tables, you may want to prevent a migration from running in a
  transaction by setting the atomic attribute to False:

Body:
Short answer:

Yes, this is the way to change the model name. You are doing it right, just as it is explained in non-atomic migrations you mentioned.

Long answer:

From SQLite Tutorial:

SQLite is a transactional database that all changes and queries are
  atomic, consistent, isolated, and durable (ACID).

Atomic means that when you commit a transaction, either the entire
  transaction is applied or not.

By default, SQLite operates in auto-commit mode. It means that for
  each command, SQLite starts, processes, and commits the transaction
  automatically.

Now imagine you have several tables in database and you decided to rename one of them. SQLite starts automatically a transaction and within this transaction it tries to rename your table. However, your table is referenced by other tables, for ex., and so an exception is raised (as you can see from the code that was presented earlier by @EunChong Lee).

if self.connection.in_atomic_block:
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # if checked atomic, raise NotSupportedError
        raise NotSupportedError((
            'Renaming the %r table while in a transaction is not '
            'supported on SQLite because it would break referential '
            'integrity. Try adding `atomic = False` to the Migration class.'
        ) % old_db_table)

So, when you use in you migration file the line atomic = False:

from django.db import migrations

class Migration(migrations.Migration):
    atomic = False

you skip this exception and then you proceed with renaming your table, yeah, doesn't look all that great to me, but well.

What is happening behind the curtain is not clear for me either, I guess one should look more into the code from django\db\backends\sqlite3\schema.py to get a deeper understanding of how references are fixed with atomic=False and at what moment we should be more careful while implementing the change.


问:
Python decomposing a dict
I have a dict like

```<code>start = 50
end = 84
data = {
    '50-52': 781445.0,
    '52-84': 56554260.0,
    '50-73': 31204670.0,
    '73-84': 39169560.0,
    '73-75' : 23123123.0,
    '75-84' : 2312322.0
}
</code>```

What I want to achieve?

I want to traverse all possible paths from start to end, eg: for the above example

```<code>>  x = data['50-52'] + data['52-84'] = 781445.0 + 56554260.0
>  y = data['50-73'] + data['73-84'] = 31204670.0 + 39169560.0
>  z = data['50-73'] + data['73-75'] + data['75-84'] = 31204670.0 + 23123123.0 + 2312322.0
</code>```

and I would like to get a list of all possible paths from start to end that is [x, y, z]

I have sort of hit a dead end with the different ways I have been trying to approach this. I have tried to create new dict and update it with each iteration but the code seems to get very complex, any ideas on what approach I can take?

Thank you!

答:
This type of information is best represented using graphs:

```<code>import networkx as nx

data = {
    '50-52': 781445.0,
    '52-84': 56554260.0,
    '50-73': 31204670.0,
    '73-84': 39169560.0,
    '73-75' : 23123123.0,
    '75-84' : 2312322.0
}

G = nx.DiGraph()
for key, weight in data.items():
    src_str, dest_str = key.split('-')
    src_idx, dest_idx = int(src_str), int(dest_str)
    G.add_edge(src_idx, dest_idx, weight=weight)

start = 50
end = 84

all_paths = list(nx.all_simple_paths(G,
                                    source=start,
                                    target=end))
distances = [sum(G.get_edge_data(s,d)['weight'] for s,d in zip(p,p[1:]))
             for p in all_paths]

results = {tuple(p):d for p,d in zip(all_paths,distances)}

print(results)
</code>```

The results are:

```<code>{
(50, 52, 84): 57335705.0,
(50, 73, 84): 70374230.0,
(50, 73, 75, 84): 56640115.0
}
</code>```

Networkx can be a bit tricky, but it's definitely worth learning about!

Title: Python decomposing a dict

Body:
I have a dict like

start = 50
end = 84
data = {
    '50-52': 781445.0,
    '52-84': 56554260.0,
    '50-73': 31204670.0,
    '73-84': 39169560.0,
    '73-75' : 23123123.0,
    '75-84' : 2312322.0
}

What I want to achieve?

I want to traverse all possible paths from start to end, eg: for the above example

>  x = data['50-52'] + data['52-84'] = 781445.0 + 56554260.0
>  y = data['50-73'] + data['73-84'] = 31204670.0 + 39169560.0
>  z = data['50-73'] + data['73-75'] + data['75-84'] = 31204670.0 + 23123123.0 + 2312322.0

and I would like to get a list of all possible paths from start to end that is [x, y, z]

I have sort of hit a dead end with the different ways I have been trying to approach this. I have tried to create new dict and update it with each iteration but the code seems to get very complex, any ideas on what approach I can take?

Thank you!

Body:
This type of information is best represented using graphs:

import networkx as nx

data = {
    '50-52': 781445.0,
    '52-84': 56554260.0,
    '50-73': 31204670.0,
    '73-84': 39169560.0,
    '73-75' : 23123123.0,
    '75-84' : 2312322.0
}

G = nx.DiGraph()
for key, weight in data.items():
    src_str, dest_str = key.split('-')
    src_idx, dest_idx = int(src_str), int(dest_str)
    G.add_edge(src_idx, dest_idx, weight=weight)

start = 50
end = 84

all_paths = list(nx.all_simple_paths(G,
                                    source=start,
                                    target=end))
distances = [sum(G.get_edge_data(s,d)['weight'] for s,d in zip(p,p[1:]))
             for p in all_paths]

results = {tuple(p):d for p,d in zip(all_paths,distances)}

print(results)

The results are:

{
(50, 52, 84): 57335705.0,
(50, 73, 84): 70374230.0,
(50, 73, 75, 84): 56640115.0
}

Networkx can be a bit tricky, but it's definitely worth learning about!


问:
How can I make an "are you sure" prompt in a Windows batch file?
I have a batch file that automates copying a bunch of files from one place to the other and back for me. Only thing is as much as it helps me I keep accidentally selecting that command off my command buffer and mass overwriting uncommitted changes.

What code would I need for my .bat file to make it output "Are you sure?", and make me type Y before it ran the rest of the file?

If anything other than Y is typed, it should exit execution on that line.

When I call exit, it closes cmd.exe which is not what I want.

答:
First, open the terminal.

Then, type

```<code>cd ~
touch .sure
chmod 700 .sure
</code>```

Next, open .sure and paste this inside.

```<code>#!/bin/bash --init-file
PS1='> '
alias y='
    $1
    exit
'
alias n='Taskkill /IM %Terminal% /f'
echo ''
echo 'Are you sure? Answer y or n.'
echo ''
</code>```

After that, close the file.

```<code>~/.sure ; ENTER COMMAND HERE
</code>```

This will give you a prompt of are you sure before continuing the command.

Body:
First, open the terminal.

Then, type

cd ~
touch .sure
chmod 700 .sure

Next, open .sure and paste this inside.

#!/bin/bash --init-file
PS1='> '
alias y='
    $1
    exit
'
alias n='Taskkill /IM %Terminal% /f'
echo ''
echo 'Are you sure? Answer y or n.'
echo ''

After that, close the file.

~/.sure ; ENTER COMMAND HERE

This will give you a prompt of are you sure before continuing the command.


问:
Persist Youtube Data API access token in Python desktop app
I have a Python application that accesses Youtube-Data-API v3.

After the program runs for an hour, it throws an error suggesting the access token has expired.

How can I persist the token for a longer period?

答:
When you create O-Auth2 credentials, you need to select "Web App" which is what I think you're trying to create. (A website, correct?).

The "Desktop-App" option is for if you want to make a desktop application, not a website.

Desktop applications and web applications handle redirect uris differently, which is what's causing your issue.


问:
Unable to create subform with table in MS Access
i've tried creating a subform (also a subdata sheet).. to be able to track which employee has trained on what document type. I want to be able to run queries/report that i can sort either by employee name or see all employees who trained on a specific document type.

If i have 2 tables, 1 with employee names (only 27 records), and 1 with document types (about 160 records).. how do i create a relationship since the autoID numbers (or primary keys) are not the same amount?

I want to be able to have a form, that displays a datasheet where i can enter employee names and training completion dates. There could be multiple employees who trained on the same document. So far, i've only been able to link 1 employee per 1 document.

Any feedback is very much appreciated!!
Thank you!

答:
This is a many-to-many relationship and requires a third "junction" table: EmpTrng.

Data entry options:

one form bound to EmpTrng with comboboxes to select employee and training

form/subform arrangement - main form bound to Employees and subform bound to junction table with a combobox to select document

form/subform arrangement - main form bound to Documents and subform bound to junction table with a combobox to select employee


问:
Terraform: merge maps of lists and combine the lists from duplicate keys
I have something like so

```<code>locals {
  roles = [
    {
      role = "roles/admin"
      members = ["user:user@example.com"]
    },
    {
      role = "roles/viewer"
      members = ["user:user2@example.com"]
    }
  ]
}
</code>```

I want my modules to be able to export their own list of roles like

```<code>roles = [
    {
      role = "roles/viewer"
      members = ["user:newperson@example.com"]
    }
]
</code>```

And then be able to merge these things together to get

```<code>locals {
  roles = [
    {
      role = "roles/admin"
      members = ["user:user@example.com"]
    },
    {
      role = "roles/viewer"
      members = ["user:user2@example.com", "user:newperson@example.com"]
    }
  ]
}
</code>```

I know if I stored everything as maps I could merge the maps and it would work fine as long as there are no duplicate keys. But in this case I explicitly want to be able to have duplicate keys so that one module doesn't need to care about any of the other modules.

Update I was able to achieve this by doing something like so:

```<code>roles = distinct(flatten([
    for rm in local.role_maps : [
      for role, members in rm :
      {
        role = role
        members = sort(distinct(flatten([
          for m in local.role_maps :
          m[role] if lookup(m, role, null) != null
        ])))
      }
    ]
  ]))
</code>```

答:
This seems like a good application for a for expression using the ... grouping modifier, which can produce a map of lists by grouping by the keys.

```<code>variable "custom_roles" {
  type = list(object({
    role    = string
    members = list(string)
  })
}

locals {
  default_roles = [
    {
      role    = "roles/admin"
      members = ["user:user@example.com"]
    },
    {
      role    = "roles/viewer"
      members = ["user:user2@example.com"]
    }
  ]
  all_roles = concat(
    local.default_roles,
    var.custom_roles,
  )

  # First we'll project the inputs so that we have one
  # role/member pair per element.
  flat_roles = flatten([
    for r in locals.all_roles : [
      for m in r.members : {
        role   = r.role
        member = m
      }
    ]
  ])

  # Then we can use that flattened list to produce a map
  # grouped by unique role key.
  merged_roles = {
    for k, v in local.all_roles : k => v...
  }

  # Finally, if the list-of-objects representation was
  # important then we can recover it by projecting that
  # merged_roles map back into the list shape.
  merged_roles_list = tolist([
    for role, members in local.merged_roles : {
      role    = role
      members = tolist(members)
    }
  ])
}
</code>```

In the above, local.merged_roles is a map of lists, like this:

```<code>{
  "roles/admin"  = ["user:user@example.com"]
  "roles/viewer" = ["user:user2@example.com", "user:newperson@example.com"]
}
</code>```

You could potentially use that map directly, but just in case the list-of-objects form was important I included local.merged_roles_list which should match the structure you asked for your question.

Body:
I have something like so

locals {
  roles = [
    {
      role = "roles/admin"
      members = ["user:user@example.com"]
    },
    {
      role = "roles/viewer"
      members = ["user:user2@example.com"]
    }
  ]
}

I want my modules to be able to export their own list of roles like

roles = [
    {
      role = "roles/viewer"
      members = ["user:newperson@example.com"]
    }
]

And then be able to merge these things together to get

locals {
  roles = [
    {
      role = "roles/admin"
      members = ["user:user@example.com"]
    },
    {
      role = "roles/viewer"
      members = ["user:user2@example.com", "user:newperson@example.com"]
    }
  ]
}

I know if I stored everything as maps I could merge the maps and it would work fine as long as there are no duplicate keys. But in this case I explicitly want to be able to have duplicate keys so that one module doesn't need to care about any of the other modules.

Update I was able to achieve this by doing something like so:

roles = distinct(flatten([
    for rm in local.role_maps : [
      for role, members in rm :
      {
        role = role
        members = sort(distinct(flatten([
          for m in local.role_maps :
          m[role] if lookup(m, role, null) != null
        ])))
      }
    ]
  ]))

Body:
This seems like a good application for a for expression using the ... grouping modifier, which can produce a map of lists by grouping by the keys.

variable "custom_roles" {
  type = list(object({
    role    = string
    members = list(string)
  })
}

locals {
  default_roles = [
    {
      role    = "roles/admin"
      members = ["user:user@example.com"]
    },
    {
      role    = "roles/viewer"
      members = ["user:user2@example.com"]
    }
  ]
  all_roles = concat(
    local.default_roles,
    var.custom_roles,
  )

  # First we'll project the inputs so that we have one
  # role/member pair per element.
  flat_roles = flatten([
    for r in locals.all_roles : [
      for m in r.members : {
        role   = r.role
        member = m
      }
    ]
  ])

  # Then we can use that flattened list to produce a map
  # grouped by unique role key.
  merged_roles = {
    for k, v in local.all_roles : k => v...
  }

  # Finally, if the list-of-objects representation was
  # important then we can recover it by projecting that
  # merged_roles map back into the list shape.
  merged_roles_list = tolist([
    for role, members in local.merged_roles : {
      role    = role
      members = tolist(members)
    }
  ])
}

In the above, local.merged_roles is a map of lists, like this:

{
  "roles/admin"  = ["user:user@example.com"]
  "roles/viewer" = ["user:user2@example.com", "user:newperson@example.com"]
}

You could potentially use that map directly, but just in case the list-of-objects form was important I included local.merged_roles_list which should match the structure you asked for your question.