问:
C++ class loop in main
I need help in a simple way of solving a part of my code that i cant seem to make it work.The point of my "assignment" is that everything must try to be in one class.Now the problem i am having is at a part of my code where it is suppose to "print" the n number of products meaning that it displays what you  have  inputted in the void get() part,but the problem i cant seem to resolve is it only prints the last name,amount,weight of the product and not everything written.

```<code>   class Class
{
public:
    string name;
    int n, amount;
    float weight;
    void market()
    {
        cout << "Give the number of products you want to get at Market : " << endl;
        cin >> n;
    }
    void get()
    {
        for (int i = 0; i < n; i++)
        {
            cout << "Give product name,amount and weight : " << endl;
            cin >> name >> amount >> weight;
        }
    }
    void print()
    {
        cout << "\nProduct display:\n" << endl;
        for (int i = 0; i < n; i++)
        {
            cout << name << " - " << amount << " , " << weight << " kg" << endl;
            cout << "------------------------" << endl;
        }
    };
};
</code>```

The main part.

```<code>int main()
    {
            Class market;
            market.market();
            market.get();
            market.print();

    }
</code>```

答:
You must use a std::vector<TYPE> (example 1), or array for holding multiple data in a single variable (example 2).

Example 1

Since you've been coding in C++ programming language, it's highly recommended to use std::vector<> for best results.

Consider the class example (read comments too):

```<code>int count = 0; // PRIVATE SECTION
char ask;
std::vector<std::string> name;
std::vector<int> amount;
std::vector<float> weight;
std::string tName; // temp variables
int tAmount;
float tWeight;

public:

void market()
{
    cout << "WELCOME!" << endl; // nothing's required with vector
}
void get()
{
    do {
        cout << "Give product name, amount and weight : " << endl;
        cin >> tName >> tAmount >> tWeight; // getting temporary variables

        name.push_back(tName); // assigning
        amount.push_back(tAmount);
        weight.push_back(tWeight);

        count++;

        cout << "Add more? (Y/n): "; // add more? Go on if yes...
        cin >> ask;

    } while (ask == 'Y' || ask == 'y');
}
void print()
{
    cout << "\nProduct display:\n"
         << endl;
    for (int i = 0; i < count; i++)
    {
        cout << name[i] << " - " << amount[i] << " , " << weight[i] << " kg" << endl;
        cout << "------------------------" << endl;
    }
}
</code>```

Sample Output

```<code>WELCOME!
Give product name, amount and weight :
ABC 12 55.5
Add more? (Y/n): y
Give product name, amount and weight :
SSD 33 43.2
Add more? (Y/n): n

Product display:

ABC - 12 , 55.5 kg
------------------------
SSD - 33 , 43.2 kg
------------------------
</code>```

Example 2

You can do the same thing just with few modifications, but having static number isn't considered dynamic. You can use arrays for your program as stated below.

Rather than:

```<code>string name;
int n, amount;
float weight;
</code>```

Consider const int MAX = 1024; and use (class variables must be visible only inner the class and nowhere else):

```<code>private: // declare on top of the class ("private:" is by default and redundant)
    string name[MAX];
    int n, amount[MAX];
    float weight[MAX];
</code>```

Edited & working example class:

```<code>void get()
{
    for (int i = 0; i < n; i++)
    {
        cout << "Give product name,amount and weight : " << endl;
        cin >> name[i] >> amount[i] >> weight[i];
    }
}
void print()
{
    cout << "\nProduct display:\n"
         << endl;
    for (int i = 0; i < n; i++)
    {
        cout << name[i] << " - " << amount[i] << " , " << weight[i] << " kg" << endl;
        cout << "------------------------" << endl;
    }
}
</code>```

Sample Output

```<code>Give the number of products you want to get at Market :
2
Give product name,amount and weight :
ABC 25 102
Give product name,amount and weight :
BDE 22 333

Product display:

ABC - 25 , 102 kg
------------------------
BDE - 22 , 333 kg
------------------------
</code>```

Title: C++ class loop in main

Body:
I need help in a simple way of solving a part of my code that i cant seem to make it work.The point of my "assignment" is that everything must try to be in one class.Now the problem i am having is at a part of my code where it is suppose to "print" the n number of products meaning that it displays what you  have  inputted in the void get() part,but the problem i cant seem to resolve is it only prints the last name,amount,weight of the product and not everything written.

   class Class
{
public:
    string name;
    int n, amount;
    float weight;
    void market()
    {
        cout << "Give the number of products you want to get at Market : " << endl;
        cin >> n;
    }
    void get()
    {
        for (int i = 0; i < n; i++)
        {
            cout << "Give product name,amount and weight : " << endl;
            cin >> name >> amount >> weight;
        }
    }
    void print()
    {
        cout << "\nProduct display:\n" << endl;
        for (int i = 0; i < n; i++)
        {
            cout << name << " - " << amount << " , " << weight << " kg" << endl;
            cout << "------------------------" << endl;
        }
    };
};

The main part.

int main()
    {
            Class market;
            market.market();
            market.get();
            market.print();

    }

Body:
You must use a std::vector<TYPE> (example 1), or array for holding multiple data in a single variable (example 2).

Example 1

Since you've been coding in C++ programming language, it's highly recommended to use std::vector<> for best results.

Consider the class example (read comments too):

int count = 0; // PRIVATE SECTION
char ask;
std::vector<std::string> name;
std::vector<int> amount;
std::vector<float> weight;
std::string tName; // temp variables
int tAmount;
float tWeight;

public:

void market()
{
    cout << "WELCOME!" << endl; // nothing's required with vector
}
void get()
{
    do {
        cout << "Give product name, amount and weight : " << endl;
        cin >> tName >> tAmount >> tWeight; // getting temporary variables

        name.push_back(tName); // assigning
        amount.push_back(tAmount);
        weight.push_back(tWeight);

        count++;

        cout << "Add more? (Y/n): "; // add more? Go on if yes...
        cin >> ask;

    } while (ask == 'Y' || ask == 'y');
}
void print()
{
    cout << "\nProduct display:\n"
         << endl;
    for (int i = 0; i < count; i++)
    {
        cout << name[i] << " - " << amount[i] << " , " << weight[i] << " kg" << endl;
        cout << "------------------------" << endl;
    }
}

Sample Output

WELCOME!
Give product name, amount and weight :
ABC 12 55.5
Add more? (Y/n): y
Give product name, amount and weight :
SSD 33 43.2
Add more? (Y/n): n

Product display:

ABC - 12 , 55.5 kg
------------------------
SSD - 33 , 43.2 kg
------------------------

Example 2

You can do the same thing just with few modifications, but having static number isn't considered dynamic. You can use arrays for your program as stated below.

Rather than:

string name;
int n, amount;
float weight;

Consider const int MAX = 1024; and use (class variables must be visible only inner the class and nowhere else):

private: // declare on top of the class ("private:" is by default and redundant)
    string name[MAX];
    int n, amount[MAX];
    float weight[MAX];

Edited & working example class:

void get()
{
    for (int i = 0; i < n; i++)
    {
        cout << "Give product name,amount and weight : " << endl;
        cin >> name[i] >> amount[i] >> weight[i];
    }
}
void print()
{
    cout << "\nProduct display:\n"
         << endl;
    for (int i = 0; i < n; i++)
    {
        cout << name[i] << " - " << amount[i] << " , " << weight[i] << " kg" << endl;
        cout << "------------------------" << endl;
    }
}

Sample Output

Give the number of products you want to get at Market :
2
Give product name,amount and weight :
ABC 25 102
Give product name,amount and weight :
BDE 22 333

Product display:

ABC - 25 , 102 kg
------------------------
BDE - 22 , 333 kg
------------------------


来源: stackexchange

答:
You're actually overwriting name, amount and weight. You have to make use of something similar to std::vector:

class Class {
    public:
        std::vector<string> names;
        // Same for others
```

<p>When you get them from <code>std::cin</code> you have to push them into the vector:</p>

<pre class="lang-cpp prettyprint-override"><code>names.push_back(name);
amounts.push_back(amount);
weights.push_back(weight);
</code>```

When printing you loop over the vectors:

for (int i = 0; i < n; i++) {
    cout << names[i] << " - " << amounts[i] << " , " << weights[i] << " kg" << endl;
    cout << "------------------------" << endl;
}
```

ContentLicense: CC BY-SA 4.0

Title: C++ class loop in main

Body:
You're actually overwriting name, amount and weight. You have to make use of something similar to std::vector:

class Class {
    public:
        std::vector<string> names;
        // Same for others

When you get them from std::cin you have to push them into the vector:

names.push_back(name);
amounts.push_back(amount);
weights.push_back(weight);

When printing you loop over the vectors:

for (int i = 0; i < n; i++) {
    cout << names[i] << " - " << amounts[i] << " , " << weights[i] << " kg" << endl;
    cout << "------------------------" << endl;
}


问:
Shared array multiprocessing Python
I am running a multi-process code in Python with a shared array. The problem is that I can't initialise that array...
To share an array in a multi-process program I have read I need to use multiprocessing.Array, but when I try it as in the code below it is not printing anything + I don't have error messages.

```<code>import multiprocessing
...
...

if  __name__ == "__main__":

   an_array= multiprocessing.Array("i", [1,2])

   print(an_array)       # why does it not print anything? I was expecting to print [1,2]

   p1 = multiprocessing.Process(target=function1, args = [an_array, 3]
</code>```

答:
To print elements inside the Array do the following:

import multiprocessing

if __name__ == '__main__':

    an_array = multiprocessing.Array("i", [1, 2])

    # first choice to print element in Array:
    for element in an_array:
        print(element)

    # second choice to print elements in Array:
    print(an_array[:])

    # third choice to print elements in Array:
    print(list(an_array[:]))
```

Title: Shared array multiprocessing Python

Body:
I am running a multi-process code in Python with a shared array. The problem is that I can't initialise that array...
To share an array in a multi-process program I have read I need to use multiprocessing.Array, but when I try it as in the code below it is not printing anything + I don't have error messages.

import multiprocessing
...
...

if  __name__ == "__main__":

   an_array= multiprocessing.Array("i", [1,2])

   print(an_array)       # why does it not print anything? I was expecting to print [1,2]

   p1 = multiprocessing.Process(target=function1, args = [an_array, 3]


问:
How to Plot Several 3D Trajectories in Julia (using a for-loop, presumably?) -- also, how to animate over time?
I am trying to plot a set of 3D trajectories in a single plot in Julia. By 3-D trajectories I mean: different sets of 3-D coordinates over time. These trajectories are stored in a multidimensional array called positions, where the dimensions respectively correspond to the Trajectory ID, X-Y-Z coordinate and Time. For example, positions[75,2,1:100] refers to the Y (2nd) coordinate of the 75th Trajectory, across the first 100 timesteps of the trajectory.

I am trying to figure out why the following code doesn't work:

```<code>using Plots

plotlyjs()

time_indices = 1:100

ax= scatter3d(positions[1,1,time_indices],positions[1,2,time_indices],positions[1,3,time_indices],label="Trajectory 1 for times 1 to 100")

for n in 2:size(positions,1)
    scatter3d!(ax, positions[n,1,time_indices], positions[n,2,time_indices],positions[n,3,time_indices],label="Trajectory $n for times 1 to 100")
end

</code>```

When I run that code, I don't see anything in the Plots window (I'm using Atom), although I don't get any errors / it appears to run successfully. Any thoughts on what I'm doing wrong? Should I use a different backend? It doesn't work on either gr() or plotlyjs() (those are the only ones I know of, based on tutorials I've completed).

Follow up question: once I can successfully plot such 3-D trajectories in a single static plot, I am wondering how you would go about animating them over time (using @gif or @animate macros, presumably)? I am asking this here, because I wasn't able to understand the documentation / tutorial on 3D animations, unfortunately. Googling / other sources have also not helped :(

答:
It looks like you're just missing a display(ax) at the end, after the loop.

Edit: to animate, try

```<code>anim = @animate for n in 1:size(positions,1)
    scatter3d(positions[n,1,time_indices], positions[n,2,time_indices],positions[n,3,time_indices],label="Trajectory $n for times 1 to 100")
end
gif(anim, "some_file_name.gif", fps=15)
</code>```

(or if you want the prior trajectories to show up as well in later frames of the gif, then replace the scatter3d with scatter3d!)

I can't test the above without having your positions, but here is another example that I have just tested on Julia 1.5.0beta with Plots and the GR backend:

```<code>using Plots; gr();
anim = @animate for i=1:100
    plot(sin.(range(0,i/10*pi,length=1000)), label="", ylims=(-1,1))
end
gif(anim, "anim_fps15.gif", fps=15)
</code>```

Body:
I am trying to plot a set of 3D trajectories in a single plot in Julia. By 3-D trajectories I mean: different sets of 3-D coordinates over time. These trajectories are stored in a multidimensional array called positions, where the dimensions respectively correspond to the Trajectory ID, X-Y-Z coordinate and Time. For example, positions[75,2,1:100] refers to the Y (2nd) coordinate of the 75th Trajectory, across the first 100 timesteps of the trajectory.

I am trying to figure out why the following code doesn't work:

using Plots

plotlyjs()

time_indices = 1:100

ax= scatter3d(positions[1,1,time_indices],positions[1,2,time_indices],positions[1,3,time_indices],label="Trajectory 1 for times 1 to 100")

for n in 2:size(positions,1)
    scatter3d!(ax, positions[n,1,time_indices], positions[n,2,time_indices],positions[n,3,time_indices],label="Trajectory $n for times 1 to 100")
end

When I run that code, I don't see anything in the Plots window (I'm using Atom), although I don't get any errors / it appears to run successfully. Any thoughts on what I'm doing wrong? Should I use a different backend? It doesn't work on either gr() or plotlyjs() (those are the only ones I know of, based on tutorials I've completed).

Follow up question: once I can successfully plot such 3-D trajectories in a single static plot, I am wondering how you would go about animating them over time (using @gif or @animate macros, presumably)? I am asking this here, because I wasn't able to understand the documentation / tutorial on 3D animations, unfortunately. Googling / other sources have also not helped :(

Body:
It looks like you're just missing a display(ax) at the end, after the loop.

Edit: to animate, try

anim = @animate for n in 1:size(positions,1)
    scatter3d(positions[n,1,time_indices], positions[n,2,time_indices],positions[n,3,time_indices],label="Trajectory $n for times 1 to 100")
end
gif(anim, "some_file_name.gif", fps=15)

(or if you want the prior trajectories to show up as well in later frames of the gif, then replace the scatter3d with scatter3d!)

I can't test the above without having your positions, but here is another example that I have just tested on Julia 1.5.0beta with Plots and the GR backend:

using Plots; gr();
anim = @animate for i=1:100
    plot(sin.(range(0,i/10*pi,length=1000)), label="", ylims=(-1,1))
end
gif(anim, "anim_fps15.gif", fps=15)


问:
Unable to fetch ZONE from the Cloud Shell instance
I want to get the zone where the Cloud Shell VM instance resides, I created this custom script to fetch the zone via the metadata server; however it's not working. What can I be missing (I know that if I were to do this from a normal VM instance I would have to enable API access to the metadata server)</p>

```<code>#! /bin/bash
ZONE=$(curl -s http://metadata.google.internal/computeMetadata/v1/instance/ -H "Metadata-Flavor: Google")
echo $ZONE
</code>```

答:
In order to see the Zone where your Cloud Shell is in you can run the following command:

```<code>curl -H "Metadata-Flavor: Google" metadata/computeMetadata/v1/instance/zone
</code>```

You may want to use this as a reference for your script or use it directly as presented.

Body:
I want to get the zone where the Cloud Shell VM instance resides, I created this custom script to fetch the zone via the metadata server; however it's not working. What can I be missing (I know that if I were to do this from a normal VM instance I would have to enable API access to the metadata server)

#! /bin/bash
ZONE=$(curl -s http://metadata.google.internal/computeMetadata/v1/instance/ -H "Metadata-Flavor: Google")
echo $ZONE

Body:
In order to see the Zone where your Cloud Shell is in you can run the following command:

curl -H "Metadata-Flavor: Google" metadata/computeMetadata/v1/instance/zone

You may want to use this as a reference for your script or use it directly as presented.


问:
ansible: how to use a interactive python script (custom module)
please advise the way to use python interactive script as custom module.

my python script sometimes prompts like below.

```<code>[ansible@localhost ~]$ python test.py
No errors found.
do you want to proceed [y/n]
[ansible@localhost ~]$
</code>```

sometimes:

```<code>[ansible@localhost ~]$ python test.py
3 Errors found.
Cant proceed with script.
[ansible@localhost ~]$
</code>```

output result & interactive output may vary depending on the conditions, written in my script.

i want to understand how to use this script under custom module in ansible, and deal with interactive prompt responses..

i read that expect module can help in ansible, to provide response, but in my script, response cant be same all the time.

for example, i have tried expect module to and it failed since my python script result was different, it has 4-6various responses as per conditions.

```<code>"invocation": {
    "module_args": {
        "chdir": null,
        "command": "/usr/bin/python3 test3.py",
        "creates": null,
        "echo": true,
        "removes": null,
        "responses": {
            "do you want to proceed [y/n]": "y"
        },
        "timeout": 30
</code>```

above failed output is when ansible expect a response as mentioned above, but my actual python script result was different.

please advice.

thanks.

答:
If I have understood the problem, your script gives you multiple possibilities. This is how I will handle it using pexpect module in a yml file for with ansible-playbook:</p>

```<code>---

- hosts      : localhost
  remote_user: USER_NAME
  tasks      :
    - name  : run the script
      expect:
        echo     : yes
        command  : /usr/bin/python3 test3.py
        timeout  : 30
        responses:
          (?i)do you want to proceed [y/n]                                       : "y"
          (?i)2nd OPTION                                                         : "y/n"
          (?i)3rd OPTION                                                         : "y/n"
</code>```

Body:
please advise the way to use python interactive script as custom module.

my python script sometimes prompts like below.

[ansible@localhost ~]$ python test.py
No errors found.
do you want to proceed [y/n]
[ansible@localhost ~]$

sometimes:

[ansible@localhost ~]$ python test.py
3 Errors found.
Cant proceed with script.
[ansible@localhost ~]$

output result & interactive output may vary depending on the conditions, written in my script.

i want to understand how to use this script under custom module in ansible, and deal with interactive prompt responses..

i read that expect module can help in ansible, to provide response, but in my script, response cant be same all the time.

for example, i have tried expect module to and it failed since my python script result was different, it has 4-6various responses as per conditions.

"invocation": {
    "module_args": {
        "chdir": null,
        "command": "/usr/bin/python3 test3.py",
        "creates": null,
        "echo": true,
        "removes": null,
        "responses": {
            "do you want to proceed [y/n]": "y"
        },
        "timeout": 30

above failed output is when ansible expect a response as mentioned above, but my actual python script result was different.

please advice.

thanks.

Body:
If I have understood the problem, your script gives you multiple possibilities. This is how I will handle it using pexpect module in a yml file for with ansible-playbook:

---

- hosts      : localhost
  remote_user: USER_NAME
  tasks      :
    - name  : run the script
      expect:
        echo     : yes
        command  : /usr/bin/python3 test3.py
        timeout  : 30
        responses:
          (?i)do you want to proceed [y/n]                                       : "y"
          (?i)2nd OPTION                                                         : "y/n"
          (?i)3rd OPTION                                                         : "y/n"


问:
How to dynamically call accessor methods in Ruby
Regardless of whether it's good practice or not, how can I dynamically call accessor methods in Ruby?

Here's an example class:

```<code>class Test_Class
  attr_accessor :a, :b
end
</code>```

I can use the Object.send method to read the variable...

```<code>instance.a = "value"
puts( instance.send( "a" ) )
# => value
</code>```

But I'm having a hard time trying to write to it. These throw "wrong number of arguments (1 for 0) (ArgumentError)"

```<code>instance.send("a", "value")
</code>```

and

```<code>instance.method("a").call("value")
</code>```

Please help me StackOverflow!

答:
I am not a ruby expert, but I think that you could do:</p>

```<code>instance.send("a=", "value")
</code>```

OwnerDisplayName: THE Joe Zack

ContentLicense: CC BY-SA 2.5

Body:
Regardless of whether it's good practice or not, how can I dynamically call accessor methods in Ruby?

Here's an example class:

class Test_Class
  attr_accessor :a, :b
end

I can use the Object.send method to read the variable...

instance.a = "value"
puts( instance.send( "a" ) )
# => value

But I'm having a hard time trying to write to it. These throw "wrong number of arguments (1 for 0) (ArgumentError)"

instance.send("a", "value")

and

instance.method("a").call("value")

Please help me StackOverflow!

Body:
I am not a ruby expert, but I think that you could do:

instance.send("a=", "value")

OwnerDisplayName: Angela


问:
c# List view focus
I have a problem in focusing the listview.In my form i have a listview which contains two columns(Question_text, question_id).When a button is get clicked(Show button) a dialog box is get opened and it show show the selected question_text and question_id.Right now i am able to show the information in the dialog box.But the problem only occurs only when i close the dialog box,the focus on the list view is gone.I what the focus to remain on the same item of list view after closing the dialog box.Can any one help me.Thanks in advance.

Ok this is my code.

There i am reading getting the selected item question id using the listview1_selectionIndexchanged();

```<code>     private void btnAdd_Question_Click(object sender, EventArgs e)
    {
        //Add Question Dialog box is shown
        add.ShowDialog();
    }

    private void btnEdit_Question_Click(object sender, EventArgs e)
    {
        //Getting the listview selected Item
        for (int i = 0; i < listView1.SelectedItems.Count; i++)
        {

            String a1 = listView1.SelectedItems[i].Text;
            int b1 = listView1.SelectedIndices[i];
            //Open the connection
             myConnection = new SqlConnection(@"User ID=sa;Password=password123;Initial Catalog=dishtv;Persist Security Info=True;Data Source=ENMEDIA-EA6278E\ENMEDIA");
            try
            {

                myConnection.Open();
                String start_time = string.Format("SELECT Question_text  from otvtbl_question where question_id={0}", a1);
                com = new SqlCommand(start_time, myConnection);
                dr = com.ExecuteReader();

                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        now = DateTime.Now;
                     //Getting the start time and convert into date time Format
                       String a = dr["question_id"].ToString();
                       date = Convert.ToDateTime(a);

                    }
                    myConnection.Close();
                }
                //If data and time is greater then current time then allow the
               // Edit question dialog box to launch
                if (date > now)
                {
                    edit.question_id = a1;

                    edit.ShowDialog();
                }
                else
                {
                    MessageBox.Show("you cant edit this question");
                }

            }

            //Catch the Exceptional error
            catch (Exception ex)
            {
                MessageBox.Show("Error while Deleteing the Data" + ex);
            }

        }

    }
</code>```

After that i am calling a another form and showing the information.Here i created a class edit.showdialog() to launch a dialog box.

In my edit dialog box:

Here I am passing  the question_id from the main form to dialog box and displaying the question_text in the dialog box.When the cancel button is get clicked then the dialog box get closed.But the focus is not remaining on the same item in list view.Once again i click on edit button for editing without selecting the item in list view it select the previous one automatically without showing the focus on it.

public String question_id;

private void Edit_Question_Load(object sender, EventArgs e)
        {

```<code>        EditData();
    }

   public void EditData()
    {
         myConnection = new SqlConnection(@"User ID=sa;Password=password123;Initial Catalog=dishtv;Persist Security Info=True;Data Source=ENMEDIA-EA6278E\ENMEDIA");
           myConnection.Open();
            String question = string.Format("SELECT question_text from otvtbl_question where question_id={0}", question_id);
            com = new SqlCommand(question, myConnection);
            dr = com.ExecuteReader();

            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    //Assign to your textbox here
                    txtQuestion.Text = dr["question_text"].ToString();
                }
            }
            myConnection.Close();

     private void btnCancel_Click_1(object sender, EventArgs e)
    {

        this.Close();
    }
</code>```

答:
```<code>private void btnAdd_Question_Click(object sender, EventArgs e)
{
    var focusedItem = listView1.FocusedItem;
    add.ShowDialog();
    listView1.FocusedItem = focusedItem;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: c# List view focus

Body:
I have a problem in focusing the listview.In my form i have a listview which contains two columns(Question_text, question_id).When a button is get clicked(Show button) a dialog box is get opened and it show show the selected question_text and question_id.Right now i am able to show the information in the dialog box.But the problem only occurs only when i close the dialog box,the focus on the list view is gone.I what the focus to remain on the same item of list view after closing the dialog box.Can any one help me.Thanks in advance.

Ok this is my code.

There i am reading getting the selected item question id using the listview1_selectionIndexchanged();

     private void btnAdd_Question_Click(object sender, EventArgs e)
    {
        //Add Question Dialog box is shown
        add.ShowDialog();
    }

    private void btnEdit_Question_Click(object sender, EventArgs e)
    {
        //Getting the listview selected Item
        for (int i = 0; i < listView1.SelectedItems.Count; i++)
        {

            String a1 = listView1.SelectedItems[i].Text;
            int b1 = listView1.SelectedIndices[i];
            //Open the connection
             myConnection = new SqlConnection(@"User ID=sa;Password=password123;Initial Catalog=dishtv;Persist Security Info=True;Data Source=ENMEDIA-EA6278E\ENMEDIA");
            try
            {

                myConnection.Open();
                String start_time = string.Format("SELECT Question_text  from otvtbl_question where question_id={0}", a1);
                com = new SqlCommand(start_time, myConnection);
                dr = com.ExecuteReader();

                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        now = DateTime.Now;
                     //Getting the start time and convert into date time Format
                       String a = dr["question_id"].ToString();
                       date = Convert.ToDateTime(a);

                    }
                    myConnection.Close();
                }
                //If data and time is greater then current time then allow the
               // Edit question dialog box to launch
                if (date > now)
                {
                    edit.question_id = a1;

                    edit.ShowDialog();
                }
                else
                {
                    MessageBox.Show("you cant edit this question");
                }

            }

            //Catch the Exceptional error
            catch (Exception ex)
            {
                MessageBox.Show("Error while Deleteing the Data" + ex);
            }

        }

    }

After that i am calling a another form and showing the information.Here i created a class edit.showdialog() to launch a dialog box.

In my edit dialog box:

Here I am passing  the question_id from the main form to dialog box and displaying the question_text in the dialog box.When the cancel button is get clicked then the dialog box get closed.But the focus is not remaining on the same item in list view.Once again i click on edit button for editing without selecting the item in list view it select the previous one automatically without showing the focus on it.

public String question_id;

private void Edit_Question_Load(object sender, EventArgs e)
        {

        EditData();
    }

   public void EditData()
    {
         myConnection = new SqlConnection(@"User ID=sa;Password=password123;Initial Catalog=dishtv;Persist Security Info=True;Data Source=ENMEDIA-EA6278E\ENMEDIA");
           myConnection.Open();
            String question = string.Format("SELECT question_text from otvtbl_question where question_id={0}", question_id);
            com = new SqlCommand(question, myConnection);
            dr = com.ExecuteReader();

            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    //Assign to your textbox here
                    txtQuestion.Text = dr["question_text"].ToString();
                }
            }
            myConnection.Close();

     private void btnCancel_Click_1(object sender, EventArgs e)
    {

        this.Close();
    }


问:
Generate RSA key pair with WebCrypto in Chromium
The following code works in Firefox 76.0.1:

```<code>"use strict"
let RSAKeys
(async () => {
  RSAKeys = await crypto.subtle.generateKey({
      name: "RSA-OAEP",
      modulusLength: 3072,
      publicExponent: new Uint8Array([1, 0, 1]),
      hash: "SHA-256"},
    true,
// Chromium bug causes it to falsely complain that the array is empty. Sometimes adding "encrypt" helps.
    ["wrapKey"])
})()
</code>```

but in Chromium 80 I get:

Uncaught (in promise) DOMException: Usages cannot be empty when creating a key.

["wrapKey"] clearly isn't an empty array, so it seems to be a browser bug. Probably this one. Can you confirm? And more importantly, do you know a workaround? (Adding the encrypt usage helped but only the first time, then the same error.) It has to be an asymmetric cipher supporting wrapping keys. According to the table in the relevant chapter of the spec, RSA-OAEP is the only possibility.

答:
I can reproduce the issue on Chromium version 85.0.4162.0: The key usage ["wrapKey"] generates the posted error message. But I can't reproduce that an adding of the key usage encrypt (i.e. ["wrapKey", "encrypt"]) solves the problem (not even the fist time). However, with the addition of the key usage unwrapKey (i.e. ["wrapKey", "unwrapKey"]) the error no longer occurs.

SubtleCrypto.generateKey() returns a CryptoKeyPair for "RSA-OAEP" that contains the RSA key pair. If you look in the Firefox browser console at the key pair generated with the key usage ["wrapKey", "unwrapKey"], you can see that the key usage of the public key is ["wrapKey"] and that of the private key is ["unwrapKey"]. Both are plausible, since the public key is used for wrapping and the private key for unwrapping:

However, if you look in the Firefox browser console at the key pair generated with the key usage ["wrapKey"], you can see that the key usage of the public key is unchanged ["wrapKey"], while that of the private key is empty:

So Chromium prevents the generation of a key without key usage by the corresponding error message (which obviously refers to the private key with the empty key usage). In contrast to Chromium, Firefox obviously allows this.

Now is that a Chromium bug? Actually it makes not much sense to create a key without a key usage, because it cannot be used!

Example for Firefox browser: If the following code is executed in the Firefox browser, the key pair is indeed generated and a key is wrapped because of the key usage wrapKey for the public key, but the unwrapping fails with an InvalidAccessError if the key usage unwrapKey for the private key is missing:

var test = async () => {

  try {

    var mode = document.querySelector('input[name="keyUsages"]:checked').value;
    var keyUsages = (mode === "wrap") ? ["wrapKey"] : ["wrapKey", "unwrapKey"]

    // Create RSA key pair
    var RSAKeys = await crypto.subtle.generateKey(
      {name: "RSA-OAEP", modulusLength: 3072, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), hash: {name: "SHA-256"}},
      true,
      keyUsages);

    // Create key to wrap
    var keyToWrap = await window.crypto.subtle.generateKey(
      {name: "AES-GCM", length: 128},
      true,
      ["encrypt", "decrypt"]);

    // Wrap key
    var wrappedKey = await window.crypto.subtle.wrapKey(
      "raw",
      keyToWrap,
      RSAKeys.publicKey,
      {name: "RSA-OAEP", hash: {name: "SHA-256"}});

    // Unwrap key
    var unwrappedKey = await window.crypto.subtle.unwrapKey(
      "raw",
      wrappedKey,
      RSAKeys.privateKey,
      {name: "RSA-OAEP", modulusLength: 3072, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), hash: {name: "SHA-256"}},
      {name: "AES-GCM", length: 128},
      false,
      ["encrypt", "decrypt"]);

    document.getElementById("result").innerHTML = "Secret key for " + unwrappedKey.algorithm.name + " unwrapped.";
    console.log(unwrappedKey);

    } catch(e) {
      document.getElementById("result").innerHTML = e.name + ": " + e.message;
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 7.0em !important; }</code>```

<!DOCTYPE html>

    <input type="radio" name="keyUsages" value="wrap" checked="true"> ["wrapKey"]
    <input type="radio" name="keyUsages" value="wrapUnwrap"> ["wrapKey", "unwrapKey"]
    <button onclick="test()">Run</button>

```

Therefore I would not classify this as a bug (but that's just my opinion).

Body:
The following code works in Firefox 76.0.1:

"use strict"
let RSAKeys
(async () => {
  RSAKeys = await crypto.subtle.generateKey({
      name: "RSA-OAEP",
      modulusLength: 3072,
      publicExponent: new Uint8Array([1, 0, 1]),
      hash: "SHA-256"},
    true,
// Chromium bug causes it to falsely complain that the array is empty. Sometimes adding "encrypt" helps.
    ["wrapKey"])
})()

but in Chromium 80 I get:

Uncaught (in promise) DOMException: Usages cannot be empty when creating a key.

["wrapKey"] clearly isn't an empty array, so it seems to be a browser bug. Probably this one. Can you confirm? And more importantly, do you know a workaround? (Adding the encrypt usage helped but only the first time, then the same error.) It has to be an asymmetric cipher supporting wrapping keys. According to the table in the relevant chapter of the spec, RSA-OAEP is the only possibility.

Body:
I can reproduce the issue on Chromium version 85.0.4162.0: The key usage ["wrapKey"] generates the posted error message. But I can't reproduce that an adding of the key usage encrypt (i.e. ["wrapKey", "encrypt"]) solves the problem (not even the fist time). However, with the addition of the key usage unwrapKey (i.e. ["wrapKey", "unwrapKey"]) the error no longer occurs.

SubtleCrypto.generateKey() returns a CryptoKeyPair for "RSA-OAEP" that contains the RSA key pair. If you look in the Firefox browser console at the key pair generated with the key usage ["wrapKey", "unwrapKey"], you can see that the key usage of the public key is ["wrapKey"] and that of the private key is ["unwrapKey"]. Both are plausible, since the public key is used for wrapping and the private key for unwrapping:

However, if you look in the Firefox browser console at the key pair generated with the key usage ["wrapKey"], you can see that the key usage of the public key is unchanged ["wrapKey"], while that of the private key is empty:

So Chromium prevents the generation of a key without key usage by the corresponding error message (which obviously refers to the private key with the empty key usage). In contrast to Chromium, Firefox obviously allows this.

Now is that a Chromium bug? Actually it makes not much sense to create a key without a key usage, because it cannot be used!

Example for Firefox browser: If the following code is executed in the Firefox browser, the key pair is indeed generated and a key is wrapped because of the key usage wrapKey for the public key, but the unwrapping fails with an InvalidAccessError if the key usage unwrapKey for the private key is missing:

var test = async () => {

  try {

    var mode = document.querySelector('input[name="keyUsages"]:checked').value;
    var keyUsages = (mode === "wrap") ? ["wrapKey"] : ["wrapKey", "unwrapKey"]

    // Create RSA key pair
    var RSAKeys = await crypto.subtle.generateKey(
      {name: "RSA-OAEP", modulusLength: 3072, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), hash: {name: "SHA-256"}},
      true,
      keyUsages);

    // Create key to wrap
    var keyToWrap = await window.crypto.subtle.generateKey(
      {name: "AES-GCM", length: 128},
      true,
      ["encrypt", "decrypt"]);

    // Wrap key
    var wrappedKey = await window.crypto.subtle.wrapKey(
      "raw",
      keyToWrap,
      RSAKeys.publicKey,
      {name: "RSA-OAEP", hash: {name: "SHA-256"}});

    // Unwrap key
    var unwrappedKey = await window.crypto.subtle.unwrapKey(
      "raw",
      wrappedKey,
      RSAKeys.privateKey,
      {name: "RSA-OAEP", modulusLength: 3072, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), hash: {name: "SHA-256"}},
      {name: "AES-GCM", length: 128},
      false,
      ["encrypt", "decrypt"]);

    document.getElementById("result").innerHTML = "Secret key for " + unwrappedKey.algorithm.name + " unwrapped.";
    console.log(unwrappedKey);

    } catch(e) {
      document.getElementById("result").innerHTML = e.name + ": " + e.message;
    }
}

.as-console-wrapper { max-height: 7.0em !important; }

<!DOCTYPE html>
<html>
<body height="200">
    <input type="radio" name="keyUsages" value="wrap" checked="true"> ["wrapKey"]
    <input type="radio" name="keyUsages" value="wrapUnwrap"> ["wrapKey", "unwrapKey"]
    <button onclick="test()">Run</button><br/>
    <p id="result"></p>
</body>
</html>

Therefore I would not classify this as a bug (but that's just my opinion).


问:
find how many elements from the beginning of the array must be added to get a total of more than 10
I have an array with numbers. Need to find how many elements from the beginning of the array must be added to get a total of more than 10. In the code I have to use reduce

    let arr = [2, 3, 1, 0, 4, 5, 4];

The console in this case must display the number 6.

My code didn't work:

```<code>let arr = [2, 3, 1, 0, 4, 5, 4];
let sumNumber = arr.reduce((sum, elem, index) => {

    let ourSum = 0;
    while (ourSum <= 10) {
        return sum + elem;
    }
    index++

}, 0)
console.log(sumNumber);
</code>```

答:
You can do this with some method, you do not have to loop through the rest of the elements when condition is achived.

var arr = [2, 3, 1, 0, 4, 5, 4];
var obj = {sum : 0, index : 0 };

arr.some((k,i)=>{
 obj.sum+=k;
 if(obj.sum > 10) {
   obj.index = i+1;
   return true
  }
 });
console.log(obj)```

Body:
I have an array with numbers. Need to find how many elements from the beginning of the array must be added to get a total of more than 10. In the code I have to use reduce

    let arr = [2, 3, 1, 0, 4, 5, 4];

The console in this case must display the number 6.

My code didn't work:

let arr = [2, 3, 1, 0, 4, 5, 4];
let sumNumber = arr.reduce((sum, elem, index) => {

    let ourSum = 0;
    while (ourSum <= 10) {
        return sum + elem;
    }
    index++

}, 0)
console.log(sumNumber);


问:
Populate a combo box with a list of last 10 latest folders from a directory
I have a combo box that I want to be filled with a list of last 10 latest folders in a specified directory. Say,

There are 40 folders. In the combo box it should list the latest 10 folders.

Thank you,

```<code>Private Sub UserForm_Initialize()
Dim name

  For Each name In ListDirectory(Path:="C:\Users\AllertonFC\Documents\FA Level 1 & Level 2\", AttrInclude:=vbDirectory, AttrExclude:=vbSystem Or vbHidden)
    Me.ComboBox1.AddItem name
  Next name
End Sub

Function ListDirectory(Path As String, AttrInclude As VbFileAttribute, Optional AttrExclude As VbFileAttribute = False) As Collection
  Dim Filename As String
  Dim Attribs As VbFileAttribute

  Set ListDirectory = New Collection

  ' first call to Dir() initializes the list
  Filename = Dir(Path, AttrInclude)

  While Filename <> ""
    Attribs = GetAttr(Path & Filename)
    ' to be added, a file must have the right set of attributes
    If Attribs And AttrInclude And Not (Attribs And AttrExclude) Then
      ListDirectory.Add Filename, Path & Filename
    End If
    ' fetch next filename
    Filename = Dir
  Wend
End Function
</code>```

答:
This should work, I find it easier to put values into a string and split it at the last minute into an array, also not using Dir, instead using a Scripting.FileSystemObject</p>

```<code>Public Sub cBoxFiller()
   Dim oFS As Object, SrcFldr As String, oFldr As Object, xFldr As Object
   Dim FldrsTxt As String, FldrsAR() As String, GudCtr As Long
   Dim cBoxTxt As String, i As Long

   SrcFldr = "C:\Users\AllertonFC\Documents\FA Level 1 & Level 2\"
   Set oFS = CreateObject("Scripting.FileSystemObject")
   Set oFldr = oFS.getfolder(SrcFldr)

   ' Generate an Array of ALL SubFolders
     FldrsTxt = ""
     For Each xFldr In oFldr.subFolders
        FldrsTxt = IIf(FldrsTxt = "", "", FldrsTxt & vbCrLf) & xFldr.name  ' or xFldr.Path
     Next xFldr
     FldrsAR = Split(FldrsTxt, vbCrLf)
   ' Done

   ' Build a String of Last 10 Folders - separated by VbCrLf
     GudCtr = 0
     For i = UBound(FldrsAR) To LBound(FldrsAR) Step -1
        If GudCtr < 10 Then
           GudCtr = GudCtr + 1
           cBoxTxt = IIf(cBoxTxt = "", "", cBoxTxt & vbCrLf) & FldrsAR(i)
        End If
     Next i
   ' Done

   ' Split into an Array & Assign to the ComboBox
     ComboBox1.List = Split(cBoxTxt, vbCrLf)
   ' Done
End Sub
</code>```

Body:
I have a combo box that I want to be filled with a list of last 10 latest folders in a specified directory. Say,

There are 40 folders. In the combo box it should list the latest 10 folders.

Thank you,

Private Sub UserForm_Initialize()
Dim name

  For Each name In ListDirectory(Path:="C:\Users\AllertonFC\Documents\FA Level 1 & Level 2\", AttrInclude:=vbDirectory, AttrExclude:=vbSystem Or vbHidden)
    Me.ComboBox1.AddItem name
  Next name
End Sub

Function ListDirectory(Path As String, AttrInclude As VbFileAttribute, Optional AttrExclude As VbFileAttribute = False) As Collection
  Dim Filename As String
  Dim Attribs As VbFileAttribute

  Set ListDirectory = New Collection

  ' first call to Dir() initializes the list
  Filename = Dir(Path, AttrInclude)

  While Filename <> ""
    Attribs = GetAttr(Path & Filename)
    ' to be added, a file must have the right set of attributes
    If Attribs And AttrInclude And Not (Attribs And AttrExclude) Then
      ListDirectory.Add Filename, Path & Filename
    End If
    ' fetch next filename
    Filename = Dir
  Wend
End Function

Body:
This should work, I find it easier to put values into a string and split it at the last minute into an array, also not using Dir, instead using a Scripting.FileSystemObject

Public Sub cBoxFiller()
   Dim oFS As Object, SrcFldr As String, oFldr As Object, xFldr As Object
   Dim FldrsTxt As String, FldrsAR() As String, GudCtr As Long
   Dim cBoxTxt As String, i As Long

   SrcFldr = "C:\Users\AllertonFC\Documents\FA Level 1 & Level 2\"
   Set oFS = CreateObject("Scripting.FileSystemObject")
   Set oFldr = oFS.getfolder(SrcFldr)

   ' Generate an Array of ALL SubFolders
     FldrsTxt = ""
     For Each xFldr In oFldr.subFolders
        FldrsTxt = IIf(FldrsTxt = "", "", FldrsTxt & vbCrLf) & xFldr.name  ' or xFldr.Path
     Next xFldr
     FldrsAR = Split(FldrsTxt, vbCrLf)
   ' Done

   ' Build a String of Last 10 Folders - separated by VbCrLf
     GudCtr = 0
     For i = UBound(FldrsAR) To LBound(FldrsAR) Step -1
        If GudCtr < 10 Then
           GudCtr = GudCtr + 1
           cBoxTxt = IIf(cBoxTxt = "", "", cBoxTxt & vbCrLf) & FldrsAR(i)
        End If
     Next i
   ' Done

   ' Split into an Array & Assign to the ComboBox
     ComboBox1.List = Split(cBoxTxt, vbCrLf)
   ' Done
End Sub


问:
Filter WordPress posts with custom fields
I would like to find out what is the way to filter posts of a specific category using custom fields. The result I want is exactly the same as the table here
. I have created a list like that and inside the table cells I have inserted three different custom fields each one containing a number of values. How can I use the same structure as above the list of forbes magazine and filter posts using drop down menus?</p>

答:
Custom Post type name = Software,
Custom field name = version meta

This coding is done on single.php. $version is used for call the custom field value on single.php and filter the data by custom field value.

```<code><?php $args = array('post_type' => 'software', 'showposts'=>'4', 'category_name' => '', 'orderby'   => '','meta_query' => array(array('key' => 'version_meta','value' => $version = get_post_meta($post->ID, 'version_meta', true))));
       $loop = new WP_Query( $args );
       while ( $loop->have_posts() ) : $loop->the_post();?>
        <div class="post_desc">
            <div class="thumb thmbhome3">
                <?php the_post_thumbnail();?>
            </div>
            <div class="title_des edu tthome3">
                <div class="title edu_titl ttshome3">
                    <h1><a href="<?php the_permalink(); ?>"><?php the_title();?></a></h1>
                </div>
            </div>

        </div>

    <?php endwhile; ?>
</code>```

Body:
Custom Post type name = Software,
Custom field name = version meta

This coding is done on single.php. $version is used for call the custom field value on single.php and filter the data by custom field value.

<?php $args = array('post_type' => 'software', 'showposts'=>'4', 'category_name' => '', 'orderby'   => '','meta_query' => array(array('key' => 'version_meta','value' => $version = get_post_meta($post->ID, 'version_meta', true))));
       $loop = new WP_Query( $args );
       while ( $loop->have_posts() ) : $loop->the_post();?>
        <div class="post_desc">
            <div class="thumb thmbhome3">
                <?php the_post_thumbnail();?>
            </div>
            <div class="title_des edu tthome3">
                <div class="title edu_titl ttshome3">
                    <h1><a href="<?php the_permalink(); ?>"><?php the_title();?></a></h1>
                </div>
            </div>

        </div>

    <?php endwhile; ?>


问:
ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file
When I use the command:

```<code>C:\>keytool -list -alias androiddebugkey
            -keystore .android\debug.keystore
            -storepass android -keypass android
</code>```

I get this error:

'keytool' is not recognized as an internal or external command, operable program or batch file.

I'm not able to get the certificate fingerprint(MD5) on my computer.

I have ensured that the keystore file is present in the appropriate location.

Any help?

答:
Check that the directory the keytool executable is in is on your %PATH% environment variable.

For example, on my Windows 7 machine, it is in
C:\Program Files (x86)\Java\jre6\bin, and my %PATH% variable looks like C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files (x86)\Java\jre6\bin;C:\WINDOWS\System32\WindowsPowerShell\v1.0\ (and many other entries)

Body:
When I use the command:

C:\>keytool -list -alias androiddebugkey
            -keystore .android\debug.keystore
            -storepass android -keypass android

I get this error:

'keytool' is not recognized as an internal or external command, operable program or batch file.

I'm not able to get the certificate fingerprint(MD5) on my computer.

I have ensured that the keystore file is present in the appropriate location.

Any help?


问:
How do i detect which specific button in my controller is being released in pygame
i am trying to detect which button is being pressed from my controller and when it is released.
This is how far i have managed to get.

import pygame

pygame.init()

j = pygame.joystick.Joystick(0)
j.init()

try:
    while True:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.JOYBUTTONDOWN:
                if j.get_button(1):
                    print("x")
                elif j.get_button(2):
                    print("a")
            elif event.type == pygame.JOYBUTTONUP:
                print("button released")

except KeyboardInterrupt:
    print("EXITING NOW")
    j.quit()
```

i am new to programming and i dont entirely understand this piece of code.
this detects if x or a is being pressed and if any button is being released. I want it to detect if x or a is being pressed and when they are released.
Thanks for reading!

答:
So, i coded what i needed with the help of the other answers!

```<code>import pygame

pygame.init()

j = pygame.joystick.Joystick(0)
j.init()

r = 2
t = 5
b = 1
x = 3
try:
    while True:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.JOYBUTTONDOWN:
                if j.get_button(1):
                    print("B")
                    b = 2
                elif j.get_button(2):
                    print("X")
                    x = 5
            elif event.type == pygame.JOYBUTTONUP:
                if b == r :
                    print("b2")
                    b = 1
                if x == t:
                    print("x2")
                    x = 3

except KeyboardInterrupt:
    print("EXITING NOW")
    j.quit()
</code>```

This isn't robust in any way. You need to make new strings for every button you need.
You do that by copying the button with the biggest variables and just adding 3 to every variable in the code you coppied. Please answer the original post if you can give a better answer (which probably exists).Also, when u press multiple buttons at the same time and u release atleast one it thinks you have realeased all of them.

Body:
i am trying to detect which button is being pressed from my controller and when it is released.
This is how far i have managed to get.

import pygame

pygame.init()

j = pygame.joystick.Joystick(0)
j.init()

try:
    while True:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.JOYBUTTONDOWN:
                if j.get_button(1):
                    print("x")
                elif j.get_button(2):
                    print("a")
            elif event.type == pygame.JOYBUTTONUP:
                print("button released")

except KeyboardInterrupt:
    print("EXITING NOW")
    j.quit()

i am new to programming and i dont entirely understand this piece of code.
this detects if x or a is being pressed and if any button is being released. I want it to detect if x or a is being pressed and when they are released.
Thanks for reading!

Body:
So, i coded what i needed with the help of the other answers!

import pygame

pygame.init()

j = pygame.joystick.Joystick(0)
j.init()

r = 2
t = 5
b = 1
x = 3
try:
    while True:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.JOYBUTTONDOWN:
                if j.get_button(1):
                    print("B")
                    b = 2
                elif j.get_button(2):
                    print("X")
                    x = 5
            elif event.type == pygame.JOYBUTTONUP:
                if b == r :
                    print("b2")
                    b = 1
                if x == t:
                    print("x2")
                    x = 3

except KeyboardInterrupt:
    print("EXITING NOW")
    j.quit()

This isn't robust in any way. You need to make new strings for every button you need.
You do that by copying the button with the biggest variables and just adding 3 to every variable in the code you coppied. Please answer the original post if you can give a better answer (which probably exists).Also, when u press multiple buttons at the same time and u release atleast one it thinks you have realeased all of them.


问:
Is it possible to have permanent variables in python
Ok so I was trying to make a script that would only activate if it was a week after installing and first running it.

My first thought was to make a new environment variable with the activation time, and making the program check if the current time is larger than that, but I found that using os.environ['activation-Time'] = str(time.time() + 604800) does not actually add a new environment variable that can be accessed at a later time.

Is it possible to have a variable that gets saved each time you run the code? Or is it possible to create a new environment variable from within a python script?

答:
I can think of a couple ways to do this, depending on your specific needs.

You can use the python-crontab package to manage cron jobs on your system. I don't know if you are on Windows, Mac OS X, or linux, and don't know if this works on windows. But on a mac or linux, this allows you to set jobs to run on a schedule, and you could decide when you want this script to be run again.

You could write the last (or first?) run-time to a sqlite database, and have a cron job check that at regular intervals, and decide when to run again based on whatever logic you want.

I will say that environment variables are probably not the way to go, unless you write them into your shell .rc file, so that they are re-used by every shell you open. You still need something to try to run your script at a certain time, either manually or via a cron job.

Hope that helps, happy coding!


问:
Write list to 2 different text files
Reading in the data text file,
Running loops to check criteria for valid and invalid student numbers.

Then trying to write 2 text files, one for the invalid student numbers and one for the valid student numbers

This far everything works accept no text files written and no data written to text files at the end

Here is the Script so far

```<code>inputList = []
outputList = []

def FileOpen(myList):
    #try:
        count=0
        INFILE=open("data.txt", "r")
        for line in INFILE:
            myList.append(line.rstrip())
            count+=1
        INFILE.close()
        return count
    #except:
    #    print("File could not be found")
    #    exit()

FileOpen(inputList)
print(FileOpen(inputList),"number of lines read from file")

def AnalyseStudents(rawStudents,totalStudents):
    for entry in rawStudents:

        amountOfDigits = len(entry)
        testOfDigits = entry.isdigit()

        def inValid1(val1,val2):
            answ = val1 != 8 and val2 != True
            return answ

        inValidResult1=(inValid1(amountOfDigits,testOfDigits))

        def Valid1(val1,val2):
            answ = val1 == 8 and val2 == True
            return answ

        validResult1=(Valid1(amountOfDigits,testOfDigits))

        if inValidResult1:
            print(entry, " is an INVALID student number")

        elif validResult1:
            a=entry[0]
            b=entry[1]
            c=entry[2]
            d=entry[3]
            e=entry[4]
            f=entry[5]
            g=entry[6]
            h=entry[7]
            sum = float((a*8)+(b*7)+(c*6)+(d*5)+(e*4)+(f*3)+(g*2)+(h*1))
            result = sum%11

            def inValid2 (val):
                answ = val != 0
                return answ

            inValidResult2=(inValid2(result))

            def Valid2 (val):
                answ = val == 0
                return answ

            validResult2=(Valid2(result))

            if validResult2:
                print(entry, " is an VALID student number")

            elif inValidResult2:
                print(entry, " is an INVALID student number")

        totalStudents

AnalyseStudents(inputList,outputList)

def Write(outList):
    if outList == (" is an VALID student number"):
        OUTFILE1=open("ValidNumbers.txt","w")
        for validResult in outList:
            OUTFILE1.write(validResult+"\n")
        OUTFILE1.close()
    elif outList == (" is an INVALID student number"):
        OUTFILE2=open("InvalidNumbers.txt","w")
        for inValidResults in outList:
            OUTFILE2.write(inValidResults+"\n")
        OUTFILE2.close()

Write(outputList)
print("See output files for more details")
</code>```

答:
Your equality statements are wrong

```<code>  if outList == (" is an VALID student number"):
   ...
  elif outList == (" is an INVALID student number"):
</code>```

The outList is a list but you are comparing it to strings. Put a debug breakpoint at those if statements and decide   what you want.

Title: Write list to 2 different text files

Body:
Reading in the data text file,
Running loops to check criteria for valid and invalid student numbers.

Then trying to write 2 text files, one for the invalid student numbers and one for the valid student numbers

This far everything works accept no text files written and no data written to text files at the end

Here is the Script so far

inputList = []
outputList = []

def FileOpen(myList):
    #try:
        count=0
        INFILE=open("data.txt", "r")
        for line in INFILE:
            myList.append(line.rstrip())
            count+=1
        INFILE.close()
        return count
    #except:
    #    print("File could not be found")
    #    exit()

FileOpen(inputList)
print(FileOpen(inputList),"number of lines read from file")

def AnalyseStudents(rawStudents,totalStudents):
    for entry in rawStudents:

        amountOfDigits = len(entry)
        testOfDigits = entry.isdigit()

        def inValid1(val1,val2):
            answ = val1 != 8 and val2 != True
            return answ

        inValidResult1=(inValid1(amountOfDigits,testOfDigits))

        def Valid1(val1,val2):
            answ = val1 == 8 and val2 == True
            return answ

        validResult1=(Valid1(amountOfDigits,testOfDigits))

        if inValidResult1:
            print(entry, " is an INVALID student number")

        elif validResult1:
            a=entry[0]
            b=entry[1]
            c=entry[2]
            d=entry[3]
            e=entry[4]
            f=entry[5]
            g=entry[6]
            h=entry[7]
            sum = float((a*8)+(b*7)+(c*6)+(d*5)+(e*4)+(f*3)+(g*2)+(h*1))
            result = sum%11

            def inValid2 (val):
                answ = val != 0
                return answ

            inValidResult2=(inValid2(result))

            def Valid2 (val):
                answ = val == 0
                return answ

            validResult2=(Valid2(result))

            if validResult2:
                print(entry, " is an VALID student number")

            elif inValidResult2:
                print(entry, " is an INVALID student number")

        totalStudents

AnalyseStudents(inputList,outputList)

def Write(outList):
    if outList == (" is an VALID student number"):
        OUTFILE1=open("ValidNumbers.txt","w")
        for validResult in outList:
            OUTFILE1.write(validResult+"\n")
        OUTFILE1.close()
    elif outList == (" is an INVALID student number"):
        OUTFILE2=open("InvalidNumbers.txt","w")
        for inValidResults in outList:
            OUTFILE2.write(inValidResults+"\n")
        OUTFILE2.close()

Write(outputList)
print("See output files for more details")

Body:
Your equality statements are wrong

  if outList == (" is an VALID student number"):
   ...
  elif outList == (" is an INVALID student number"):

The outList is a list but you are comparing it to strings. Put a debug breakpoint at those if statements and decide   what you want.


问:
Merge NodeJS project with .NET project in VisualStudio
I have a .NET WebAPI web application which I develop in VisualStudio.

I also have a NodeJS project for running UI tests (on this website) with Cypress, which I develop in Webstorm/VSCode.

I want to merge them to one project, so it will be more comfortable handling code and versions (git, deployments) in one place (VisualStudio, I guess).

How can I do that? How can I merge them + how can I ran them after that?

答:
OK, after some digging I found it.

I needed to update my VisualStudio to support nodeJS projects (with visual studio installer).

In my solution I created a new blank NodeJS Web Application project (right click on the solution > add new project > choose the right type).

I copied there all my files from the second project - without the node modules directory.

On the new project > npm > right click > install the npm packages.
(Also you can read here)

My package json had this code:

```<code>"scripts": {
    "cy:open": "cypress open",
    "cy:run": "cypress run"
  },
</code>```

...so I run CMD in my project folder > npm run cy:open
(There might be some easier ways, but some of them made my Chrome crush so I used this way)

Body:
OK, after some digging I found it.

I needed to update my VisualStudio to support nodeJS projects (with visual studio installer).

In my solution I created a new blank NodeJS Web Application project (right click on the solution > add new project > choose the right type).

I copied there all my files from the second project - without the node modules directory.

On the new project > npm > right click > install the npm packages.
(Also you can read here)

My package json had this code:

"scripts": {
    "cy:open": "cypress open",
    "cy:run": "cypress run"
  },

...so I run CMD in my project folder > npm run cy:open
(There might be some easier ways, but some of them made my Chrome crush so I used this way)


问:
Is there a way querying alias and partition together?
I want to querying like

select enp.LAST_NAME from EMPLOYEES enp partition("P20120101");

When I try It oracle says;

```<code>> ORA-00924: missing BY keyword
</code>```

Is there a way to use alias and partition together?

答:
The correct syntax is

FROM <TABLE_NAME> PARTITION(<PARTITION_NAME>) <ALIAS_NAME>

So,
try select enp.LAST_NAME from EMPLOYEES partition("P20120101") enp;

Body:
I want to querying like

select enp.LAST_NAME from EMPLOYEES enp partition("P20120101");

When I try It oracle says;

> ORA-00924: missing BY keyword

Is there a way to use alias and partition together?


问:
How I can open the "ExpandableListView" on new Activity when click on ImageView
I've created ExpandableListView that is shown first when you run the app.

But now I have created another activity with ImageView to be the main page of the app. I don't want the ExpandableListView to be the first shown -  only to show after click on the ImageView. How I can do that?

Here is the code.

```<code>public class MainActivity extends AppCompatActivity {

    ExpandableListViewAdapter listViewAdapter;
    ExpandableListView expandableListView;
    List<String> chapterList;
    HashMap<String, List<String>> topicList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        expandableListView = findViewById(R.id.eListView);
        showList();
        listViewAdapter = new ExpandableListViewAdapter(this, chapterList, topicList);
        expandableListView.setAdapter(listViewAdapter);

    }

    private void showList() {

        chapterList = new ArrayList<String>();
        topicList =   new HashMap<String, List<String>>();

        chapterList.add("Chapter 1");
        chapterList.add("Chapter 2");
        chapterList.add("Chapter 3");
        chapterList.add("Chapter 4");
        chapterList.add("Chapter 5");

        List<String> topic1 = new ArrayList<>();
        topic1.add("Topic 1");
        topic1.add("Topic 2");
        topic1.add("Topic 3");

        List<String> topic2 = new ArrayList<>();
        topic2.add("Topic 1");
        topic2.add("Topic 2");
        topic2.add("Topic 3");

        List<String> topic3 = new ArrayList<>();
        topic3.add("Topic 1");
        topic3.add("Topic 2");
        topic3.add("Topic 3");

        List<String> topic4 = new ArrayList<>();
        topic4.add("Topic 1");
        topic4.add("Topic 2");
        topic4.add("Topic 3");

        List<String> topic5 = new ArrayList<>();
        topic5.add("Topic 1");
        topic5.add("Topic 2");
        topic5.add("Topic 3");

        topicList.put(chapterList.get(0),topic1);
        topicList.put(chapterList.get(1),topic2);
        topicList.put(chapterList.get(2),topic3);
        topicList.put(chapterList.get(3),topic4);
        topicList.put(chapterList.get(4),topic5);

    }
}
</code>```

答:
You need to remove showList() from the onCreate-Method. Instead, find your ImageView by id using ImageView yourImageView = findViewById(R.id.your_image_view). And then add an OnClickListener to yourImageView that calls the showList()-method like so:

```<code>yourImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showList();
        }
    });
</code>```

Body:
I've created ExpandableListView that is shown first when you run the app.

But now I have created another activity with ImageView to be the main page of the app. I don't want the ExpandableListView to be the first shown -  only to show after click on the ImageView. How I can do that?

Here is the code.

public class MainActivity extends AppCompatActivity {

    ExpandableListViewAdapter listViewAdapter;
    ExpandableListView expandableListView;
    List<String> chapterList;
    HashMap<String, List<String>> topicList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        expandableListView = findViewById(R.id.eListView);
        showList();
        listViewAdapter = new ExpandableListViewAdapter(this, chapterList, topicList);
        expandableListView.setAdapter(listViewAdapter);

    }

    private void showList() {

        chapterList = new ArrayList<String>();
        topicList =   new HashMap<String, List<String>>();

        chapterList.add("Chapter 1");
        chapterList.add("Chapter 2");
        chapterList.add("Chapter 3");
        chapterList.add("Chapter 4");
        chapterList.add("Chapter 5");

        List<String> topic1 = new ArrayList<>();
        topic1.add("Topic 1");
        topic1.add("Topic 2");
        topic1.add("Topic 3");

        List<String> topic2 = new ArrayList<>();
        topic2.add("Topic 1");
        topic2.add("Topic 2");
        topic2.add("Topic 3");

        List<String> topic3 = new ArrayList<>();
        topic3.add("Topic 1");
        topic3.add("Topic 2");
        topic3.add("Topic 3");

        List<String> topic4 = new ArrayList<>();
        topic4.add("Topic 1");
        topic4.add("Topic 2");
        topic4.add("Topic 3");

        List<String> topic5 = new ArrayList<>();
        topic5.add("Topic 1");
        topic5.add("Topic 2");
        topic5.add("Topic 3");

        topicList.put(chapterList.get(0),topic1);
        topicList.put(chapterList.get(1),topic2);
        topicList.put(chapterList.get(2),topic3);
        topicList.put(chapterList.get(3),topic4);
        topicList.put(chapterList.get(4),topic5);

    }
}

Body:
You need to remove showList() from the onCreate-Method. Instead, find your ImageView by id using ImageView yourImageView = findViewById(R.id.your_image_view). And then add an OnClickListener to yourImageView that calls the showList()-method like so:

yourImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showList();
        }
    });


问:
IExtensibleDataObject vs IExtensibleObject?
I am trying to figure out what is the difference between IExtensibleDataObject and IExtensibleObject.

MSDN say that the first one (IExtensibleDataObject) is to let the deserialization of object that may have added attribute and the second one (IExtensibleObject) look very similar, it does let the object add attribute too.

I am confused.

答:
IExtensibleDataObject is about serialization, and it can be used outside of WCF's service stack. Its main purpose is round-tripping different versions of a data contract without losing information. For example, on the first version of your contract, you have this type:

```<code>[DataContract(Name = "Person")]
public class Person : IExtensibleDataObject {
   ExtensionDataObject IExtensibleDataObject.ExtensionData { get; set; }
   [DataMember(Order = 0)] public string Name;
   [DataMember(Order = 1)] public int Age;
}
</code>```

You deploy your services with this data type, and you have some clients using this type. Some service operations return a Person to the client, and the client can send those objects back to the service, as in the example below.

```<code>[ServiceContract]
public interface ITest {
    [OperationContract] Person[] GetAllPeople();
    [OperationContract] void DoSomething(Person person);
}
</code>```

It all works great, until a change in the business logic requires that a new member to be added to Person, and a backing database requires that field to be present (not null).

```<code>[DataContract(Name = "Person")]
public class Person_V2 : IExtensibleDataObject {
   ExtensionDataObject IExtensibleDataObject.ExtensionData { get; set; }
   [DataMember(Order = 0)] public string Name;
   [DataMember(Order = 1)] public int Age;
   [DataMember(Order = 2)] public string Address;
}
</code>```

Without IExtensibleDataObject, the existing clients would receive the Person object, fill its Name / Age property and promptly discard the Address element passed to it. And when it called the DoSomething method with that object, it would pass an instance which would be invalid at the server (Address would be null).

What IEDO does is enable this scenario, where existing (legacy) clients can continue receiving new versions of data contracts from the service - the client will fill the fields it understands with the data from the service, and those elements which it doesn't understand will be stored in the ExtensionDataObject so that they can be reserialized later. In the example above, the legacy clients will only be able to read the Name and Age properties of the Person, but when it sends the object back to the server, the serialized data will contain all three properties.

That was a long story about IEDO. IExtensibleObject does not have anything to do with serialization - is about hooking up extensions to some pre-defined objects in the WCF service stack (the host, the operation context, the instance context and the context channel). Not as interesting as IEDO, so I'll stop for here :)

Edited: for completeness sake, if you want more information about IExtensibleObject, you can check the post at http://blogs.msdn.com/b/carlosfigueira/archive/2012/01/31/wcf-extensibility-iextension-and-iextensibleobject.aspx.

Body:
IExtensibleDataObject is about serialization, and it can be used outside of WCF's service stack. Its main purpose is round-tripping different versions of a data contract without losing information. For example, on the first version of your contract, you have this type:

[DataContract(Name = "Person")]
public class Person : IExtensibleDataObject {
   ExtensionDataObject IExtensibleDataObject.ExtensionData { get; set; }
   [DataMember(Order = 0)] public string Name;
   [DataMember(Order = 1)] public int Age;
}

You deploy your services with this data type, and you have some clients using this type. Some service operations return a Person to the client, and the client can send those objects back to the service, as in the example below.

[ServiceContract]
public interface ITest {
    [OperationContract] Person[] GetAllPeople();
    [OperationContract] void DoSomething(Person person);
}

It all works great, until a change in the business logic requires that a new member to be added to Person, and a backing database requires that field to be present (not null).

[DataContract(Name = "Person")]
public class Person_V2 : IExtensibleDataObject {
   ExtensionDataObject IExtensibleDataObject.ExtensionData { get; set; }
   [DataMember(Order = 0)] public string Name;
   [DataMember(Order = 1)] public int Age;
   [DataMember(Order = 2)] public string Address;
}

Without IExtensibleDataObject, the existing clients would receive the Person object, fill its Name / Age property and promptly discard the Address element passed to it. And when it called the DoSomething method with that object, it would pass an instance which would be invalid at the server (Address would be null).

What IEDO does is enable this scenario, where existing (legacy) clients can continue receiving new versions of data contracts from the service - the client will fill the fields it understands with the data from the service, and those elements which it doesn't understand will be stored in the ExtensionDataObject so that they can be reserialized later. In the example above, the legacy clients will only be able to read the Name and Age properties of the Person, but when it sends the object back to the server, the serialized data will contain all three properties.

That was a long story about IEDO. IExtensibleObject does not have anything to do with serialization - is about hooking up extensions to some pre-defined objects in the WCF service stack (the host, the operation context, the instance context and the context channel). Not as interesting as IEDO, so I'll stop for here :)

Edited: for completeness sake, if you want more information about IExtensibleObject, you can check the post at http://blogs.msdn.com/b/carlosfigueira/archive/2012/01/31/wcf-extensibility-iextension-and-iextensibleobject.aspx.


问:
Location of ~./mavenrc
I was setting up maven on OS X machine when I encountered the error :

```<code>JAVA_HOME should point to a JDK not a JRE.
</code>```

On changing the JAVA_HOME variable to /Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home and updating the PATH  variable it still didn't work.

Turns out, JAVA_HOME reads from ~.mavenrc and not bash_profile.

So we have to update the JAVA_HOME in ~.mavenrc. But how do I know the location of the same?

答: The ~ indicates the $HOME directory, so it should be there. The dot behind the file name indicates it's a hidden file, you have to activate View > Show Hidden Files to see it.

Title: Location of ~./mavenrc

Body:
I was setting up maven on OS X machine when I encountered the error :

JAVA_HOME should point to a JDK not a JRE.

On changing the JAVA_HOME variable to /Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home and updating the PATH  variable it still didn't work.

Turns out, JAVA_HOME reads from ~.mavenrc and not bash_profile.

So we have to update the JAVA_HOME in ~.mavenrc. But how do I know the location of the same?


问:
Custom Leaflet map in MediaWiki
so i build a custom Leaflet map and I would like to integrate it into my Wiki. I tried both the Kartographer and the Maps extension, but for both I can't find how to feed them the url of my map.
Is this even possible?
If there is such an option in either of these extensions or another extension I have overlooked please let me know.</p>

答:
It is possible now (May 2020) with the Maps extension

So you can add this to a wiki page

```<code>{{#display_map:
| image layers=mymap.jpg
| geojson=MyMap
}}
</code>```

Then create a page in the GeoJson namespace called GeoJson:MyMap to match the param you passed to display_map

Now the map has editable GeoJson data in the wiki and on the GeoJson: namespace page

Now you have a map with GeoJson data that you can add for markers etc

Not all of leaflet's options are available as of yet in mediawiki Maps extension - but a few are - they can be seen by adding the following to a page:

```<code>{{#mapsdoc:leaflet|parameters=all}}
</code>```

Finally there is the maps documentation Maps for MediaWiki Docs

Title: Custom Leaflet map in MediaWiki

Body:
It is possible now (May 2020) with the Maps extension

So you can add this to a wiki page

{{#display_map:
| image layers=mymap.jpg
| geojson=MyMap
}}

Then create a page in the GeoJson namespace called GeoJson:MyMap to match the param you passed to display_map

Now the map has editable GeoJson data in the wiki and on the GeoJson: namespace page

Now you have a map with GeoJson data that you can add for markers etc

Not all of leaflet's options are available as of yet in mediawiki Maps extension - but a few are - they can be seen by adding the following to a page:

{{#mapsdoc:leaflet|parameters=all}}

Finally there is the maps documentation Maps for MediaWiki Docs


问:
Replacing window.setTimeout
Guys,
   I'm thinking of replacing window.setTimeout with a function of my own (for example we could have a generic error handler for exceptions thrown in callbacks).

The code will be along these lines:

```<code>var nativeSetTimeout = window.setTimeout;
window.setTimeout = function(fn, interval){
    nativeSetTimeout(function(){
            try{
               fn();
            }catch(e){
                // handle errors coming from the execution of fn
            }
        }, interval);
}
</code>```

Given that my app will stay in a single iframe, is there any outstanding issue that I should be concerned about?

答: You could do it that way, but unless you're deliberately trying to intercept the behaviour of existing code or third party libraries, it would be clearer to just write a wrapper with an alternative name, E.g. function setSafeTimeout(fn, timeout) { ... ; return setTimeout(fn, timeout);}.

Title: Replacing window.setTimeout

Body:
Guys,
   I'm thinking of replacing window.setTimeout with a function of my own (for example we could have a generic error handler for exceptions thrown in callbacks).

The code will be along these lines:

var nativeSetTimeout = window.setTimeout;
window.setTimeout = function(fn, interval){
    nativeSetTimeout(function(){
            try{
               fn();
            }catch(e){
                // handle errors coming from the execution of fn
            }
        }, interval);
}

Given that my app will stay in a single iframe, is there any outstanding issue that I should be concerned about?


问:
creating a display popup message in jquery if both the values are same in two input filed
How can i create in j query or java script if both the input values are same display popup message (That both the values are same) bootstrap please show with example.</p>

答:
You can do like this in html:

```<code><input class="text" id="text1" type="text">
<input class="text" id="text2" type="text">
</code>```

And using jQuery:

```<code>$("input.text").on('change paste input', function(){
      if($("#text1").val()==$("#text2").val()){
        alert("Equal");
      }
});

</code>```

Body:
You can do like this in html:

<input class="text" id="text1" type="text">
<input class="text" id="text2" type="text">

And using jQuery:

$("input.text").on('change paste input', function(){
      if($("#text1").val()==$("#text2").val()){
        alert("Equal");
      }
});


问:
Is it possible to set a button width to match parent in kotlin?
Im working with a button in kotlin, for example i have this code:

```<code>val listHorizontal =  LinearLayout(this);
listHorizontal.setOrientation(LinearLayout.HORIZONTAL)
val button1 = Button(this)
button1.text= "horario"
val button2 = Button (this)
button2.width = 100
listHorizontal.addView(boton1)
listHorizontal.addView(boton2)
</code>```

So i want to set button2 to its width at Match_Parent.

答:
For example if button2 is a in LinearLayout:

```<code>val params = button2?.layoutParams as LinearLayout.LayoutParams
params.width = LinearLayout.LayoutParams.MATCH_PARENT
params.height = LinearLayout.LayoutParams.MATCH_PARENT
button2?.layoutParams = params
</code>```

or shortly:

```<code>button2.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.MATCH_PARENT)
</code>```

Body:
Im working with a button in kotlin, for example i have this code:

val listHorizontal =  LinearLayout(this);
listHorizontal.setOrientation(LinearLayout.HORIZONTAL)
val button1 = Button(this)
button1.text= "horario"
val button2 = Button (this)
button2.width = 100
listHorizontal.addView(boton1)
listHorizontal.addView(boton2)

So i want to set button2 to its width at Match_Parent.

Body:
For example if button2 is a in LinearLayout:

val params = button2?.layoutParams as LinearLayout.LayoutParams
params.width = LinearLayout.LayoutParams.MATCH_PARENT
params.height = LinearLayout.LayoutParams.MATCH_PARENT
button2?.layoutParams = params

or shortly:

button2.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.MATCH_PARENT)


问:
Application Load Balancer https request to EC2 nodejs running on port 4000
I have an Application Load Balancer that is in HTTPS and will make a request to my EC2 instance. I have configured the ALB listeners to HTTP/HTTPS and then I have specified the target group (for the application load balancer) as the EC2 instance.

On this EC2 instance, I have two things running: 1) A website 2) A nodejs service (on port 4000)

In the target group I have specified the relevant EC2 instance twice. (once with port number 80 and another with port number 4000). On port 4000, the health check seems to be failing (even though the service is running on port 4000 only).

When I make the htttps request to my website, the response is fine. However, when I make the https request to my nodejs service (running on port number 4000), it is giving connection refused error.

答:
A target group should only be forwarding to one application. So you would want a separate target group for your web site and your node js service. Then using ALB use advanced routing to determine which to load.

An example of above would be:

Path of /api/* forwards to node js target group

Default forwards to website.

Secondly your health check must pass on your node js app, its currently returning a 404 indicating that the path you are host checking against is not available.

Finally make sure you connect based on the listener configuration (http/https and port), not the port from the target group.


问:
Overriding an Android library project asset file
Based on the following links:

Best practice: Extending or overriding an Android library project class

https://developer.android.com/studio/write/add-resources.html#resource_merging

classes and resources in the Android library (AAR) are override-able. How about overriding an asset file? In my AAR file, I have an asset named first.xml. I want to create my own first.xml in my android project that overrides the file in my AAR. How do I do it?

答:
Here is the result of my test.

This is my assets/ inside the AAR:

```<code>-assets/
 -a.xml
 -b.xml
</code>```

This is my assets/ inside my android project that depends on the AAR above:

```<code>-assets/
 -b.xml
 -c.xml
</code>```

The resulting assets/ in my APK is below:

```<code>-assets/
 -a.xml (from AAR)
 -b.xml (from my project)
 -c.xml (from my project)
</code>```

Body:
Here is the result of my test.

This is my assets/ inside the AAR:

-assets/
 -a.xml
 -b.xml

This is my assets/ inside my android project that depends on the AAR above:

-assets/
 -b.xml
 -c.xml

The resulting assets/ in my APK is below:

-assets/
 -a.xml (from AAR)
 -b.xml (from my project)
 -c.xml (from my project)


问:
Snowflake / How get the original caller when a stored procedure is executed as OWNER
I have created a stored procedure with the behavior execute as OWNER (I need the owner’s rights).

I am looking to get the original role of the user that called it, is there any way to do that?
Unfortunately, as expected  the select current_role() statement returns the owner's role ...

If a workaround exists, I would appreciate if you could describe it to me.

Following Mike's advice:there the code I done to test Harsh's solution:

Failed again ^^
There's my code. May be you ll see my mistake.

```<code>create or replace procedure do_noting_proc()
returns string
language javascript
execute as OWNER
AS
$$
 var retour="Resultat";
 try{
   rs0=snowflake.createStatement({sqlText:"SELECT $QUERY_TAG;"}).execute();
   cR=rs0.getColumnValue(1);
   return "QRValue= "+callerRole;
 }catch(err){
    return "do_noting_proc KO: "+ err.message+";";
 }
$$;

create or replace procedure test_proc()
returns string
language javascript
execute as CALLER
AS
$$
var rString="Result -->";
try{
  rs0=snowflake.createStatement({sqlText:"SELECT CURRENT_ROLE();"}).execute();
  rs0.next();
  cr="testQT"+rs0.getColumnValue(1);
  snowflake.createStatement({sqlText:"alter session set QUERY_TAG="+cr+";"}).execute();
  rs=snowflake.createStatement({sqlText:"call  PUBLIC.do_noting_proc();"}).execute();
  rs.next();
  rString+=rs.getColumnValue(1);
}catch(err){
    return "test_proc: "+ err.message+";";
}
return "test_proc : "+rString;
$$;
</code>```

Thencall share_view_or_table();
==>test_proc : ** Result -->do_noting_proc KO: Use of session variable '$QUERY_TAG' is not allowed in owners rights stored procedure;**
(procedure created by sysadmin and Executed as sysadmin)

Also if I run 'code'
   select $QUERY_TAG;

I get the error: SQL compilation error: error line 1 at position 7 Session variable '$QUERY_TAG' does not exist

whereas

```<code>SHOW PARAMETERs LIKE 'QUERY_TAG' IN SESSION ;
</code>```

works fine and print TESTQTSYSADMIN

@Harsh many thanks for your time

答:
When using EXECUTE AS OWNER the rules do not permit reading the caller's session details, including their identity or role:

Owner’s rights stored procedures adhere to the following rules within a session:

[…]

Cannot access most caller-specific information. For example:

Cannot view, set, or unset the caller’s session variables.

Can read only specific session parameters, and cannot set or unset any of the caller’s session parameters.

Cannot query INFORMATION_SCHEMA table functions, such as AUTOMATIC_CLUSTERING_HISTORY, that return results based on the current user.

While inconvenient, you can use logic within the stored procedure to enforce that the role name of the caller should be passed as an argument:

CREATE OR REPLACE PROCEDURE PROC(ROLE_NAME STRING)
[…]
var VALID_ROLES_ARRAY = ["FOO", "BAR"];
var IS_VALID_CALLER_ROLENAME = VALID_ROLES_ARRAY.includes(ROLE_NAME);
[…];

CALL PROC(CURRENT_ROLE());
```

Body:
I have created a stored procedure with the behavior execute as OWNER (I need the owner’s rights).

I am looking to get the original role of the user that called it, is there any way to do that?
Unfortunately, as expected  the select current_role() statement returns the owner's role ...

If a workaround exists, I would appreciate if you could describe it to me.

Following Mike's advice:there the code I done to test Harsh's solution:

Failed again ^^
There's my code. May be you ll see my mistake.

create or replace procedure do_noting_proc()
returns string
language javascript
execute as OWNER
AS
$$
 var retour="Resultat";
 try{
   rs0=snowflake.createStatement({sqlText:"SELECT $QUERY_TAG;"}).execute();
   cR=rs0.getColumnValue(1);
   return "QRValue= "+callerRole;
 }catch(err){
    return "do_noting_proc KO: "+ err.message+";";
 }
$$;

create or replace procedure test_proc()
returns string
language javascript
execute as CALLER
AS
$$
var rString="Result -->";
try{
  rs0=snowflake.createStatement({sqlText:"SELECT CURRENT_ROLE();"}).execute();
  rs0.next();
  cr="testQT"+rs0.getColumnValue(1);
  snowflake.createStatement({sqlText:"alter session set QUERY_TAG="+cr+";"}).execute();
  rs=snowflake.createStatement({sqlText:"call  PUBLIC.do_noting_proc();"}).execute();
  rs.next();
  rString+=rs.getColumnValue(1);
}catch(err){
    return "test_proc: "+ err.message+";";
}
return "test_proc : "+rString;
$$;

Thencall share_view_or_table();
==>test_proc : ** Result -->do_noting_proc KO: Use of session variable '$QUERY_TAG' is not allowed in owners rights stored procedure;**
(procedure created by sysadmin and Executed as sysadmin)

Also if I run 'code'
   select $QUERY_TAG;

I get the error: SQL compilation error: error line 1 at position 7 Session variable '$QUERY_TAG' does not exist

whereas

SHOW PARAMETERs LIKE 'QUERY_TAG' IN SESSION ;

works fine and print TESTQTSYSADMIN

@Harsh many thanks for your time


问:
Laravel SQLSTATE[HY000] [1049] Unknown database 'previous_db_name'
I have this error when i use php artisan migrate in my Laravel project.

```<code>[PDOException]
SQLSTATE[HY000] [1049] Unknown database 'previous_db_name'
</code>```

this is my database.php file :

```<code>'default' => env('DB_CONNECTION', 'mysql'),
'connections' => [

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'current_db_name'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],
],
</code>```

I saw this error in this question and this question but none of them was not helpful.

答:
Please run this command:</p>

```<code>php artisan config:cache
</code>```

Body:
I have this error when i use php artisan migrate in my Laravel project.

[PDOException]
SQLSTATE[HY000] [1049] Unknown database 'previous_db_name'

this is my database.php file :

'default' => env('DB_CONNECTION', 'mysql'),
'connections' => [

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'current_db_name'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],
],

I saw this error in this question and this question but none of them was not helpful.

Body:
Please run this command:

php artisan config:cache


问:
Why does `evalb(((3*x + 1)^5)(3*x - 1)/x^6 = ((3 + 1/x)^5)(3 - 1/x)) assuming (0 < x)` return `false` in Maple?
The question should perhaps be why does (3*x + 1)^5 * (3*x - 1) / x^6 = (3 + 1/x)^5 * (3 - 1/x) evaluate to false in Maple, even with the assumption that x > 0. The same expression evaluates to true in Mathematica and, of course, the statement itself is mathematically true under the previous assumption.

Maple's help pages don't give any clue on why this happens, and I would like someone to explain this behaviour before I think that Maple's evalb() is kind of broken. It is the type of questions I'm asking myself lately, since I'm deciding wether I should learn Maple or rather drop it and focus on learning Mathematica.

Thank you in advance.

答:
If both sides of the equation are of type numeric (or extended complex numeric, etc), then evalb will test the equality. But for your symbolic expressions the evalb command will only test that they are the very same expression (by comparing memory address).

But they are not the very same expression. They are merely two different symbolic expressions for which you wish to do a mathematical test of equivalence.

```<code>restart;

expr:=(3*x+1)^5*(3*x-1)/x^6=(3+1/x)^5*(3-1/x):

is(expr);
                          true

testeq(expr);
                          true

simplify((rhs-lhs)(expr));
                           0
</code>```

Body:
If both sides of the equation are of type numeric (or extended complex numeric, etc), then evalb will test the equality. But for your symbolic expressions the evalb command will only test that they are the very same expression (by comparing memory address).

But they are not the very same expression. They are merely two different symbolic expressions for which you wish to do a mathematical test of equivalence.

restart;

expr:=(3*x+1)^5*(3*x-1)/x^6=(3+1/x)^5*(3-1/x):

is(expr);
                          true

testeq(expr);
                          true

simplify((rhs-lhs)(expr));
                           0


答:
You can find what you seek in this thread. It has done with id and the keyup event listner. Apart from that use jQuery will make that more easier.

$( "#text1" ).bind( "keyup", function() {
  testpassword2();
});
$( "#text2" ).bind( "keyup", function() {
  testpassword2();
});

function testpassword2() {
  var text1 = document.getElementById("text1");
  var text2 = document.getElementById("text2");
  if ($("text1").val() == $("text2").val())
    text2.style.borderColor = "#2EFE2E";
  else
    text2.style.borderColor = "red";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<input type="text" id="text1" size="30">
<input type="text" id="text2" size="30">
</body></code>```

Title: creating a display popup message in jquery if both the values are same in two input filed

Body: How can i create in j query or java script if both the input values are same display popup message (That both the values are same) bootstrap please show with example.

Body:
You can find what you seek in this thread. It has done with id and the keyup event listner. Apart from that use jQuery will make that more easier.

$( "#text1" ).bind( "keyup", function() {
  testpassword2();
});
$( "#text2" ).bind( "keyup", function() {
  testpassword2();
});

function testpassword2() {
  var text1 = document.getElementById("text1");
  var text2 = document.getElementById("text2");
  if ($("text1").val() == $("text2").val())
    text2.style.borderColor = "#2EFE2E";
  else
    text2.style.borderColor = "red";
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<input type="text" id="text1" size="30">
<input type="text" id="text2" size="30">
</body>


问:
js - Higher order unary function - why is this needed?
Here's where it starts: This below snippet doesn't work as expected:

```<code>['1', '2', '3'].map(parseInt)           // [1, NaN, NaN] <- bad output
</code>```

A simple change remedies it:

```<code>['1', '2', '3'].map(a => parseInt(a))   // [ 1, 2, 3 ] <- good output
</code>```

But this book I'm reading has a different remedy:

Create a unary function, which takes in a function (parseInt in our case)  and if the function has n arguments, it returns a new function that has only a single argument. Here's how the book does it:

```<code>const unary = (f) => {
  return f.length === 1 ? f : (args) => f(args)
}

['1', '2', '3'].map(unary(parseInt)) // [ 1, 2, 3 ] <- good output again!
</code>```

My question is:

How is this unary function is working?

Any practical scenario where this function (or at least this idea in general) will find a good use?

Any help would be much appreciated :)

Note to the future reader: Checkout currying

答:
in this unary function, fn.length is checking the arguments length of parseInt,
 if the parseInt have only one arguments then it return the function as usual. but in this scenario,
 we have got 2 arguments in parseInt which is parseInt(value ,radix) so our fn.length === 1 failed.
 if it have 2 arguments then it return the parseInt with one argument which is value only. eg parseInt(value) not parseInt(value, radix)</p>

Body:
Here's where it starts: This below snippet doesn't work as expected:

['1', '2', '3'].map(parseInt)           // [1, NaN, NaN] <- bad output

A simple change remedies it:

['1', '2', '3'].map(a => parseInt(a))   // [ 1, 2, 3 ] <- good output

But this book I'm reading has a different remedy:

Create a unary function, which takes in a function (parseInt in our case)  and if the function has n arguments, it returns a new function that has only a single argument. Here's how the book does it:

const unary = (f) => {
  return f.length === 1 ? f : (args) => f(args)
}

['1', '2', '3'].map(unary(parseInt)) // [ 1, 2, 3 ] <- good output again!

My question is:

How is this unary function is working?

Any practical scenario where this function (or at least this idea in general) will find a good use?

Any help would be much appreciated :)

Note to the future reader: Checkout currying