问:
Printing multiple dictionaries horizontally
I have multiple dictionaries:

```<code>dict1 = {"Hello": [1, 2, 3], "World": [1,2]}
dict2 = {"Hello": [1], "World":[2]}
dict3 =  {"Test": [1]}
</code>```

I'm trying to print these dictionaries horizontally based on the key and values from each dictionary. It will print a header (Word, Dict1, Dict2, Dict3 ... etc) then the subsequent word and value from each dictionary horizontally in the correct location.

Example output:

```<code>Word, Dict1, Dict2, Dict3
Hello, 1:2:3, 1,
World, 1:2, 2,
Test, , , 1
</code>```

Currently, I'm working with (I can fix formatting later, right now focused on just printing the correct values in the correct location):

```<code>my_dicts = [dict1, dict2, dict3]
header = "Word, " + "dict1"+", dict2"+", dict3"
all_possible_keys = set(reduce(lambda x,y: x + y.keys(), my_dicts, []))

print(header)
for k in all_possible_keys:
    print_str = "{},".format(k)
    for d in my_dicts:
        print_str += "{},".format(d.get(k, None))
    print_str += "\n"
    print(print_str)
</code>```

I'm currently getting the following error on my all_possible_keys assignment:

```<code>TypeError: can only concatenate list (not "dict_keys") to list
</code>```

Any thoughts?

答: y.keys() does not return a list. Use list(y.keys()).

Body:
I have multiple dictionaries:

dict1 = {"Hello": [1, 2, 3], "World": [1,2]}
dict2 = {"Hello": [1], "World":[2]}
dict3 =  {"Test": [1]}

I'm trying to print these dictionaries horizontally based on the key and values from each dictionary. It will print a header (Word, Dict1, Dict2, Dict3 ... etc) then the subsequent word and value from each dictionary horizontally in the correct location.

Example output:

Word, Dict1, Dict2, Dict3
Hello, 1:2:3, 1,
World, 1:2, 2,
Test, , , 1

Currently, I'm working with (I can fix formatting later, right now focused on just printing the correct values in the correct location):

my_dicts = [dict1, dict2, dict3]
header = "Word, " + "dict1"+", dict2"+", dict3"
all_possible_keys = set(reduce(lambda x,y: x + y.keys(), my_dicts, []))

print(header)
for k in all_possible_keys:
    print_str = "{},".format(k)
    for d in my_dicts:
        print_str += "{},".format(d.get(k, None))
    print_str += "\n"
    print(print_str)

I'm currently getting the following error on my all_possible_keys assignment:

TypeError: can only concatenate list (not "dict_keys") to list

Any thoughts?


来源: stackexchange

问:
Accessing a control created at runtime
I am new to c# and wpf.

If I create a control in XAML, I can access its properties anywhere in my code.
However, if I create a control at runtime, it shows up as null when I try to access it outside the method it was created.

```<code>public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
        Button newBtn = new Button();

        newBtn.Content = "Test";
        newBtn.Name = "btnTest";
        spTest.Children.Add(newBtn);

    }

    private void WPFButton_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
         //I want to access the button called btnTest and display the name of the button
    }
}
</code>```

答:
The most easiest way is storing a reference to the button in a field:

```<code>public partial class MainWindow : Window
{
    private Button _newBtn;

    public MainWindow()
    {
        InitializeComponent();
        _newBtn = new Button();

        _newBtn.Content = "Test";
        _newBtn.Name = "btnTest";  // < the name is not needed, because you already have a reference. (so you don't have to use FindControl)
        // and if you want to register the click event.
        _newBtn.Click += Button_Click;
        spTest.Children.Add(_newBtn);
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Button clicked");
    }

    private void WPFButton_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        //I want to access the button called btnTest and display the name of the button
        _newBtn.Content = "Test2";
    }
}
</code>```

If you want to store multiple controls, use a dictionary or list.

ContentLicense: CC BY-SA 4.0

Title: Accessing a control created at runtime

Body:
I am new to c# and wpf.

If I create a control in XAML, I can access its properties anywhere in my code.
However, if I create a control at runtime, it shows up as null when I try to access it outside the method it was created.

public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
        Button newBtn = new Button();

        newBtn.Content = "Test";
        newBtn.Name = "btnTest";
        spTest.Children.Add(newBtn);

    }

    private void WPFButton_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
         //I want to access the button called btnTest and display the name of the button
    }
}

Body:
The most easiest way is storing a reference to the button in a field:

public partial class MainWindow : Window
{
    private Button _newBtn;

    public MainWindow()
    {
        InitializeComponent();
        _newBtn = new Button();

        _newBtn.Content = "Test";
        _newBtn.Name = "btnTest";  // < the name is not needed, because you already have a reference. (so you don't have to use FindControl)
        // and if you want to register the click event.
        _newBtn.Click += Button_Click;
        spTest.Children.Add(_newBtn);
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Button clicked");
    }

    private void WPFButton_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        //I want to access the button called btnTest and display the name of the button
        _newBtn.Content = "Test2";
    }
}

If you want to store multiple controls, use a dictionary or list.


问:
How to prevent snakemake from deleting output folders from failed jobs?
I have a rule that iterates over a file pulls out the Fastq file paths  and runs trimGalore on the Fastq files. However some of the files are corrupted / truncated and so trimGalore fails to process them. It continues to run on remaining files but the overall rule fails and deletes the output folder with the successfully processed files too. How do I retain the output folder?

I tried altering the shell command to ignore exit status but snakemake seems to enforce set -euo pipefailwithin a shell element of the run.

```<code>rule trimGalore:
    """
    This module takes in the temporary file created by parse sampleFile rule and determines if libraries are single end or paired end.
    The appropriate step for trimGalore is then ran and a summary of the runs is produced in summary_tg.txt
    """
    input:
        rules.parse_sampleFile.output[1]+"singleFile.txt", rules.parse_sampleFile.output[1]+"pairFile.txt"
    output:
        directory(projectDir+"/trimmed_reads/")
    log:
        projectDir+"/logs/"+stamp+"_trimGalore.log"
    params:
        p = trimGaloreParams
    shell:
        """
        (awk -F "," '{{print $2}}' {input[0]} |while read i; do echo $(date +"%Y-%m-%d %H:%M:%S") >>{log}; echo "$USER">>{log}; trim_galore {params.p} --gzip -o {output} $i; done
        awk -F "," '{{print $2" "$3}}' {input[1]} |while read i; do echo $(date +"%Y-%m-%d %H:%M:%S") >>{log}; echo "$USER">>{log}; trim_galore --paired {params.p} --gzip -o {output} $i; done) 2>>{log}
        """
</code>```

I am happy that it continues to process the remaining Fastq files if one fails but I want the rule output folder to be kept when the job finishes and fails. I want to continue to process the non truncated files

答:
I had a similar-ish issue, my approach was to create a dummy file for the output, and move my/your output to params.

```<code>rule trimGalore:
    """
    This module takes in the temporary file created by parse sampleFile rule and determines if libraries are single end or paired end.
    The appropriate step for trimGalore is then ran and a summary of the runs is produced in summary_tg.txt
    """
    input:
        rules.parse_sampleFile.output[1]+"singleFile.txt", rules.parse_sampleFile.output[1]+"pairFile.txt"
    output:
        dummy = dummy.txt,
    log:
        projectDir+"/logs/"+stamp+"_trimGalore.log"
    params:
        p = trimGaloreParams,
        dir = directory(projectDir+"/trimmed_reads/")
    shell:
        """
        (awk -F "," '{{print $2}}' {input[0]} |while read i; do echo $(date +"%Y-%m-%d %H:%M:%S") >>{log}; echo "$USER">>{log}; trim_galore {params.p} --gzip -o {params.dir} $i; done
        awk -F "," '{{print $2" "$3}}' {input[1]} |while read i; do echo $(date +"%Y-%m-%d %H:%M:%S") >>{log}; echo "$USER">>{log}; trim_galore --paired {params.p} --gzip -o {params.dir} $i; done) 2>>{log}  && touch {output.dummy}
        """
</code>```

I cannot test this and you may need to tinker a bit...it may bear fruit.

Body:
I have a rule that iterates over a file pulls out the Fastq file paths  and runs trimGalore on the Fastq files. However some of the files are corrupted / truncated and so trimGalore fails to process them. It continues to run on remaining files but the overall rule fails and deletes the output folder with the successfully processed files too. How do I retain the output folder?

I tried altering the shell command to ignore exit status but snakemake seems to enforce set -euo pipefailwithin a shell element of the run.

rule trimGalore:
    """
    This module takes in the temporary file created by parse sampleFile rule and determines if libraries are single end or paired end.
    The appropriate step for trimGalore is then ran and a summary of the runs is produced in summary_tg.txt
    """
    input:
        rules.parse_sampleFile.output[1]+"singleFile.txt", rules.parse_sampleFile.output[1]+"pairFile.txt"
    output:
        directory(projectDir+"/trimmed_reads/")
    log:
        projectDir+"/logs/"+stamp+"_trimGalore.log"
    params:
        p = trimGaloreParams
    shell:
        """
        (awk -F "," '{{print $2}}' {input[0]} |while read i; do echo $(date +"%Y-%m-%d %H:%M:%S") >>{log}; echo "$USER">>{log}; trim_galore {params.p} --gzip -o {output} $i; done
        awk -F "," '{{print $2" "$3}}' {input[1]} |while read i; do echo $(date +"%Y-%m-%d %H:%M:%S") >>{log}; echo "$USER">>{log}; trim_galore --paired {params.p} --gzip -o {output} $i; done) 2>>{log}
        """

I am happy that it continues to process the remaining Fastq files if one fails but I want the rule output folder to be kept when the job finishes and fails. I want to continue to process the non truncated files

Body:
I had a similar-ish issue, my approach was to create a dummy file for the output, and move my/your output to params.

rule trimGalore:
    """
    This module takes in the temporary file created by parse sampleFile rule and determines if libraries are single end or paired end.
    The appropriate step for trimGalore is then ran and a summary of the runs is produced in summary_tg.txt
    """
    input:
        rules.parse_sampleFile.output[1]+"singleFile.txt", rules.parse_sampleFile.output[1]+"pairFile.txt"
    output:
        dummy = dummy.txt,
    log:
        projectDir+"/logs/"+stamp+"_trimGalore.log"
    params:
        p = trimGaloreParams,
        dir = directory(projectDir+"/trimmed_reads/")
    shell:
        """
        (awk -F "," '{{print $2}}' {input[0]} |while read i; do echo $(date +"%Y-%m-%d %H:%M:%S") >>{log}; echo "$USER">>{log}; trim_galore {params.p} --gzip -o {params.dir} $i; done
        awk -F "," '{{print $2" "$3}}' {input[1]} |while read i; do echo $(date +"%Y-%m-%d %H:%M:%S") >>{log}; echo "$USER">>{log}; trim_galore --paired {params.p} --gzip -o {params.dir} $i; done) 2>>{log}  && touch {output.dummy}
        """

I cannot test this and you may need to tinker a bit...it may bear fruit.


问:
iOS 13 In Tab Bar child view controller viewWillAppear is not called
I have a tab bar controller and I have added five view controllers in it like this:

```<code>class InfluencerMainTabBarController: UITabBarController {
override func viewDidLoad() {
    super.viewDidLoad()

    let findWorkVC = UINavigationController.init(rootViewController: InfluencerFindWorkVC.instantiate(fromAppStoryboard: .Influencer))
    findWorkVC.tabBarItem = UITabBarItem(title: nil, image: #imageLiteral(resourceName: "ic_home"), tag: 0)

    let inboxVC = UINavigationController.init(rootViewController: InfluencerInboxVC.instantiate(fromAppStoryboard: .Inbox))
    inboxVC.tabBarItem = UITabBarItem(title: nil, image: #imageLiteral(resourceName: "ic_inbox"), tag: 1)

    let workDiaryVC = UINavigationController.init(rootViewController: InfluencerWorkDiaryVC.instantiate(fromAppStoryboard: .Influencer))
    workDiaryVC.tabBarItem = UITabBarItem(title: nil, image: #imageLiteral(resourceName: "ic_work"), tag: 2)

    let notificationsVC = InfluencerNotificationsVC.instantiate(fromAppStoryboard: .Influencer)
    notificationsVC.tabBarItem = UITabBarItem(title: nil, image: #imageLiteral(resourceName: "ic_notification"), tag: 3)

    let accountVC = InfluencerProfileVC.instantiate(fromAppStoryboard: .Influencer)
    accountVC.tabBarItem = UITabBarItem(title: nil, image: #imageLiteral(resourceName: "ic_profile"), tag: 4)

    let tabBarList = [findWorkVC, inboxVC, workDiaryVC, notificationsVC, accountVC]

    viewControllers = tabBarList

    self.tabBar.tintColor = UIColor.appPurpleColor
    self.tabBar.barTintColor = UIColor.white
}
}
</code>```

Problem is my first controller, which is findWorkVC, its viewWillAppear is getting called but when I click on any other view controller, their viewWillAppear are not getting called.

It is working fine pre iOS 13 devices but on iOS 13 its not just getting called and also the height of navigation bar is lesser than iOS 12's navigation bar height, you can see the title in navigation bar is just overlapping the status bar text.

答: If your presentation style is not the new default by Apple (sheet), than just set the presentation style for all your ViewControllers (NavigationController included) to FullScreen. This way the viewWillAppear method will be called again for every VC. </p>

Body:
I have a tab bar controller and I have added five view controllers in it like this:

class InfluencerMainTabBarController: UITabBarController {
override func viewDidLoad() {
    super.viewDidLoad()

    let findWorkVC = UINavigationController.init(rootViewController: InfluencerFindWorkVC.instantiate(fromAppStoryboard: .Influencer))
    findWorkVC.tabBarItem = UITabBarItem(title: nil, image: #imageLiteral(resourceName: "ic_home"), tag: 0)

    let inboxVC = UINavigationController.init(rootViewController: InfluencerInboxVC.instantiate(fromAppStoryboard: .Inbox))
    inboxVC.tabBarItem = UITabBarItem(title: nil, image: #imageLiteral(resourceName: "ic_inbox"), tag: 1)

    let workDiaryVC = UINavigationController.init(rootViewController: InfluencerWorkDiaryVC.instantiate(fromAppStoryboard: .Influencer))
    workDiaryVC.tabBarItem = UITabBarItem(title: nil, image: #imageLiteral(resourceName: "ic_work"), tag: 2)

    let notificationsVC = InfluencerNotificationsVC.instantiate(fromAppStoryboard: .Influencer)
    notificationsVC.tabBarItem = UITabBarItem(title: nil, image: #imageLiteral(resourceName: "ic_notification"), tag: 3)

    let accountVC = InfluencerProfileVC.instantiate(fromAppStoryboard: .Influencer)
    accountVC.tabBarItem = UITabBarItem(title: nil, image: #imageLiteral(resourceName: "ic_profile"), tag: 4)

    let tabBarList = [findWorkVC, inboxVC, workDiaryVC, notificationsVC, accountVC]

    viewControllers = tabBarList

    self.tabBar.tintColor = UIColor.appPurpleColor
    self.tabBar.barTintColor = UIColor.white
}
}

Problem is my first controller, which is findWorkVC, its viewWillAppear is getting called but when I click on any other view controller, their viewWillAppear are not getting called.

It is working fine pre iOS 13 devices but on iOS 13 its not just getting called and also the height of navigation bar is lesser than iOS 12's navigation bar height, you can see the title in navigation bar is just overlapping the status bar text.


问:
How to customize Allure report to add new status to allure status report?
I have allure report integrated with our testng automation framework. And, we are trying to get the allure reporting customized in such a way that we would be able to get the pass% for the Priority 1 test cases.
At the moment, the allure report only contains the Failed, Broken, Canceled, Pending, and Passed test cases. Is there a way I can maybe add another category to the report say "P1 Tests"?</p>

答:
There's a feature that lets you set a tests severity:
https://docs.qameta.io/allure/#_severity_3

I'm not aware of a way to show test status by severity in %. The "Graphs" category has a widget that comes close to it. It shows each test status in columns according to amount of tests. You can see how many tests failed, are brocken, etc for each level of severity.

There are 5 levels:

blocker

critical

normal

minor

trivial

Example from the docs:

```<code>public class MyTest {
    @Test
    @Severity(SeverityLevel.CRITICAL)
    public void testSomething() throws Exception {
        // ...
    }
}
</code>```

Body:
There's a feature that lets you set a tests severity:
https://docs.qameta.io/allure/#_severity_3

I'm not aware of a way to show test status by severity in %. The "Graphs" category has a widget that comes close to it. It shows each test status in columns according to amount of tests. You can see how many tests failed, are brocken, etc for each level of severity.

There are 5 levels:

blocker

critical

normal

minor

trivial

Example from the docs:

public class MyTest {
    @Test
    @Severity(SeverityLevel.CRITICAL)
    public void testSomething() throws Exception {
        // ...
    }
}


问:
From Notification: AlertDialog without UI
I'm creating a notification which fires an Intent. Here a really shortened excerpt of my code...

```<code>Notification notification = new Notification(R.drawable.icon, "notification", System.currentTimeMillis());
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(BackgroundService.this, ConnectionHandler.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.addFlags(Intent.FLAG_FROM_BACKGROUND);

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, getString(R.string.notification_title), getString(R.string.notification_body), pendingIntent);
notification.flags |= notification.FLAG_AUTO_CANCEL;
nm.notify(1, notification);
</code>```

In my intent (ConnectionHandler.class), I'd like to show an AlertDialog, which works. But I'd like the AlertDialog to show up without opening a new UI-Window. The best for me was if the AlertDialog simply appears without anything else when tapping the notification-entry.

Any idea is appreciated.

Regards, Tobi

答:
From the Dev Guide:

Showing a Dialog

A dialog is always created and displayed as a part of an Activity.

The easy alternative is to create a very basic Activity, with nothing showing up except the dialog, and calling finish() as soon as the dialog is dismissed.

ContentLicense: CC BY-SA 3.0

Body:
I'm creating a notification which fires an Intent. Here a really shortened excerpt of my code...

Notification notification = new Notification(R.drawable.icon, "notification", System.currentTimeMillis());
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(BackgroundService.this, ConnectionHandler.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.addFlags(Intent.FLAG_FROM_BACKGROUND);

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, getString(R.string.notification_title), getString(R.string.notification_body), pendingIntent);
notification.flags |= notification.FLAG_AUTO_CANCEL;
nm.notify(1, notification);

In my intent (ConnectionHandler.class), I'd like to show an AlertDialog, which works. But I'd like the AlertDialog to show up without opening a new UI-Window. The best for me was if the AlertDialog simply appears without anything else when tapping the notification-entry.

Any idea is appreciated.

Regards, Tobi


问:
Use String.Split to split by character in c#
I have a string named String1. How can I use String.Split to split it by letters into letters[].

As an example, say String1 = "Hello World". How can I split it so that letters[0] = H, letters[1] = e, letters[2] = l, and so on.

答:
String class in .NET has an indexer, which allows you to access the char value at specific position in a string. So, you can do something like that

var String1 = "Hello World";
var letter = String1[0]; //equals `H`
letter = String1[1]; //equals `e`
```

<p>Another option is to use <code>ToCharArray</code> method, it copies the characters from a <code>string</code> instance to a character array</p>

<pre class="lang-cs prettyprint-override"><code>var String1 = "Hello World";
var array = String1.ToCharArray();
</code>```

But there is no need to copy the string to a char array (unless you have a good reason for that), indexer is just enough

Body:
String class in .NET has an indexer, which allows you to access the char value at specific position in a string. So, you can do something like that

var String1 = "Hello World";
var letter = String1[0]; //equals `H`
letter = String1[1]; //equals `e`

Another option is to use ToCharArray method, it copies the characters from a string instance to a character array

var String1 = "Hello World";
var array = String1.ToCharArray();

But there is no need to copy the string to a char array (unless you have a good reason for that), indexer is just enough


问:
Passing data from Node.js to Vue.js
I have an issue with passing data from Node.js code to Vue.js

my Vue.js part:

```<code><p class="align-self-center m-0">Name</p>
<div v-for="info in infos" v-bind:key="info">
   {{info}}
</div>
</code>```

and Node.js part:

```<code>import axios from 'axios';

export default {
  name: 'section1',
  data () {
    return {
      infos:""
    }
  },
  mounted(){
  let headers = {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
    };
    axios.get('http://localhost:5000/api/v1/profile/5e21990d8d18cf33f8adf94a',{ headers })
    .then( response => {
        var user = JSON.parse( response.data ).results[0]
        console.log(user)
        this.infos = user.name
        })

  }

}
</code>```

I want to pass the infos i.e user.name to my view.
Thank you for your help.

答:
Tips:

You don't need axios or smth. third party request client, fetch works everywhere.

Probably your backend responds with what you need, just pass into vue w/o picking which one needed.

I didn't tested code below but your question might covered like this, if it solves your problem or clarify something please verify the answer.

```<code><template>
  <span>Name {{user.name}}</span>
</template>

<script>
export default {
  data() {
    return {
      user: {}
    };
  },
  async mounted() {
    // API URL must be constant, should be in config.
    const API_URL = "http://localhost:5000/api/v1/profile/5e21990d8d18cf33f8adf94a";
    // Custom headers, but no need for content-type.
    const headers = new Headers({
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*"
    });

    // If the fetch fails,
    try {
      // Fetch with custom headers.
      const user = await fetch(API_URL, { headers })
        .then(response => response.json())
        .then(users => users[0]);
      // Then set the user object to data
      this.user = user;
    } catch (err) {
      console.error(err);
    }
  }
};
</script>
</code>```

Title: Passing data from Node.js to Vue.js

Body:
I have an issue with passing data from Node.js code to Vue.js

my Vue.js part:

Name

   {{info}}

and Node.js part:

import axios from 'axios';

export default {
  name: 'section1',
  data () {
    return {
      infos:""
    }
  },
  mounted(){
  let headers = {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
    };
    axios.get('http://localhost:5000/api/v1/profile/5e21990d8d18cf33f8adf94a',{ headers })
    .then( response => {
        var user = JSON.parse( response.data ).results[0]
        console.log(user)
        this.infos = user.name
        })

  }

}

I want to pass the infos i.e user.name to my view.
Thank you for your help.

Body:
Tips:

You don't need axios or smth. third party request client, fetch works everywhere.

Probably your backend responds with what you need, just pass into vue w/o picking which one needed.

I didn't tested code below but your question might covered like this, if it solves your problem or clarify something please verify the answer.

<template>
  <span>Name {{user.name}}</span>
</template>

<script>
export default {
  data() {
    return {
      user: {}
    };
  },
  async mounted() {
    // API URL must be constant, should be in config.
    const API_URL = "http://localhost:5000/api/v1/profile/5e21990d8d18cf33f8adf94a";
    // Custom headers, but no need for content-type.
    const headers = new Headers({
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*"
    });

    // If the fetch fails,
    try {
      // Fetch with custom headers.
      const user = await fetch(API_URL, { headers })
        .then(response => response.json())
        .then(users => users[0]);
      // Then set the user object to data
      this.user = user;
    } catch (err) {
      console.error(err);
    }
  }
};
</script>


问:
How to take multiple key input in wxwidgets?
As I am making a game in Wxwidgets. The place where i am stuck is to jump Mario and take the input when the Mario is jumping in the air. Let me make you clear - When an player press space to jump vertical
the loop to jump Mario will run but when the player presses the "d" key to move forward while jumping it should jump forward.... i also need your help to take two input at the same time like in game when we press shift and "w" the player will walk faster but when we press only "w" key the player will walk slow..

```<code>void MyFrame :: OnChar(wxKeyEvent& event){
     wxChar  uc = event.GetUnicodeKey();
           switch ( uc )
         {
             case 97:
                        tempx = x;
                        x = x - 5;
                        Check(x);
                        FindGround(x);
                        CheckForNextMove(x,y,CurrentGroundX,CurrentGroundY,PreviousGroundX,PreviousGroundY,NextGroundX,NextGroundY);
                        Refresh();
                        break;
             case 100:
                        tempx =x;
                        x = x + 5;
                        Check(x);
                        FindGround(x);
                        CheckForNextMove(x,y,CurrentGroundX,CurrentGroundY,PreviousGroundX,PreviousGroundY,NextGroundX,NextGroundY);
                        Refresh();
                        break;
            case 32:
            tempy = y;
                for(int i=0;i<=10;i++){
                    check = true;
                    tempx = x;
                    Sleep(1);
                        y=y-7;
                        x=x+5;
                        Check(x);
                        FindGround(x);
                        CheckForNextMove(x,y,CurrentGroundX,CurrentGroundY,PreviousGroundX,PreviousGroundY,NextGroundX,NextGroundY);
                        Update();
                        Refresh();
                                              }
                for(int j=0;j<=10;j++){
                    check = true;
                    tempx = x;
                    Sleep(1);
                        y=y+7;
                        x=x+5;
                        Check(x);
                        FindGround(x);
                        CheckForNextMove(x,y,CurrentGroundX,CurrentGroundY,PreviousGroundX,PreviousGroundY,NextGroundX,NextGroundY);
                        Update();
                        Refresh();
                        if(stop){ stop = false; break; }
                                              }
                        check = false;
                        Update();
                        Refresh();
                        break;
 }
event.Skip();
}
</code>```

here is the code where pressing space bar will make mario to jump in parabolic path but i wanted to make it more professional. I want mario to jump in parabolic when we press two key at the same time i.e. (when I press vertical jump key and right motion key then it will have to jump in right direction in parabolic path.

答:
You need to change your program control flow to only remember that a key was pressed or released in wxEVT_KEY_{DOWN,UP} handlers instead of trying to do everything in wxEVT_CHAR handler.

Also, you definitely shouldn't ever have any calls to Sleep() or long-running loops in the event handlers, so whenever you think about putting them there, you can be sure that you're doing something wrong.

Body:
As I am making a game in Wxwidgets. The place where i am stuck is to jump Mario and take the input when the Mario is jumping in the air. Let me make you clear - When an player press space to jump vertical
the loop to jump Mario will run but when the player presses the "d" key to move forward while jumping it should jump forward.... i also need your help to take two input at the same time like in game when we press shift and "w" the player will walk faster but when we press only "w" key the player will walk slow..

void MyFrame :: OnChar(wxKeyEvent& event){
     wxChar  uc = event.GetUnicodeKey();
           switch ( uc )
         {
             case 97:
                        tempx = x;
                        x = x - 5;
                        Check(x);
                        FindGround(x);
                        CheckForNextMove(x,y,CurrentGroundX,CurrentGroundY,PreviousGroundX,PreviousGroundY,NextGroundX,NextGroundY);
                        Refresh();
                        break;
             case 100:
                        tempx =x;
                        x = x + 5;
                        Check(x);
                        FindGround(x);
                        CheckForNextMove(x,y,CurrentGroundX,CurrentGroundY,PreviousGroundX,PreviousGroundY,NextGroundX,NextGroundY);
                        Refresh();
                        break;
            case 32:
            tempy = y;
                for(int i=0;i<=10;i++){
                    check = true;
                    tempx = x;
                    Sleep(1);
                        y=y-7;
                        x=x+5;
                        Check(x);
                        FindGround(x);
                        CheckForNextMove(x,y,CurrentGroundX,CurrentGroundY,PreviousGroundX,PreviousGroundY,NextGroundX,NextGroundY);
                        Update();
                        Refresh();
                                              }
                for(int j=0;j<=10;j++){
                    check = true;
                    tempx = x;
                    Sleep(1);
                        y=y+7;
                        x=x+5;
                        Check(x);
                        FindGround(x);
                        CheckForNextMove(x,y,CurrentGroundX,CurrentGroundY,PreviousGroundX,PreviousGroundY,NextGroundX,NextGroundY);
                        Update();
                        Refresh();
                        if(stop){ stop = false; break; }
                                              }
                        check = false;
                        Update();
                        Refresh();
                        break;
 }
event.Skip();
}

here is the code where pressing space bar will make mario to jump in parabolic path but i wanted to make it more professional. I want mario to jump in parabolic when we press two key at the same time i.e. (when I press vertical jump key and right motion key then it will have to jump in right direction in parabolic path.


问:
How to write this IF statement in Linear programming with Big-M
I have to define a variable based on the decision variable (Var[i]).
This is what I want to express:

```<code>if var[i] >= 0, b[i] = 1.08; else b[i] = 0.91
</code>```

What I wrote was :

```<code>var=LpVariable.dicts("Var", df.index, lowBound=-2, upBound=2, cat="Continuous")

b={}
for i in df.index:
    if var[i] >= 0.0:
       b[i] = 1.08
    else:
       b[i] = 0.91
</code>```

However, it turned out that all b[i] were 1.08...;
I searched for the problems, and found that it should be replaced by "Big M" method. But I still can't catch how to derive it.

答:
There are many ways of implementing this.

Here is a way using binary variables δ. For simplicity, I am dropping here the index i for all variables. First, assume we have good bounds on x, e.g. L ≤ x ≤ U (with L<0). Then we can state:

```<code> x ≤ -ε + δ M1
 x ≥ -(1-δ) M2
 b = 1.08 δ + 0.91(1-δ)
 δ ∈ {0,1}
 x ∈ [L,U] (with L<0)
</code>```

where ε≥0 is a small constant (e.g. ε=0.0001). In practice, I just use ε=0 in these cases. (This essentially lets the solver decide what happens at x=0; that means it will pick the most profitable choice). The big-M constants M1 and M2 can be set to:

```<code> M1 = ε+U
 M2 = -L
</code>```

More advanced systems will allow SOS1 variables. With a SOS1 approach, we no longer need big-M constants or good bounds. Read the manual of your LP/MIP solver or modeling tool to find out if this is supported.

Body:
I have to define a variable based on the decision variable (Var[i]).
This is what I want to express:

if var[i] >= 0, b[i] = 1.08; else b[i] = 0.91

What I wrote was :

var=LpVariable.dicts("Var", df.index, lowBound=-2, upBound=2, cat="Continuous")

b={}
for i in df.index:
    if var[i] >= 0.0:
       b[i] = 1.08
    else:
       b[i] = 0.91

However, it turned out that all b[i] were 1.08...;
I searched for the problems, and found that it should be replaced by "Big M" method. But I still can't catch how to derive it.

Body:
There are many ways of implementing this.

Here is a way using binary variables δ. For simplicity, I am dropping here the index i for all variables. First, assume we have good bounds on x, e.g. L ≤ x ≤ U (with L<0). Then we can state:

 x ≤ -ε + δ M1
 x ≥ -(1-δ) M2
 b = 1.08 δ + 0.91(1-δ)
 δ ∈ {0,1}
 x ∈ [L,U] (with L<0)

where ε≥0 is a small constant (e.g. ε=0.0001). In practice, I just use ε=0 in these cases. (This essentially lets the solver decide what happens at x=0; that means it will pick the most profitable choice). The big-M constants M1 and M2 can be set to:

 M1 = ε+U
 M2 = -L

More advanced systems will allow SOS1 variables. With a SOS1 approach, we no longer need big-M constants or good bounds. Read the manual of your LP/MIP solver or modeling tool to find out if this is supported.


问:
Using Gatsby JS and markdown MDX, how can I render HTML5 animations in MDX?
Setting up a personal blog with Gatsby JS, using the excellent Chronoblog theme. I need to embed small clips of HTLM5 animations, inside a markdown MDX document.

The animations-presentations are created from Google WEB Designer and are exported locally as assets; js and html files.

Any suggestions?

答:
I didn't had an error but looking for a direction, should I use a plugin ? Which one? Other ideas...

From what I found, there is basically 2 options to create animated presentation in MDX documents;  use an app that creates html5 containers (Google Web designer, Tumult Hype...)  and find a way to present them into an MDX document or, to use third party apps were you only have to put an iframe in the page.

After trying many options, I reverted to use iframes for the simplicity. Tried many apps like Visme, Greensock and others, to finally go with Reveal.js-Slides.com.

First post here, got a "-1" and answered my own question... Hum.

Thanks.

François


问:
How can I change the colour of selected text in a WPF ComboBox?
In my application, I have defined the following style for TextBlocks.

```<code><Style TargetType="{x:Type TextBlock}">
    <Setter Property="FontFamily" Value="Arial"/>
    <Setter Property="FontSize" Value="11"/>
    <Setter Property="Foreground" Value="{StaticResource TextBrush}"/>
    <Setter Property="Opacity" Value="1.0"/>
    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Opacity" Value="0.40"/>
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

The style is intentionally defined at the highest level of my application so that it applies to all TextBlocks by default.

The problem is that this style breaks the behaviour of TextBlocks in ComboBoxes. Normally, the selected item in a ComboBox has its Foreground colour change to white. With this style applied however, the foreground colour of the text does not change.

How can I trigger the text to change colour when the TextBlock in a ComboBox is highlighted?

答:
I resolved this issue by moving the styles out of app.xaml and into a separate resource dictionary that I include as needed in my application Window & Pages.

This stops the TextBlock style from affecting the colour of the text in the ComboBox. Finally, to achieve the text colour I wanted on all items I overrode the following default system colours with my own.

```<code><SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}"
                 Color="{StaticResource TextColor}"/>

<SolidColorBrush x:Key="{x:Static SystemColors.WindowTextBrushKey}"
                 Color="{StaticResource TextColor}"/>
</code>```

Body:
In my application, I have defined the following style for TextBlocks.

</Style>

The style is intentionally defined at the highest level of my application so that it applies to all TextBlocks by default.

The problem is that this style breaks the behaviour of TextBlocks in ComboBoxes. Normally, the selected item in a ComboBox has its Foreground colour change to white. With this style applied however, the foreground colour of the text does not change.

How can I trigger the text to change colour when the TextBlock in a ComboBox is highlighted?

Body:
I resolved this issue by moving the styles out of app.xaml and into a separate resource dictionary that I include as needed in my application Window & Pages.

This stops the TextBlock style from affecting the colour of the text in the ComboBox. Finally, to achieve the text colour I wanted on all items I overrode the following default system colours with my own.

<SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}"
                 Color="{StaticResource TextColor}"/>

<SolidColorBrush x:Key="{x:Static SystemColors.WindowTextBrushKey}"
                 Color="{StaticResource TextColor}"/>


问:
How can I create raster plots with the same colour scale in R
I'm creating some maps from raster files using the "raster" package in R. I'd like to create comparison rasters, showing several maps side by side. It's important for this that the colour scales used are the same for all maps, regardless of the values in each map. For example, if map 1 has values from 0-1, and map 2 has values from 0-0.5, cells with a value of 0.5 should have the same colour on both maps.

For example:

map 1 has values from 0 to 1

map 2 has values from 0 to 0.5

the colour goes from red (lowest) to green (highest)

I would like a value of 0.5 to have the same colour in both maps (i.e. yellow, as halfway between red and green). The current behaviour is that it is yellow in map 1, and green in map 2.

I can't find a way to make this work. I can't see any way to set the range of pixel values to use with the plotting function. setMinMax() doesn't help (as 'plot' always calculates the values). Even trying to set the values by hand (e.g. g1@data@max <- 10) doesn't work (these are ignored when plotting).

Finally, making a stack of the maps (which might be expected to plot everything on the same colour scale) doesn't work either - each map still has it's own colour scale.

Any thoughts on how to do this?

EDIT:

The solution I ended up using is:

```<code>plot( d, col=rev( rainbow( 99, start=0,end=1 ) ), breaks=seq(min(minValue( d )),max(maxValue(d)),length.out=100) )
</code>```

答:
A pretty simple solution that should usually work (e.g. with the "plot" function in the raster package) is to set "z axis" limits (which control the colors and the color legend).

E.g. you can do something like:
plot(d, zlim=c(0,1))

where d is a stacked raster object. Or, if you have a bunch of separate rasters d1, d2, d2..., you can just do:
plot(d1, zlim=c(0,1))
plot(d2, zlim=c(0,1))
plot(d3, zlim=c(0,1))
...

ContentLicense: CC BY-SA 2.5

Body:
I'm creating some maps from raster files using the "raster" package in R. I'd like to create comparison rasters, showing several maps side by side. It's important for this that the colour scales used are the same for all maps, regardless of the values in each map. For example, if map 1 has values from 0-1, and map 2 has values from 0-0.5, cells with a value of 0.5 should have the same colour on both maps.

For example:

map 1 has values from 0 to 1

map 2 has values from 0 to 0.5

the colour goes from red (lowest) to green (highest)

I would like a value of 0.5 to have the same colour in both maps (i.e. yellow, as halfway between red and green). The current behaviour is that it is yellow in map 1, and green in map 2.

I can't find a way to make this work. I can't see any way to set the range of pixel values to use with the plotting function. setMinMax() doesn't help (as 'plot' always calculates the values). Even trying to set the values by hand (e.g. g1@data@max <- 10) doesn't work (these are ignored when plotting).

Finally, making a stack of the maps (which might be expected to plot everything on the same colour scale) doesn't work either - each map still has it's own colour scale.

Any thoughts on how to do this?

EDIT:

The solution I ended up using is:

plot( d, col=rev( rainbow( 99, start=0,end=1 ) ), breaks=seq(min(minValue( d )),max(maxValue(d)),length.out=100) )


问:
How to merge result from multiple tables in efficient way Laravel
I have to merge results from multiple tables in Laravel. Currently I am using the following way:

```<code>public function getMachines(Request $request) {
        $vendor_id = Auth::id();
        $ml_8_machine=ML8Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_16_machine=ML16Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_32_machine=ML32Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_64_machine=ML64Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_96_machine=ML96Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_128_machine=ML128Machine::where('vendor_id','=',$vendor_id)->get();
        $machines = collect($ml_8_machine)
                        ->merge($ml_16_machine)
                        ->merge($ml_32_machine)
                        ->merge($ml_64_machine)
                        ->merge($ml_96_machine)
                        ->merge($ml_128_machine);
        return view('vendor.machines', compact('machines'));
    }
</code>```

I am looking for an efficient way to do the query and merge result in one collection.

答:
If your columns are the same,
you can use unionAll to merge the records. This will reduce the IO cost:

public function getMachines(Request $request) {
        $vendor_id = Auth::id();
        $ml_8_machine=ML8Machine::where('vendor_id','=',$vendor_id)->select('column1', 'column2'...);
        $ml_16_machine=ML16Machine::where('vendor_id','=',$vendor_id)->select('column1', 'column2'...);
        $ml_32_machine=ML32Machine::where('vendor_id','=',$vendor_id)->select('column1', 'column2'...);
        $ml_64_machine=ML64Machine::where('vendor_id','=',$vendor_id)->select('column1', 'column2'...);
        $ml_96_machine=ML96Machine::where('vendor_id','=',$vendor_id)->select('column1', 'column2'...);
        $ml_128_machine=ML128Machine::where('vendor_id','=',$vendor_id)->select('column1', 'column2'...);
        $machines = $ml_8_machine->unionAll($ml_16_machine)
                        ->unionAll($ml_32_machine)
                        ->unionAll($ml_64_machine)
                        ->unionAll($ml_96_machine)
                        ->unionAll($ml_128_machine)
                        ->get();
        return view('vendor.machines', compact('machines'));
    }
```

<p>Remember, you need to keep each columns as same order as others.</p>

<p>And you can add <code>paginate()</code> on this query too:</p>

<pre class="lang-php prettyprint-override"><code>$machines = $ml_8_machine->unionAll($ml_16_machine)
                        ->unionAll($ml_32_machine)
                        ->unionAll($ml_64_machine)
                        ->unionAll($ml_96_machine)
                        ->unionAll($ml_128_machine)
                        ->paginate(10);
</code>```

Body:
I have to merge results from multiple tables in Laravel. Currently I am using the following way:

public function getMachines(Request $request) {
        $vendor_id = Auth::id();
        $ml_8_machine=ML8Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_16_machine=ML16Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_32_machine=ML32Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_64_machine=ML64Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_96_machine=ML96Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_128_machine=ML128Machine::where('vendor_id','=',$vendor_id)->get();
        $machines = collect($ml_8_machine)
                        ->merge($ml_16_machine)
                        ->merge($ml_32_machine)
                        ->merge($ml_64_machine)
                        ->merge($ml_96_machine)
                        ->merge($ml_128_machine);
        return view('vendor.machines', compact('machines'));
    }

I am looking for an efficient way to do the query and merge result in one collection.

Body:
If your columns are the same,
you can use unionAll to merge the records. This will reduce the IO cost:

public function getMachines(Request $request) {
        $vendor_id = Auth::id();
        $ml_8_machine=ML8Machine::where('vendor_id','=',$vendor_id)->select('column1', 'column2'...);
        $ml_16_machine=ML16Machine::where('vendor_id','=',$vendor_id)->select('column1', 'column2'...);
        $ml_32_machine=ML32Machine::where('vendor_id','=',$vendor_id)->select('column1', 'column2'...);
        $ml_64_machine=ML64Machine::where('vendor_id','=',$vendor_id)->select('column1', 'column2'...);
        $ml_96_machine=ML96Machine::where('vendor_id','=',$vendor_id)->select('column1', 'column2'...);
        $ml_128_machine=ML128Machine::where('vendor_id','=',$vendor_id)->select('column1', 'column2'...);
        $machines = $ml_8_machine->unionAll($ml_16_machine)
                        ->unionAll($ml_32_machine)
                        ->unionAll($ml_64_machine)
                        ->unionAll($ml_96_machine)
                        ->unionAll($ml_128_machine)
                        ->get();
        return view('vendor.machines', compact('machines'));
    }

Remember, you need to keep each columns as same order as others.

And you can add paginate() on this query too:

$machines = $ml_8_machine->unionAll($ml_16_machine)
                        ->unionAll($ml_32_machine)
                        ->unionAll($ml_64_machine)
                        ->unionAll($ml_96_machine)
                        ->unionAll($ml_128_machine)
                        ->paginate(10);


问:
The length of trainPred is not correct in prediction function with R
This is my code for part of Naive Bayes a

```<code>trainPred<- predict(NBclassfier, newdata = train, type = "raw")
</code>```

but I am getting wrong number for length of trainPred which two times biger than the actual size of the trainPre.

Even when I am using

```<code>trainPred<- predict(NBclassfier, newdata = train, type = "class")
</code>```

I only get 0 for length of trainPred

so when I am running bellow code I get an error

```<code>trainTable <- table(train$prog, trainPred)
</code>```

The Code for NBclassifer is NBclassfier = naiveBayes(prog~., data= train)

the whole code an an error

```<code> library(caret)
library(e1071)

 set.seed(25)
trainIndex=createDataPartition(NaiveData$prog, p=0.8)$Resample1
train=NaiveData[trainIndex, ]
test=NaiveData[-trainIndex, ]
</code>```

check the balance

```<code>print(table(NaiveData$prog))

 0   1
496 261
</code>```

Check the train table

```<code>print(table(train$prog))

 0   1
388 218

NBclassfier = naiveBayes(prog~., data= train)
trainPred <- predict(NBclassfier, newdata = train, type = "raw")
trainPred<- trainPred
trainTable <- table(train$prog, trainPred)

Error in table(train$prog, trainPred) :   all arguments must have the same length
</code>```

答:
I just solved the problem and wanted to share the answer as well, </p>

```<code>NBclassfier = naiveBayes(as.factor(prog)~., data= train)
confusionMatrix(as.factor(trainPred), as.factor(train$prog), mode = "prec_recall")
</code>```

<p>Justmake them Factor. </p>

Body:
This is my code for part of Naive Bayes a

trainPred<- predict(NBclassfier, newdata = train, type = "raw")

but I am getting wrong number for length of trainPred which two times biger than the actual size of the trainPre.

Even when I am using

trainPred<- predict(NBclassfier, newdata = train, type = "class")

I only get 0 for length of trainPred

so when I am running bellow code I get an error

trainTable <- table(train$prog, trainPred)

The Code for NBclassifer is NBclassfier = naiveBayes(prog~., data= train)

the whole code an an error

 library(caret)
library(e1071)

 set.seed(25)
trainIndex=createDataPartition(NaiveData$prog, p=0.8)$Resample1
train=NaiveData[trainIndex, ]
test=NaiveData[-trainIndex, ]

check the balance

print(table(NaiveData$prog))

 0   1
496 261

Check the train table

print(table(train$prog))

 0   1
388 218

NBclassfier = naiveBayes(prog~., data= train)
trainPred <- predict(NBclassfier, newdata = train, type = "raw")
trainPred<- trainPred
trainTable <- table(train$prog, trainPred)

Error in table(train$prog, trainPred) :   all arguments must have the same length

Body:
I just solved the problem and wanted to share the answer as well,

NBclassfier = naiveBayes(as.factor(prog)~., data= train)
confusionMatrix(as.factor(trainPred), as.factor(train$prog), mode = "prec_recall")

Justmake them Factor.


问:
I am getting error for isDisplayed method?
if (driver.findElement(By.id(id)).isDisplayed()) {

}

Always execution is failed when element is not available?

Environment:

Appium 1.15.1

java Client 7.3.0

selenium-java 3.141.59

error logs:

Android Loding Problem Pages

org.openqa.selenium.NoSuchElementException: Can't locate an element by this strategy: By.chained({By.AccessibilityId: OK})
    at io.appium.java_client.pagefactory.AppiumElementLocator.findElement(AppiumElementLocator.java:126)
    at io.appium.java_client.pagefactory.interceptors.InterceptorOfASingleElement.intercept(InterceptorOfASingleElement.java:59)
    at io.appium.java_client.ios.IOSElement$$EnhancerByCGLIB$$d311658.isDisplayed()
    at
    at ✽.And Verify the On Side Menu List are Navigating to correspont Screen with OnBoared User(:12)
Caused by: org.openqa.selenium.TimeoutException: Expected condition failed: waiting for io.appium.java_client.pagefactory.AppiumElementLocator$WaitingFunction@66ba7e45 (tried for 1 second(s) with 500 milliseconds interval)
    at org.openqa.selenium.support.ui.FluentWait.timeoutException(FluentWait.java:304)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:272)
    at io.appium.java_client.pagefactory.AppiumElementLocator.waitFor(AppiumElementLocator.java:99)
    at io.appium.java_client.pagefactory.AppiumElementLocator.findElement(AppiumElementLocator.java:119)
    at io.appium.java_client.pagefactory.interceptors.InterceptorOfASingleElement.intercept(InterceptorOfASingleElement.java:59)
    at io.appium.java_client.ios.IOSElement$$EnhancerByCGLIB$$d311658.isDisplayed()
    at
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at cucumber.runtime.Utils$1.call(Utils.java:40)
    at cucumber.runtime.Timeout.timeout(Timeout.java:16)
    at cucumber.runtime.Utils.invoke(Utils.java:34)
    at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
    at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
    at cucumber.runtime.Runtime.runStep(Runtime.java:300)
    at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
    at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
    at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
    at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:102)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:95)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:38)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.api.junit.Cucumber.run(Cucumber.java:100)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:39)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.Iterator.forEachRemaining(Iterator.java:116)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:79)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:70)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: org.openqa.selenium.NoSuchElementException: Cannot locate an element using By.chained({By.AccessibilityId: OK})
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'Elites-MacBook-Pro-4.local', ip: 'fe80:0:0:0:1c56:6e8a:fceb:a653%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.15.3', java.version: '1.8.0_201'
Driver info: driver.version: IOSDriver
    at io.appium.java_client.pagefactory.bys.builder.ByChained.findElement(ByChained.java:74)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:57)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.ios.IOSDriver.findElement(IOSDriver.java:1)
    at io.appium.java_client.pagefactory.bys.ContentMappedBy.findElement(ContentMappedBy.java:50)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:57)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.ios.IOSDriver.findElement(IOSDriver.java:1)
    at io.appium.java_client.pagefactory.AppiumElementLocator.lambda$0(AppiumElementLocator.java:120)
    at io.appium.java_client.pagefactory.AppiumElementLocator$WaitingFunction.apply(AppiumElementLocator.java:172)
    at io.appium.java_client.pagefactory.AppiumElementLocator$WaitingFunction.apply(AppiumElementLocator.java:1)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:249)
    ... 67 more

答:
You can create a custom isDisplayed method here with some explicit wait. Something like this

```<code>protected boolean isDisplayed(WebElement id, long timeOutInSeconds) {
        try {
            WebDriverWait wait = new WebDriverWait(DriverManager.getDriver(), timeOutInSeconds);
            wait.until(ExpectedConditions.visibilityOf(id));
        } catch (TimeoutException | NoSuchElementException ex) {
            return false;
        }
        return true;
    }
</code>```

And then apply to your element like this:

```<code>if (!isDisplayed(ELEMENTNAME, 10)) {
            Assert.fail("");
        } else {
            Log.info("");
        }
    }
</code>```

Body:
You can create a custom isDisplayed method here with some explicit wait. Something like this

protected boolean isDisplayed(WebElement id, long timeOutInSeconds) {
        try {
            WebDriverWait wait = new WebDriverWait(DriverManager.getDriver(), timeOutInSeconds);
            wait.until(ExpectedConditions.visibilityOf(id));
        } catch (TimeoutException | NoSuchElementException ex) {
            return false;
        }
        return true;
    }

And then apply to your element like this:

if (!isDisplayed(ELEMENTNAME, 10)) {
            Assert.fail("");
        } else {
            Log.info("");
        }
    }


问:
Class Validator @ValidateIf() not working properly
I have the following class in nest js with this class validator:

```<code> @ValidateIf(val => val !== '*')
 @IsObject()
 @IsNotEmptyObject()
 queryParams: DbQuery | '*';
</code>```

If I send '*' it returns

```<code> [ 'queryParams must be a non-empty object' ]
</code>```

答:
For who ever finds himself here.</p>

```<code>@ValidateIf(val => val.queryParams !== '*')
@IsNotEmptyObject()
queryParams: DbQuery | '*';
</code>```

Body:
I have the following class in nest js with this class validator:

 @ValidateIf(val => val !== '*')
 @IsObject()
 @IsNotEmptyObject()
 queryParams: DbQuery | '*';

If I send '*' it returns

 [ 'queryParams must be a non-empty object' ]

Body:
For who ever finds himself here.

@ValidateIf(val => val.queryParams !== '*')
@IsNotEmptyObject()
queryParams: DbQuery | '*';


问:
typescript: enforcing existing object keys
I would like dropdownAttributes to limited to attributes on DropDownItem interface.

```<code>interface DropDownItem {
    [key: string]: any;
}
</code>```

```<code>interface Props {
   dropdownList: DropDownItem[];
   dropdownAttributes: string[];
}
</code>```

if DropDownItem did now have dynamic properties I think I could solve this with keyof like this:

```<code>interface Props {
   dropdownList: DropDownItem[];
   dropdownAttributes: (keyof DropDownItem)[];
}
</code>```

But that does not work now in my case. How to solve?

答:
In the end I did this.

```<code>interface Props<T> {
   dropdownList: T[];
   dropdownAttributes: (keyof T)[];
}

declare class MyComponent<T> extends React.Component<Props<T>> {}

export default MyComponent;

</code>```

Usage:

```<code>interface DropdownItem {
   key1: string;
   key2: string;
}

<MyComponent
   <DropdownItem>
   dropdownAttributes={['key1', 'key2']}
   dropdownList={[{key1: 'hello', key2: 'world'}]}
/>

</code>```

Body:
I would like dropdownAttributes to limited to attributes on DropDownItem interface.

interface DropDownItem {
    [key: string]: any;
}

interface Props {
   dropdownList: DropDownItem[];
   dropdownAttributes: string[];
}

if DropDownItem did now have dynamic properties I think I could solve this with keyof like this:

interface Props {
   dropdownList: DropDownItem[];
   dropdownAttributes: (keyof DropDownItem)[];
}

But that does not work now in my case. How to solve?

Body:
In the end I did this.

interface Props<T> {
   dropdownList: T[];
   dropdownAttributes: (keyof T)[];
}

declare class MyComponent<T> extends React.Component<Props<T>> {}

export default MyComponent;

Usage:

interface DropdownItem {
   key1: string;
   key2: string;
}

<MyComponent
   <DropdownItem>
   dropdownAttributes={['key1', 'key2']}
   dropdownList={[{key1: 'hello', key2: 'world'}]}
/>


问:
Firebase/Telegram Post request
I'm currently trying to build a firebase cloud function (using express) where:
- I check if a use exists in database
- Sends a message to the telegram API depending on whether it exists or not

The issue is, when I try to run the function, Firebase logs is able to get the console.log telling me if the user exists, but will not send to telegram. The error log says:

[2020-02-15T10:41:34.568Z]  @firebase/database: FIREBASE WARNING:
  Exception was thrown by user callback. Error: Can't set headers after
  they are sent.
      at validateHeader (_http_outgoing.js:491:11)
      at ServerResponse.setHeader (_http_outgoing.js:498:3)
      at ServerResponse.header (/srv/node_modules/express/lib/response.js:771:10)
      at ServerResponse.send (/srv/node_modules/express/lib/response.js:170:12)
      at ServerResponse.json (/srv/node_modules/express/lib/response.js:267:15)
      at ServerResponse.send (/srv/node_modules/express/lib/response.js:158:21)
      at firebase.database.ref.child.once.snapshot (/srv/index.js:59:40)
      at onceCallback (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:4933:51)
      at /srv/node_modules/@firebase/database/dist/index.node.cjs.js:4549:22
      at exceptionGuard (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:698:9)

Could anyone please help? Thank you!

```<code> app.post("/", async (req, res) => {

    const isTelegramMessage =
        req.body &&
        req.body.message &&
        req.body.message.chat &&
        req.body.message.chat.id &&
        req.body.message.from &&
        req.body.message.from.first_name &&
        req.body.update_id;
    const user_id = req.body.message.from.id
 firebase.initializeApp(firebaseConfig);
    let myUser;
    const chat_id = req.body.message.chat.id;
    const {
        first_name
    } = req.body.message.from;
    // Check User Exists
    firebase
        .database()
        .ref("/telegramUsers")
        .child(req.body.message.from.id)
        .once("value", snapshot => {
            if (snapshot.exists()) {
                myUser = true;
                console.log("exists!", myUser);
                return res.status(200).send({
                    method: "sendMessage",
                    chat_id,
                    text: `Welcome Back ${first_name}`
                });
            } else {
                myUser = false;
                console.log("does not exist!");
                return res.status(200).send({
                    method: "sendMessage",
                    chat_id,
                    text: `Hello ${first_name}`
                });
            }
        });

    return res.status(200).send({
        status: "not a telegram message"
    });
});
</code>```

答:
As others have commented, you're returning and writing a response to the caller twice. Since send starts writing the body of the HTTP response, you can't call status (or even send) after you've already called it on res before.

In code that'd look something like this:

```<code> app.post("/", async (req, res) => {

    const isTelegramMessage =
        req.body &&
        req.body.message &&
        req.body.message.chat &&
        req.body.message.chat.id &&
        req.body.message.from &&
        req.body.message.from.first_name &&
        req.body.update_id;
    const user_id = req.body.message.from.id
    firebase.initializeApp(firebaseConfig);
    let myUser;
    const chat_id = req.body.message.chat.id;
    const {
        first_name
    } = req.body.message.from;
    // Check User Exists
    if (isTelegramMessage) {
      return firebase
        .database()
        .ref("/telegramUsers")
        .child(req.body.message.from.id)
        .once("value")
        .then(snapshot => {
            if (snapshot.exists()) {
                myUser = true;
                console.log("exists!", myUser);
                return res.status(200).send({
                    method: "sendMessage",
                    chat_id,
                    text: `Welcome Back ${first_name}`
                });
            } else {
                myUser = false;
                console.log("does not exist!");
                return res.status(200).send({
                    method: "sendMessage",
                    chat_id,
                    text: `Hello ${first_name}`
                });
            }
          });
    } else {
      return res.status(200).send({
        status: "not a telegram message"
      });
   }
});
</code>```

The changes:

Now only checks if the user exists if isTelegramMessage is true.

Now returns the result from the database read operation.

Use once().then(), so that the return res.status().send()... bubbles up. This ensures that Cloud Functions will not terminate the function before both the database load and the sending of the response are done.

Though the second and third bullets are not strictly needed for HTTPS triggered Cloud Functions (as those terminate when you send a response), I still recommend to use them, to make it easier to port/copy-paste the code to Cloud Functions types that are triggered by other events.

Title: Firebase/Telegram Post request

Body:
I'm currently trying to build a firebase cloud function (using express) where:
- I check if a use exists in database
- Sends a message to the telegram API depending on whether it exists or not

The issue is, when I try to run the function, Firebase logs is able to get the console.log telling me if the user exists, but will not send to telegram. The error log says:

[2020-02-15T10:41:34.568Z]  @firebase/database: FIREBASE WARNING:
  Exception was thrown by user callback. Error: Can't set headers after
  they are sent.
      at validateHeader (_http_outgoing.js:491:11)
      at ServerResponse.setHeader (_http_outgoing.js:498:3)
      at ServerResponse.header (/srv/node_modules/express/lib/response.js:771:10)
      at ServerResponse.send (/srv/node_modules/express/lib/response.js:170:12)
      at ServerResponse.json (/srv/node_modules/express/lib/response.js:267:15)
      at ServerResponse.send (/srv/node_modules/express/lib/response.js:158:21)
      at firebase.database.ref.child.once.snapshot (/srv/index.js:59:40)
      at onceCallback (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:4933:51)
      at /srv/node_modules/@firebase/database/dist/index.node.cjs.js:4549:22
      at exceptionGuard (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:698:9)

Could anyone please help? Thank you!

 app.post("/", async (req, res) => {

    const isTelegramMessage =
        req.body &&
        req.body.message &&
        req.body.message.chat &&
        req.body.message.chat.id &&
        req.body.message.from &&
        req.body.message.from.first_name &&
        req.body.update_id;
    const user_id = req.body.message.from.id
 firebase.initializeApp(firebaseConfig);
    let myUser;
    const chat_id = req.body.message.chat.id;
    const {
        first_name
    } = req.body.message.from;
    // Check User Exists
    firebase
        .database()
        .ref("/telegramUsers")
        .child(req.body.message.from.id)
        .once("value", snapshot => {
            if (snapshot.exists()) {
                myUser = true;
                console.log("exists!", myUser);
                return res.status(200).send({
                    method: "sendMessage",
                    chat_id,
                    text: `Welcome Back ${first_name}`
                });
            } else {
                myUser = false;
                console.log("does not exist!");
                return res.status(200).send({
                    method: "sendMessage",
                    chat_id,
                    text: `Hello ${first_name}`
                });
            }
        });

    return res.status(200).send({
        status: "not a telegram message"
    });
});

Body:
As others have commented, you're returning and writing a response to the caller twice. Since send starts writing the body of the HTTP response, you can't call status (or even send) after you've already called it on res before.

In code that'd look something like this:

 app.post("/", async (req, res) => {

    const isTelegramMessage =
        req.body &&
        req.body.message &&
        req.body.message.chat &&
        req.body.message.chat.id &&
        req.body.message.from &&
        req.body.message.from.first_name &&
        req.body.update_id;
    const user_id = req.body.message.from.id
    firebase.initializeApp(firebaseConfig);
    let myUser;
    const chat_id = req.body.message.chat.id;
    const {
        first_name
    } = req.body.message.from;
    // Check User Exists
    if (isTelegramMessage) {
      return firebase
        .database()
        .ref("/telegramUsers")
        .child(req.body.message.from.id)
        .once("value")
        .then(snapshot => {
            if (snapshot.exists()) {
                myUser = true;
                console.log("exists!", myUser);
                return res.status(200).send({
                    method: "sendMessage",
                    chat_id,
                    text: `Welcome Back ${first_name}`
                });
            } else {
                myUser = false;
                console.log("does not exist!");
                return res.status(200).send({
                    method: "sendMessage",
                    chat_id,
                    text: `Hello ${first_name}`
                });
            }
          });
    } else {
      return res.status(200).send({
        status: "not a telegram message"
      });
   }
});

The changes:

Now only checks if the user exists if isTelegramMessage is true.

Now returns the result from the database read operation.

Use once().then(), so that the return res.status().send()... bubbles up. This ensures that Cloud Functions will not terminate the function before both the database load and the sending of the response are done.

Though the second and third bullets are not strictly needed for HTTPS triggered Cloud Functions (as those terminate when you send a response), I still recommend to use them, to make it easier to port/copy-paste the code to Cloud Functions types that are triggered by other events.


问:
Angular <mat-select> component is not working on a FormGroup
I'm trying to use  inside a formGroup but although it builds the component and I can navigate through options, I couldn't select any of them. When the page is loaded I can see this error :

ERROR TypeError: "this._selectionModel.onChange is undefined"

Here's my component.ts :

```<code>@Component({
  selector: 'app-agent',
  templateUrl: './agent.component.html',
  styleUrls: ['./agent.component.css']
})
export class AgentComponent implements OnInit {

  agents = [];
  durationInSeconds = 5;
  statusList = ['AVAILABLE', 'NOT_AVAILABLE'];
  agentForm = new FormGroup ({
    name: new FormControl(),
    status: new FormControl(this.statusList[0]),
  });
  searchForm = new FormGroup(
    {key: new FormControl()}
  );

  constructor(private agentService: AgentService) { }

  ngOnInit(): void {
    this.getAll();
  }

  filter(): void {
    if (this.searchForm.value.key) {
      this.getOne();
    } else {
      this.getAll();
    }
  }

  save(): void {
    this.agentService.save(new AgentData(this.agentForm.value.name, this.agentForm.value.status)).subscribe((data) => {
      this.agentForm.value.name = data.name;
      this.agentForm.value.status = data.status;
    }
    );
  }
}
</code>```

And this is the component html part :

```<code>        <form [formGroup]="agentForm" (submit)="save()">
          <table class="form-group" style="width: 100%; ">
            <div class="row" >
              <mat-form-field style="width: 100%; ">
                <mat-label>Agent name</mat-label>
                <input matInput placeholder="Ex. fferchichi" formControlName="name">
              </mat-form-field>
            </div>

            <div class="row">
              <mat-form-field style="width: 100%;">
                <mat-label>Status</mat-label>
                <mat-select formControlName="status">
                  <mat-option *ngFor="let status of statusList" [value]="status">
                    {{status | labelit}}
                  </mat-option>
                </mat-select>
                <mat-error *ngIf="agentForm.hasError('required')">Please choose a Status</mat-error>
              </mat-form-field>
            </div>

            <div class="row" style="text-align: right;">
              <input type="submit" class="btn btn-default" value="Save"/>
            </div>

          </table>
        </form>
</code>```

It feels like the binding with formControl is read-only but I can't find out why or how to fix it.

答:
According to Angular.io documentation for FormControl the 'value' property is readonly.

you should use the formcontrol.setValue() method to change the value of a formcontrol

Body:
I'm trying to use  inside a formGroup but although it builds the component and I can navigate through options, I couldn't select any of them. When the page is loaded I can see this error :

ERROR TypeError: "this._selectionModel.onChange is undefined"

Here's my component.ts :

@Component({
  selector: 'app-agent',
  templateUrl: './agent.component.html',
  styleUrls: ['./agent.component.css']
})
export class AgentComponent implements OnInit {

  agents = [];
  durationInSeconds = 5;
  statusList = ['AVAILABLE', 'NOT_AVAILABLE'];
  agentForm = new FormGroup ({
    name: new FormControl(),
    status: new FormControl(this.statusList[0]),
  });
  searchForm = new FormGroup(
    {key: new FormControl()}
  );

  constructor(private agentService: AgentService) { }

  ngOnInit(): void {
    this.getAll();
  }

  filter(): void {
    if (this.searchForm.value.key) {
      this.getOne();
    } else {
      this.getAll();
    }
  }

  save(): void {
    this.agentService.save(new AgentData(this.agentForm.value.name, this.agentForm.value.status)).subscribe((data) => {
      this.agentForm.value.name = data.name;
      this.agentForm.value.status = data.status;
    }
    );
  }
}

And this is the component html part :

        <form [formGroup]="agentForm" (submit)="save()">

              <mat-form-field style="width: 100%; ">
                <mat-label>Agent name</mat-label>
                <input matInput placeholder="Ex. fferchichi" formControlName="name">
              </mat-form-field>

              <mat-form-field style="width: 100%;">
                <mat-label>Status</mat-label>
                <mat-select formControlName="status">
                  <mat-option *ngFor="let status of statusList" [value]="status">
                    {{status | labelit}}
                  </mat-option>
                </mat-select>
                <mat-error *ngIf="agentForm.hasError('required')">Please choose a Status</mat-error>
              </mat-form-field>

              <input type="submit" class="btn btn-default" value="Save"/>

        </form>

It feels like the binding with formControl is read-only but I can't find out why or how to fix it.


问:
Version control for binaries with timestamps
I need a version control system that works like Subversion but is able to keep the 'modified' timestamp (date) of each file.

We need to version our setup projects. In this case it is imporatant that the input files (dll/exe's) keep their timestamp.

What is the best tool to do this? (OS: Windows)

Updated:

Here's an example of what I would like it to do:

put "foo.dll" (modified 1/1/2009) and "bar.dll" (modified 2/2/2009) into the working directory

create/test the setup and do a single commit

when another developer checks out the project both foo.dll and bar.dll should have their orginal modified date (1/1/2009 and 2/2/2009)

Our current workaround is to zip each dll (the modified date is kept in the zip) but I would prefer something easier.

答: In git, a "commit" points to a single tree, marking it as what the project looked like at a certain point in time. It contains meta-information about that point in time, such as a timestamp, the author of the changes since the last commit, a pointer to the previous commit(s), etc.

OwnerDisplayName: Nerdling


问:
Split Java project by build.xml dependencies
I am working with a Java project that really should have been coded as 2 separate projects.  Thus, I'm trying to find a good way to split out the code of each sub-project into its own new project.  There are 2 build files that build and package each sub-project.  Thus, is there a good way that I can retrieve a list of all the resources and files needed for each build file, and thus separate out my projects?

EDIT:

I have found Manifest*.MF files associated with each build file, which specify both the Main-Class and the Class-Path.  From the Class-Path, I can determine which JAR files are needed for each new project.  These are both applications that only run off their respective main classes, so if I determine the dependent classes of the main class, I determine the classes I need in the new project.

Here is my current plan for this:

Copy the old project into a new project

Remove the unused build files, MANIFEST*.MF files, and unused JARs based on the manifest

Remove the unused Main files based on the manifest

Use IntelliJ's built-in functionality to manually go through files and methods to check if they are referenced anywhere and remove them 1-by-1 if they are not.

I'm guessing step 4 can be improved on...

UPDATE:

I've now completed separating out my projects.  I ended up using IntelliJ's "Analyze Dependencies..." (in 10.0.3 it is under the "Analyze" menu).  For those of you that have that tool, it only searches dependencies 1 deep by default, so be aware of this and set a greater depth as needed.  You can then highlight the core classes and it will show you all the files that those classes depend on to your specified depth.  In my case, one of the main files of one sub-project referenced the main file of another sub-project, so by removing that one dependency I was able to eliminate 65+ files as dependencies.

The above solution worked well for me, but I don't like saying "you have to buy this tool to do what you want..."   Thus, I'm keeping this question open in the hopes of an open-source solution.

答:
Dependencies:

You could create 2 projects, both referring all of the original jars (dependencies) of the original project. At this point you are referring to some unnecessary jars in both projects. Then you can use tools suggested here to detect these unnecessary jars and remove these in each project.

Resources (like xml config files):

Maybe there are some tools out there, but I don't know. Hopefully you don't have that many config files etc., and if so manual copy is probably the fastest way.


问:
How to hide elements in jQuery until after the user starts scrolling
I need to hide two divs #top and #header-space until the user begins scrolling the page. I have already tried to do so but this code still displays the two divs after the page has loaded. I am doing this within WordPress using jQuery and only want to do it for the homepage. Can't get past this point.

Here's the code I have tried:

```<code>jQuery(document).ready(function($){
    $(window).on('scroll', function(){
        var y = $(window).scrollTop(0);
        var width = $(window).innerWidth();

        if(window.location.pathname == '/'){
            if ( window.innerWidth > 1000) {
                if( y > 0 ){
                    $('#top').fadeIn();
                    $('#header-space').fadeIn();
                } else {
                    $('#top').fadeOut();
                    $('#header-space').fadeOut();
                }
            }
        } else {
        }
    });
});
</code>```

答:
try this code out:

```<code>var position = $(window).scrollTop();
// should start at 0

$(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if(scroll > position) {
        // Code to for Scrolling Down
    } else {
         // Code to for Scrolling Up
    }
    position = scroll;
});
</code>```

You can delete the 'IF' statement and make the code run on any case. or only place your code on the first condition which is triggered when the user scrolls down.

Body:
I need to hide two divs #top and #header-space until the user begins scrolling the page. I have already tried to do so but this code still displays the two divs after the page has loaded. I am doing this within WordPress using jQuery and only want to do it for the homepage. Can't get past this point.

Here's the code I have tried:

jQuery(document).ready(function($){
    $(window).on('scroll', function(){
        var y = $(window).scrollTop(0);
        var width = $(window).innerWidth();

        if(window.location.pathname == '/'){
            if ( window.innerWidth > 1000) {
                if( y > 0 ){
                    $('#top').fadeIn();
                    $('#header-space').fadeIn();
                } else {
                    $('#top').fadeOut();
                    $('#header-space').fadeOut();
                }
            }
        } else {
        }
    });
});

Body:
try this code out:

var position = $(window).scrollTop();
// should start at 0

$(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if(scroll > position) {
        // Code to for Scrolling Down
    } else {
         // Code to for Scrolling Up
    }
    position = scroll;
});

You can delete the 'IF' statement and make the code run on any case. or only place your code on the first condition which is triggered when the user scrolls down.


问:
Electron App Installation to ProgramFiles
What's the best way to make an electron app installer so that it installs it in ProgramFiles? I am using the electron-builder, but it installs the app in %appdata%</p>

答: The installer will indeed install in %appdata% if you have set build/nsis/perMachine to false (which is default) in your package.json. If you set perMachine to true, the program will be installed in program files, and furthermore if you set oneClick to false, you allow the user to choose where to install.</p>


问:
react axios then works but catch doesn't work
I've read the following questions but I couldn't find the solution.

https://github.com/axios/axios/issues/960

https://github.com/axios/axios/issues/41

axios catch doesn't catch error

I wanna to get errors 400, 500, ... someone has said you should catch in then but I tried it and nothing happened. for test I wrote a function to get error 404, 400, ...

```<code>export const myAxios = url => {
  Axios.get(url)
    .then(response => {
      // Success
      console.log("then response ", response);
    })
    .catch(error => {
      // Error
      if (error.response) {
        console.log("error respone", error.response);
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        // console.log(error.response.data);
        // console.log(error.response.status);
        // console.log(error.response.headers);
      } else if (error.request) {
        // The request was made but no response was received
        // `error.request` is an instance of XMLHttpRequest in the
        // browser and an instance of
        // http.ClientRequest in node.js
        console.log("erros request: ", error.request);
      } else {
        // Something happened in setting up the request that triggered an Error
        console.log("Error message", error.message);
      }
      console.log("errors config : ", error.config);
    });
};
</code>```

axios doesn't catch errors and browser console logs this:

```<code>xhr.js:172 GET http://localhost:3000/app/..../choices 404 (Not Found)
dispatchXhrRequest @ xhr.js:172
xhrAdapter @ xhr.js:11
dispatchRequest @ dispatchRequest.js:59
Promise.then (async)
request @ Axios.js:53
Axios.<computed> @ Axios.js:68
wrap @ bind.js:9
myAxios @ textaxios.js:4
(anonymous) @ List.jsx:14
commitHookEffectList @ react-dom.development.js:22030
</code>```

Any tips or help will be appreciated.

packages:

```<code>   "axios": "^0.19.0"
   "react": "^16.12.0"
</code>```

答:
Your code seems fine, perhaps it's the local endpoint (resource) that you're trying to get to?

Here's an example using an example placeholder service:

document.getElementById('btn-valid').addEventListener('click', () => {
  // Valid URL
  myAxios('https://jsonplaceholder.typicode.com/todos/1')
})

document.getElementById('btn-invalid').addEventListener('click', () => {
  // Invalid URL
  myAxios('https://jsonplaceholder.typicode.com/todus/1')
})

const myAxios = url => {
  axios.get(url)
    .then(response => {
      console.log('success', response);
    })
    .catch(error => {
      console.log('error', error)
    })
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<button id="btn-invalid">Invalid URL</button>
<button id="btn-valid">Valid URL</button></code>```

Additionally, you can try using Axios interceptors to 'intercept' requests or responses before they're handled by then or catch:

```<code>axios.interceptors.response.use(response => {
        // Any status code that lie within the range of 2xx cause this function to trigger
        // Do something with response data
        console.log('inside interceptor success')
        return response;
      }, error => {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error
        console.log('inside interceptor error')
        return Promise.reject(error);
      });
</code>```

Body:
I've read the following questions but I couldn't find the solution.

https://github.com/axios/axios/issues/960

https://github.com/axios/axios/issues/41

axios catch doesn't catch error

I wanna to get errors 400, 500, ... someone has said you should catch in then but I tried it and nothing happened. for test I wrote a function to get error 404, 400, ...

export const myAxios = url => {
  Axios.get(url)
    .then(response => {
      // Success
      console.log("then response ", response);
    })
    .catch(error => {
      // Error
      if (error.response) {
        console.log("error respone", error.response);
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        // console.log(error.response.data);
        // console.log(error.response.status);
        // console.log(error.response.headers);
      } else if (error.request) {
        // The request was made but no response was received
        // `error.request` is an instance of XMLHttpRequest in the
        // browser and an instance of
        // http.ClientRequest in node.js
        console.log("erros request: ", error.request);
      } else {
        // Something happened in setting up the request that triggered an Error
        console.log("Error message", error.message);
      }
      console.log("errors config : ", error.config);
    });
};

axios doesn't catch errors and browser console logs this:

xhr.js:172 GET http://localhost:3000/app/..../choices 404 (Not Found)
dispatchXhrRequest @ xhr.js:172
xhrAdapter @ xhr.js:11
dispatchRequest @ dispatchRequest.js:59
Promise.then (async)
request @ Axios.js:53
Axios.<computed> @ Axios.js:68
wrap @ bind.js:9
myAxios @ textaxios.js:4
(anonymous) @ List.jsx:14
commitHookEffectList @ react-dom.development.js:22030

Any tips or help will be appreciated.

packages:

   "axios": "^0.19.0"
   "react": "^16.12.0"

Body:
Your code seems fine, perhaps it's the local endpoint (resource) that you're trying to get to?

Here's an example using an example placeholder service:

document.getElementById('btn-valid').addEventListener('click', () => {
  // Valid URL
  myAxios('https://jsonplaceholder.typicode.com/todos/1')
})

document.getElementById('btn-invalid').addEventListener('click', () => {
  // Invalid URL
  myAxios('https://jsonplaceholder.typicode.com/todus/1')
})

const myAxios = url => {
  axios.get(url)
    .then(response => {
      console.log('success', response);
    })
    .catch(error => {
      console.log('error', error)
    })
}

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<button id="btn-invalid">Invalid URL</button>
<button id="btn-valid">Valid URL</button>

Additionally, you can try using Axios interceptors to 'intercept' requests or responses before they're handled by then or catch:

axios.interceptors.response.use(response => {
        // Any status code that lie within the range of 2xx cause this function to trigger
        // Do something with response data
        console.log('inside interceptor success')
        return response;
      }, error => {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error
        console.log('inside interceptor error')
        return Promise.reject(error);
      });


问:
PHP app cannot connect to docker mysql container at 127.0.0.1
Mysql is in it's own docker-compose.yml as I want a mysql server up and running that any other php application can connect to. So I do not have php and mysql in the same docker-compose.yml. From the php application, I can connect to mysql if I use the mysql container's gateway ip address by looking it up and then hard coding it into the php application. docker inspect mysql-db. But docker will change that 172... ip address each time mysql restarts so that is not ideal for development.

I can connect to mysql via mysql -h 127.0.0.1 no problem, but from the php application if I try to use 127.0.0.1 I get connection refused. I can only connect if I use the 172... gateway ip address.

How do I get the mysql container listening for connections from the host to 127.0.0.1?

docker-compose.yml for mysql

```<code>version: "3"

services:
  mysql:
    container_name: mysql-db
    image: mysql
    build:
      dockerfile: Dockerfile
      context: ./server/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=admin
    volumes:
      - ./data/mysql:/var/lib/mysql
    ports:
      - 3306:3306
</code>```

docker-compose.yml for php

```<code>version: "3"

services:
  nginx:
    container_name: nginx_myapp
    image: nginx
    build:
      dockerfile: Dockerfile
      context: ./server/nginx
    ports:
      - 80:80
      - 443:443
    volumes:
      - ./app:/var/www/html
    networks:
      - myapp
  php:
    container_name: php_myapp
    image: php:7.3-fpm
    build:
      dockerfile: Dockerfile
      context: ./server/php-fpm
    environment:
      CI_ENV: development
    volumes:
      - ./app:/var/www/html
    networks:
      - myapp

networks:
  myapp:
</code>```

答:
127.0.0.1 is the loopback address. It points to localhost. In the context of docker, localhost is the container itself. There is no db running on your php container so the connection will never succeed.

What you need to do is to configure the default network in you mysql compose file so that you will predictably control its name for later convenience (else it will be calculated from your compose project name which could change if you rename the containing folder...):

Important note: for the below to work, you need to use compose file version >= 3.5

```<code>---
version: '3.7'
#...
networks:
  default:
    name: shared_mysql
</code>```

You can now use that shared_mysql network as external from any other compose project.

```<code>version: '3.7'

services:
  nginx:
    #...
    networks:
      - myapp
  php:
    #...
    networks:
      - myapp
      - database

networks:
  myapp:
  database:
    external: true
    name: shared_mysql
</code>```

You can then connect to mysql from your php container using the service name mysql (e.g. mysql -h mysql -u user -p)

Reference: https://docs.docker.com/compose/networking/

Body:
Mysql is in it's own docker-compose.yml as I want a mysql server up and running that any other php application can connect to. So I do not have php and mysql in the same docker-compose.yml. From the php application, I can connect to mysql if I use the mysql container's gateway ip address by looking it up and then hard coding it into the php application. docker inspect mysql-db. But docker will change that 172... ip address each time mysql restarts so that is not ideal for development.

I can connect to mysql via mysql -h 127.0.0.1 no problem, but from the php application if I try to use 127.0.0.1 I get connection refused. I can only connect if I use the 172... gateway ip address.

How do I get the mysql container listening for connections from the host to 127.0.0.1?

docker-compose.yml for mysql

version: "3"

services:
  mysql:
    container_name: mysql-db
    image: mysql
    build:
      dockerfile: Dockerfile
      context: ./server/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=admin
    volumes:
      - ./data/mysql:/var/lib/mysql
    ports:
      - 3306:3306

docker-compose.yml for php

version: "3"

services:
  nginx:
    container_name: nginx_myapp
    image: nginx
    build:
      dockerfile: Dockerfile
      context: ./server/nginx
    ports:
      - 80:80
      - 443:443
    volumes:
      - ./app:/var/www/html
    networks:
      - myapp
  php:
    container_name: php_myapp
    image: php:7.3-fpm
    build:
      dockerfile: Dockerfile
      context: ./server/php-fpm
    environment:
      CI_ENV: development
    volumes:
      - ./app:/var/www/html
    networks:
      - myapp

networks:
  myapp:

Body:
127.0.0.1 is the loopback address. It points to localhost. In the context of docker, localhost is the container itself. There is no db running on your php container so the connection will never succeed.

What you need to do is to configure the default network in you mysql compose file so that you will predictably control its name for later convenience (else it will be calculated from your compose project name which could change if you rename the containing folder...):

Important note: for the below to work, you need to use compose file version >= 3.5

---
version: '3.7'
#...
networks:
  default:
    name: shared_mysql

You can now use that shared_mysql network as external from any other compose project.

version: '3.7'

services:
  nginx:
    #...
    networks:
      - myapp
  php:
    #...
    networks:
      - myapp
      - database

networks:
  myapp:
  database:
    external: true
    name: shared_mysql

You can then connect to mysql from your php container using the service name mysql (e.g. mysql -h mysql -u user -p)

Reference: https://docs.docker.com/compose/networking/