问:
How can I set the height of an element equal to another element? (Codepen included)
I have two Bootstrap columns with 4 divs (2 in each):

```<code><div class="row">
  <div class="col-8">
    <div class="cell-1">
      Cell 1
    </div>
    <div class="cell-2">
      Cell 2
      <ul>
        <li>Some repeatable text</li>
        <li>Some repeatable text</li>
      </ul>
    </div>
  </div>
  <div class="col-4">
    <div class="cell-3">
      Cell 3
    </div>
    <div class="cell-4" style="overflow-y:auto; max-height:[height of cell-2]">
      Cell 4
      <ul>
        <li>Lots of repeatable text</li>
        <li>Lots of repeatable text</li>
        <li>Lots of repeatable text</li>
        <li>Lots of repeatable text</li>
        <li>Lots of repeatable text</li>
        <li>Lots of repeatable text</li>
      </ul>
    </div>
  </div>
</div>
</code>```

.cell-4 has overflow-y: auto. How can I set the max-height of .cell-4 equal to the dynamic height of .cell-2?

Ideally without Javacript.

Codepen here: link

答:
Use display:flex and align-items: stretch.

```<code>.col-4{
  display: flex;
  align-items: center;
}
</code>```

Body:
I have two Bootstrap columns with 4 divs (2 in each):

      Cell 1

      Cell 2

Some repeatable text

Some repeatable text

      Cell 3

      Cell 4

Lots of repeatable text

Lots of repeatable text

Lots of repeatable text

Lots of repeatable text

Lots of repeatable text

Lots of repeatable text

.cell-4 has overflow-y: auto. How can I set the max-height of .cell-4 equal to the dynamic height of .cell-2?

Ideally without Javacript.

Codepen here: link

Body:
Use display:flex and align-items: stretch.

.col-4{
  display: flex;
  align-items: center;
}


来源: stackexchange

问:
How to search through a DB using a cursor( sqlite query) in android
I am an android beginner. I am trying to design this simple application which takes the name of a city from the user using an editText View , compares that in the database , and returns the ZIP code of that city.
Now ,I'm having a problem with the implementation of cursors. Please help.How can i query the database to fetch the corresponding code.</p>

```<code>        EditText city;
    Button add,show1;
    RadioGroup choose;
    String k;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        try
        {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //final ContentValues values = new ContentValues();
        city=(EditText)findViewById(R.id.editText1);
        add=(Button)findViewById(R.id.add);
        choose=(RadioGroup)findViewById(R.id.radio01);
        show1=(Button)findViewById(R.id.button1);
        k=city.getText().toString();
        createDatabase();
    }
        catch(Exception e)
        {

        }

show1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        db=openOrCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE,null);
        try{

        if(k == "CITY")
        {
            String[] result_columns=new String[]{"_id","CITY","CODE"};
            Cursor cursor = db.query(TABLE_NAME, result_columns,
                    "CITY" +"=?", new String[]{"k"}, null, null, null);

    cursor.moveToFirst();

        String xnewcode=cursor.getString(0);
        Toast.makeText(activity1.this, xnewcode, Toast.LENGTH_LONG).show();
        cursor.moveToNext();

            //db.close();
        }}
        catch(Exception e)
        {
            Toast.makeText(activity1.this,"Fault in showing " + e,Toast.LENGTH_LONG).show();

        }

    }

});
</code>```

答:
I think you forgot to get the result in loop

```<code>String[] result_columns=new String[]{"_id","CITY","CODE"};
        Cursor cursor = db.query(TABLE_NAME, result_columns,
                "CITY" +"=?", new String[]{"k"}, null, null, null);

do {

                        String xnewcode = cursor.getString(0);
                        System.ouot.println("...display the result..."+xnewcode);
                    }while (cursor.moveToNext());
                    }
</code>```

Have a look on Sample project

or

Tutorial on sqlite database for android

Thanks
Deepak

ContentLicense: CC BY-SA 3.0

Body:
I am an android beginner. I am trying to design this simple application which takes the name of a city from the user using an editText View , compares that in the database , and returns the ZIP code of that city.
Now ,I'm having a problem with the implementation of cursors. Please help.How can i query the database to fetch the corresponding code.

        EditText city;
    Button add,show1;
    RadioGroup choose;
    String k;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        try
        {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //final ContentValues values = new ContentValues();
        city=(EditText)findViewById(R.id.editText1);
        add=(Button)findViewById(R.id.add);
        choose=(RadioGroup)findViewById(R.id.radio01);
        show1=(Button)findViewById(R.id.button1);
        k=city.getText().toString();
        createDatabase();
    }
        catch(Exception e)
        {

        }

show1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        db=openOrCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE,null);
        try{

        if(k == "CITY")
        {
            String[] result_columns=new String[]{"_id","CITY","CODE"};
            Cursor cursor = db.query(TABLE_NAME, result_columns,
                    "CITY" +"=?", new String[]{"k"}, null, null, null);

    cursor.moveToFirst();

        String xnewcode=cursor.getString(0);
        Toast.makeText(activity1.this, xnewcode, Toast.LENGTH_LONG).show();
        cursor.moveToNext();

            //db.close();
        }}
        catch(Exception e)
        {
            Toast.makeText(activity1.this,"Fault in showing " + e,Toast.LENGTH_LONG).show();

        }

    }

});

Body:
I think you forgot to get the result in loop

String[] result_columns=new String[]{"_id","CITY","CODE"};
        Cursor cursor = db.query(TABLE_NAME, result_columns,
                "CITY" +"=?", new String[]{"k"}, null, null, null);

do {

                        String xnewcode = cursor.getString(0);
                        System.ouot.println("...display the result..."+xnewcode);
                    }while (cursor.moveToNext());
                    }

Have a look on Sample project

or

Tutorial on sqlite database for android

Thanks
Deepak


问:
Use Session window in Kafka stream to order records and insert into MySQL database
As per the KSQLDB documentation, session window can be used to order the records as per timestamp and do aggregation.
I have an use case where I want to insert records into MySQL in sequence.
I have a timestamp field in my record that I used as ROWTIME and then tried session window over it and inserted into an output stream that will push into a topic and then to RDS. But in the output stream I was not able to reorder the messages as per the timestamp.
Example -
There are two records - Record 1 at 11:00AM and Record 2 at 11:01AM and both of them has same primary keys. These two records are getting ingested in Kafka in sequence - Record 2 , Record 1. But in MYSQL I need Record 1 and then Record 2 as the Record 1 has lower timestamp. I tried window session of 5 minutes in stream. But in output stream, it is always coming as Record 2, Record 1.

Is this scenario possible inside Kafka? Can I reorder the records inside Kafka and then push into a stream using INSERT INTO statement?

Currently I am trying to do using KSQL queries as I am using confluent Kafka.

答:
Session windows do not change the order of records, they GROUP records together that have the same key and are within some time period of each other.

Hence session windows are not going to allow you to reorder messages.

Reordering messages is not a use-case ksqlDB is suited for at present.  You may have better luck if you tried to write a Kafka Streams based application.

Kafka Streams would allow you to use a state-store to buffer input messages for some time to allow for out-of-order messages.  You should be able to use punctuation to trigger outputting of cached messages after some time period. You will need to choose how long you are willing to buffer the input to allow for out-of-order messages.

ContentLicense: CC BY-SA 4.0


问:
Symfony 5 can't use Font Awesome icons
I am trying to import Font Awesome into my Symfony 5 with Webpack Encore project but I can't. I have read all the (most of them) S.O questions, framework tutorials, etc. but none of the icons are being displayed.

Steps I followed:

First attempt:

Compile assets and watch for changes with yarn watch

Install Font Awesome Free: yarn add --dev @fortawesome/fontawesome-free

Import CSS files into app.css file (assets/css/app.css):

@import '~@fortawesome/fontawesome-free/css/fontawesome.css';
@import '~@fortawesome/fontawesome-free/css/regular.css';
@import '~@fortawesome/fontawesome-free/css/solid.css';
@import '~@fortawesome/fontawesome-free/css/brands.css';
```

<ol start="4">
<li>Add the icon to the TWIG template: <code><i class="fas fa-star"></i></code> ( I also tried to prepend the icon with <code>fa fa-star</code>, according to Font Awesome documentation.</li>
</ol>

<h3>Second attempt:</h3>

<ol>
<li>Compile assets and watch for changes with <code>yarn watch</code></li>
<li>Install Font Awesome Free: <code>yarn add --dev @fortawesome/fontawesome-free</code></li>
<li>Import CSS / JS files into <code>app.js</code> file (<code>assets/js/app.js</code>):</li>
</ol>

<pre class="lang-js prettyprint-override"><code>import '~@fortawesome/fontawesome-free/css/all.min.css';
import '~@fortawesome/fontawesome-free/js/all.js';
</code>```

Import Solid Font Awesome icons into CSS file (assets/css/app.css) (and also in JS file):

@import '~@fortawesome/fontawesome-free/css/solid.css';
```

<ol start="5">
<li>Add the icon to the TWIG template: <code><i class="fas fa-star"></i></code></li>
</ol>

<p>I also have tried using CSS  unicode:</p>

<pre class="lang-css prettyprint-override"><code>element {
    content: "\f005"
}
</code>```

None of them displays any icon, or any console error, warning, message, or anything, but I get an empty icon every time. Any clues?

答:
Your first attempt is the right way, you just missed setting the $fa-font-path correctly.

```<code>$fa-font-path: '~@fortawesome/fontawesome-free/webfonts';
@import '~@fortawesome/fontawesome-free/scss/fontawesome';
@import '~@fortawesome/fontawesome-free/scss/solid';
@import '~@fortawesome/fontawesome-free/scss/regular';
@import '~@fortawesome/fontawesome-free/scss/brands';
</code>```

Title: Symfony 5 can't use Font Awesome icons

Body:
I am trying to import Font Awesome into my Symfony 5 with Webpack Encore project but I can't. I have read all the (most of them) S.O questions, framework tutorials, etc. but none of the icons are being displayed.

Steps I followed:

First attempt:

Compile assets and watch for changes with yarn watch

Install Font Awesome Free: yarn add --dev @fortawesome/fontawesome-free

Import CSS files into app.css file (assets/css/app.css):

@import '~@fortawesome/fontawesome-free/css/fontawesome.css';
@import '~@fortawesome/fontawesome-free/css/regular.css';
@import '~@fortawesome/fontawesome-free/css/solid.css';
@import '~@fortawesome/fontawesome-free/css/brands.css';

Add the icon to the TWIG template:  ( I also tried to prepend the icon with fa fa-star, according to Font Awesome documentation.

Second attempt:

Compile assets and watch for changes with yarn watch

Install Font Awesome Free: yarn add --dev @fortawesome/fontawesome-free

Import CSS / JS files into app.js file (assets/js/app.js):

import '~@fortawesome/fontawesome-free/css/all.min.css';
import '~@fortawesome/fontawesome-free/js/all.js';

Import Solid Font Awesome icons into CSS file (assets/css/app.css) (and also in JS file):

@import '~@fortawesome/fontawesome-free/css/solid.css';

Add the icon to the TWIG template:

I also have tried using CSS  unicode:

element {
    content: "\f005"
}

None of them displays any icon, or any console error, warning, message, or anything, but I get an empty icon every time. Any clues?

Body:
Your first attempt is the right way, you just missed setting the $fa-font-path correctly.

$fa-font-path: '~@fortawesome/fontawesome-free/webfonts';
@import '~@fortawesome/fontawesome-free/scss/fontawesome';
@import '~@fortawesome/fontawesome-free/scss/solid';
@import '~@fortawesome/fontawesome-free/scss/regular';
@import '~@fortawesome/fontawesome-free/scss/brands';


问:
How to check particular file is exist in our cellphone's "Download" Directory
I have created one android app in which I have provided features of download attachment and I want to change the text of the download button from Download to View once the file is downloaded or already present in the Downloads directory of my mobile. For this, I need code in Kotlin to check whether a particular file is present in the Download directory or not.

答:
At first check the manifest permissions is important and then accept them in the app.

Manifest

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

MainActivity

```<code>class MenuActivity : AppCompatActivity(){

   internal var isExist: Boolean? = false
   internal var file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)

@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val filesInSideOfDownloadDirectory = Arrays.asList(*file.list()!!) //this code puts file names in the download directory to the list
        for (i in filesInSideOfDownloadDirectory.indices) {
            if (filesInSideOfDownloadDirectory[i] == "YOUR_FILE_NAME") {
                isExist = true
            } else {
                isExist = false
            }
        }

        if (isExist!!) {
            Toast.makeText(this@MenuActivity, "The File Is Exist", Toast.LENGTH_LONG).show()
        } else {
            Toast.makeText(this@MenuActivity, "The File Is Not Exist", Toast.LENGTH_LONG).show()
        }
</code>```

Body:
At first check the manifest permissions is important and then accept them in the app.

Manifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

MainActivity

class MenuActivity : AppCompatActivity(){

   internal var isExist: Boolean? = false
   internal var file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)

@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val filesInSideOfDownloadDirectory = Arrays.asList(*file.list()!!) //this code puts file names in the download directory to the list
        for (i in filesInSideOfDownloadDirectory.indices) {
            if (filesInSideOfDownloadDirectory[i] == "YOUR_FILE_NAME") {
                isExist = true
            } else {
                isExist = false
            }
        }

        if (isExist!!) {
            Toast.makeText(this@MenuActivity, "The File Is Exist", Toast.LENGTH_LONG).show()
        } else {
            Toast.makeText(this@MenuActivity, "The File Is Not Exist", Toast.LENGTH_LONG).show()
        }


问:
How do I cut substrings in these strings in powershell?
everyone. I'm a rookie at Powershell and I don't know much about the values in a particular column.

```<code>JOBID    STATUS       STORAGE POLICY        APPTYPE          BACKUPSET           SUBCLIENT                              INSTANCE                CLIENT

-----    ------       --------------        -------          ---------           ---------                              --------                ------

647      Completed    SP_Dedupe Files       File System      defaultBackupSet    ClienteDDB                             <default>               WIN-U0O9K2LMAF1

641      Completed    SP_Dedupe Files       File System      defaultBackupSet    DDBBackup                              <default>               WIN-U0O9K2LMAF1
</code>```

I filter the lines with a Select-String by jobid for example but I need the value of subclient column in particular.
As it is not a cmdlet I can't split by properties, so how do I do it with a regular expression?and which one?

答:
The best solution will be to output the data in a format that is more PowerShell ready. An XML or CSV format would be ideal as PowerShell can convert those formats into objects.

You can use a -match and -split combination here assuming your data is in file.txt:

```<code>$jobid = 641
$values = (Get-Content file.txt) -match "^$jobid\s+" -split '\s{2,}'
$values[5] # SUBCLIENT value
$values[7] # CLIENT value
</code>```

Since your text file will invariably have more than one line of text, you can read the file with Get-Content and match against your jobid number. The -match comparison operator will return only the line that matches the jobid. It behaves this way because Get-Content without the -Raw switch reads each line into an array index.

The match regex string "^$jobid\s+" is enclosed in double quotes so that the variable $jobid expands. Single quotes will prevent expansion and use the verbatim string. ^ matches the start of the string. \s+ matches one or more consecutive spaces.

-split uses regex matching and then splits the single string into an array based on that match. \s{2,} matches two or more consecutive spaces. The split array is stored in $values. Now, you can reference whichever column number (starting with 0) using syntax $value[number].

Note that this solution still has potential issues if any of your columns are only one space apart. It will be difficult to code around that situation. You'd have to include conditions where you explicitly list potential values for each column in your code. The alternative is to stop using spaces in your values or use values that clearly indicate when a new column is starting.

AVshalom's solution points you in a very good direction if reading raw strings. Working with a CSV is superior to text matching in this case. However, the solution has flaws and misaligns your data. The flaws are easily correctable though. \s{2,} should be used in favor of \s+ (one or more consecutive spaces) because values that contain spaces will also be replaced. You can see this behavior since the output has more columns than the original file. We can take this solution further using conditional logic.

```<code># If values have commas, you will need a different delimiter
$jobid = 641
$csv = (Get-Content file.txt) -replace '\s{2,}',',' | ConvertFrom-Csv
$csv | Where JOBID -eq $jobid | Select-Object -Expand SUBCLIENT
</code>```

Where or Where-Object uses a condition (checking JOBID here) used to retrieve the correct line. Then you can pipe to Select or Select-Object to retrieve the SUBCLIENT value. Using -Expand only prints the value of the property. Leaving off -Expand will print an object containing the SUBCLIENT property.

Body:
everyone. I'm a rookie at Powershell and I don't know much about the values in a particular column.

JOBID    STATUS       STORAGE POLICY        APPTYPE          BACKUPSET           SUBCLIENT                              INSTANCE                CLIENT

-----    ------       --------------        -------          ---------           ---------                              --------                ------

647      Completed    SP_Dedupe Files       File System      defaultBackupSet    ClienteDDB                             <default>               WIN-U0O9K2LMAF1

641      Completed    SP_Dedupe Files       File System      defaultBackupSet    DDBBackup                              <default>               WIN-U0O9K2LMAF1

I filter the lines with a Select-String by jobid for example but I need the value of subclient column in particular.
As it is not a cmdlet I can't split by properties, so how do I do it with a regular expression?and which one?

Body:
The best solution will be to output the data in a format that is more PowerShell ready. An XML or CSV format would be ideal as PowerShell can convert those formats into objects.

You can use a -match and -split combination here assuming your data is in file.txt:

$jobid = 641
$values = (Get-Content file.txt) -match "^$jobid\s+" -split '\s{2,}'
$values[5] # SUBCLIENT value
$values[7] # CLIENT value

Since your text file will invariably have more than one line of text, you can read the file with Get-Content and match against your jobid number. The -match comparison operator will return only the line that matches the jobid. It behaves this way because Get-Content without the -Raw switch reads each line into an array index.

The match regex string "^$jobid\s+" is enclosed in double quotes so that the variable $jobid expands. Single quotes will prevent expansion and use the verbatim string. ^ matches the start of the string. \s+ matches one or more consecutive spaces.

-split uses regex matching and then splits the single string into an array based on that match. \s{2,} matches two or more consecutive spaces. The split array is stored in $values. Now, you can reference whichever column number (starting with 0) using syntax $value[number].

Note that this solution still has potential issues if any of your columns are only one space apart. It will be difficult to code around that situation. You'd have to include conditions where you explicitly list potential values for each column in your code. The alternative is to stop using spaces in your values or use values that clearly indicate when a new column is starting.

AVshalom's solution points you in a very good direction if reading raw strings. Working with a CSV is superior to text matching in this case. However, the solution has flaws and misaligns your data. The flaws are easily correctable though. \s{2,} should be used in favor of \s+ (one or more consecutive spaces) because values that contain spaces will also be replaced. You can see this behavior since the output has more columns than the original file. We can take this solution further using conditional logic.

# If values have commas, you will need a different delimiter
$jobid = 641
$csv = (Get-Content file.txt) -replace '\s{2,}',',' | ConvertFrom-Csv
$csv | Where JOBID -eq $jobid | Select-Object -Expand SUBCLIENT

Where or Where-Object uses a condition (checking JOBID here) used to retrieve the correct line. Then you can pipe to Select or Select-Object to retrieve the SUBCLIENT value. Using -Expand only prints the value of the property. Leaving off -Expand will print an object containing the SUBCLIENT property.


问:
Generate 3x3 puzzles with the same difficulty?
I want to generate several 3x3 puzzles (https://datawookie.netlify.app/blog/2019/04/sliding-puzzle-solvable/) with the same difficulty where difficulty is defined as the minimum necessary moves to reach the solution. For example, in a puzzle [1,2,3,4,5,6,7,0,8], the minimum necessary move is 1 because we can reach the solution by moving 8 up.

The above site has a python code to determine solvability, and I modified it a little bit so that it gives me the number of inversions:

```<code>def solvable(tiles):
    count = 0
    for i in range(8):
        for j in range(i+1, 9):
            if tiles[j] and tiles[i] and tiles[i] > tiles[j]:
                count += 1
    return [count, count % 2 == 0]
</code>```

But the number of inversions is not the minimum necessary moves. How could I modify the code so that it also returns the minimum necessary moves? And, is there any way to automatically generate puzzles with the same minimum necessary moves?

答:
You have 3 general approaches:

1 - If the number of puzzles to create is limited, you can generate a puzzle, and solve it to obtain the exact minimum number of moves - you then use that to classify the puzzles per level of difficulty.

2- From a solved position, you can scramble a puzzle by randomly sliding tiles - this will give you an estimate of the difficulty; some moves may cancel previous ones, so the number of moves will be capping.

2-bis) A more sophisticated scrambler will prevent repeated states, and give you a more exact path length as in (1) - You will still have some puzzle classified as hard (long path) when they are in fact easy, when there exist a more efficient shortcut in the random path.

3 - as was mentioned in other answers, you can find metrics that estimate the number of moves required, but this may not be easy to get a good estimate.

Body:
I want to generate several 3x3 puzzles (https://datawookie.netlify.app/blog/2019/04/sliding-puzzle-solvable/) with the same difficulty where difficulty is defined as the minimum necessary moves to reach the solution. For example, in a puzzle [1,2,3,4,5,6,7,0,8], the minimum necessary move is 1 because we can reach the solution by moving 8 up.

The above site has a python code to determine solvability, and I modified it a little bit so that it gives me the number of inversions:

def solvable(tiles):
    count = 0
    for i in range(8):
        for j in range(i+1, 9):
            if tiles[j] and tiles[i] and tiles[i] > tiles[j]:
                count += 1
    return [count, count % 2 == 0]

But the number of inversions is not the minimum necessary moves. How could I modify the code so that it also returns the minimum necessary moves? And, is there any way to automatically generate puzzles with the same minimum necessary moves?


问:
How to update a label text with button inside a collection view in swift 4
I have a collection view inside a table view. There are two plus minus buttons in collection view cell. Now i have to update a label on the plus minus buttons action which is outside of table view. Thanks in advance.

I have to update a Slot: (label) by clicking on plus minus button.

I tried something like this with the delegate protocol.

I declare a delegate in my collection view class.

```<code> protocol SlotsCollectionViewCellDelegate: NSObjectProtocol {
func didTapOnIncrement(Int: Int)
func didTapOnDecrement(Int: Int)
</code>```

}

//after that,

```<code> var delegate: SlotsCollectionViewCellDelegate?

 @IBAction func plusBtnAction(_ sender: Any) {
     self.delegate?.didTapOnIncrement(Int: cartCount)
  }

   @IBAction func minusBtnAction(_ sender: Any) {
     delegate?.didTapOnDecrement(cell: self)
   }
</code>```

And in my Main View Controller

```<code>extension MainViewController: SlotsCollectionViewCellDelegate {

func didTapOnIncrement(Int: Int) {
       cartSlot_lbl.text = Int.description
     }

     func didTapOnDecrement(Int: Int) {
         cartSlot_lbl.text = Int.description
     }
</code>```

}

答:
If I understood correctly, each time you push + or - you want to update slot label. In my opinion the easiest and fastest way to achieve this it's using NotificationCenter.default.post

In your collection view cell on button action write:

```<code>NotificationCenter.default.post(name: Notification.Name("postAction"), object: numberToIncreaseOrDecrease)
</code>```

In your MainViewController where you have the slot label, add this code in view did load:

```<code>NotificationCenter.default.addObserver(self, selector: #selector(updateSlotValue(_:)), name: NSNotification.Name("postAction"), object: nil)
</code>```

And out from the view did load add this function:

```<code> @objc func updateSlotValue(_ notification: Notification) {
    let value = notification.object as! Int
    cartSlot_lbl.text.text = value
}
</code>```

Body:
I have a collection view inside a table view. There are two plus minus buttons in collection view cell. Now i have to update a label on the plus minus buttons action which is outside of table view. Thanks in advance.

I have to update a Slot: (label) by clicking on plus minus button.

I tried something like this with the delegate protocol.

I declare a delegate in my collection view class.

 protocol SlotsCollectionViewCellDelegate: NSObjectProtocol {
func didTapOnIncrement(Int: Int)
func didTapOnDecrement(Int: Int)

}

//after that,

 var delegate: SlotsCollectionViewCellDelegate?

 @IBAction func plusBtnAction(_ sender: Any) {
     self.delegate?.didTapOnIncrement(Int: cartCount)
  }

   @IBAction func minusBtnAction(_ sender: Any) {
     delegate?.didTapOnDecrement(cell: self)
   }

And in my Main View Controller

extension MainViewController: SlotsCollectionViewCellDelegate {

func didTapOnIncrement(Int: Int) {
       cartSlot_lbl.text = Int.description
     }

     func didTapOnDecrement(Int: Int) {
         cartSlot_lbl.text = Int.description
     }

}

Body:
If I understood correctly, each time you push + or - you want to update slot label. In my opinion the easiest and fastest way to achieve this it's using NotificationCenter.default.post

In your collection view cell on button action write:

NotificationCenter.default.post(name: Notification.Name("postAction"), object: numberToIncreaseOrDecrease)

In your MainViewController where you have the slot label, add this code in view did load:

NotificationCenter.default.addObserver(self, selector: #selector(updateSlotValue(_:)), name: NSNotification.Name("postAction"), object: nil)

And out from the view did load add this function:

 @objc func updateSlotValue(_ notification: Notification) {
    let value = notification.object as! Int
    cartSlot_lbl.text.text = value
}


问:
Why does using Shell to run a .MSI file sometimes fail in VB6?
I am attempting to launch the .NET CF installer from a VB6 app using the following code (for the sake of brevity I have replaced the full path to the installer with "(full path)"):

```<code>Shell "C:\WINDOWS\system32\msiexec.exe /fa ""(full path)\NETCFSetupv35.msi"""
</code>```

I've run this on four machines so far.  On two it works fine, on the other two it fails.  When it works, the CF installer just runs.  When it fails, the first thing it does is pop up a dialog saying, "The feature you are trying to use is on a CD ROM or other removable disk that is not available."  The dialog provides a text box to enter a path and a browse button to find it, so I provide the path, click the open button and get this error, "Error 1706.No valid source could be found for product Microsoft .NET Compact Framework 3.5.  The Windows Installer cannot continue."

Can anyone tell me what's going wrong here?  What is missing from the machines upon which it fails?

答:
Have you tried running the installer manually on the computer where vb6 fails?

If it does work then it is probably not an installer issue. My guess would be that it is an execution path issue where shell finds the correct components when the PATH variable is set correctly

OwnerDisplayName: raven

ContentLicense: CC BY-SA 2.5

Body:
I am attempting to launch the .NET CF installer from a VB6 app using the following code (for the sake of brevity I have replaced the full path to the installer with "(full path)"):

Shell "C:\WINDOWS\system32\msiexec.exe /fa ""(full path)\NETCFSetupv35.msi"""

I've run this on four machines so far.  On two it works fine, on the other two it fails.  When it works, the CF installer just runs.  When it fails, the first thing it does is pop up a dialog saying, "The feature you are trying to use is on a CD ROM or other removable disk that is not available."  The dialog provides a text box to enter a path and a browse button to find it, so I provide the path, click the open button and get this error, "Error 1706.No valid source could be found for product Microsoft .NET Compact Framework 3.5.  The Windows Installer cannot continue."

Can anyone tell me what's going wrong here?  What is missing from the machines upon which it fails?

OwnerDisplayName: Eric


问:
Application.Current.MainPage working inside OnAppearing but not on Button Click
I am facing this weird issue with Xamarin Forms.

This code is working:

```<code>protected override void OnAppearing()
{
 base.OnAppearing();
 Application.Current.MainPage = new MasterIndexPage();
}
</code>```

but this is not working:

```<code>private void BtnLogin_Clicked(object sender, EventArgs e)
{
 Application.Current.MainPage = new MasterIndexPage();
}
</code>```

Both methods belong to the same view page. I added a break-point inside button click event, which is hitting successfully. But MasterIndexPage is not appearing, view stays on same page.

And there is one more thing... the above behavior is only when I install the app for the first time. If I close and relaunch the app, both the above codes work. There may be something really small, but I am struggling from over 4 hours and still unable to figure out.

Please help.

Update: Sharing full code sample to reproduce the issue.

MasterIndexPage.xaml

```<code><?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  Title="Workman"
                  x:Class="Workman.MasterIndexPage">

    <MasterDetailPage.Master>

        <ContentPage Title="Menu" BackgroundColor="#FFFFFF">
            <Label Text="Test Menu" />
        </ContentPage>

    </MasterDetailPage.Master>

    <MasterDetailPage.Detail>
        <ContentPage Title="Content" BackgroundColor="#FFFFFF">
            <Label Text="Content Area" />
        </ContentPage>
    </MasterDetailPage.Detail>

</MasterDetailPage>
</code>```

MasterIndexPage.xaml.cs

```<code>using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Workman
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MasterIndexPage : MasterDetailPage
    {

        public MasterIndexPage()
        {
            InitializeComponent();
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
        }

    }
}
</code>```

LoginPage.xaml

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             Title="About"
             x:Class="Workman.LoginPage">

    <ContentPage.Content>

        <StackLayout Margin="20,20,20,20">

            <Button Grid.Row="8" Grid.Column="1"
                    x:Name="btnlogin" Clicked="BtnLogin_Clicked"
                    TextColor="White" FontSize="Large"
                    Text="Login" />

        </StackLayout>

    </ContentPage.Content>

</ContentPage>
</code>```

LoginPage.xaml.cs

```<code>using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Workman
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class LoginPage : ContentPage
    {

        public LoginPage()
        {
            InitializeComponent();
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
        }

        private void BtnLogin_Clicked(object sender, EventArgs e)
        {
            Application.Current.MainPage = new MasterIndexPage();
            //This line is hitting but not working
        }

    }
}
</code>```

I am able to reproduce the issue with two newly created pages and with above minimalist code. However, as mentioned before, the issue happens only when the app is not installed, on first run. After closing and relaunching, it works.

答:
Your code works fine on my side . And since it works after you relaunching it, I don't think the issue is caused by your code .

As a better design , you could set the MainPage as MasterIndexPage  directly in App.xaml.cs . And login page could come as a modal page .

```<code>public partial class MasterIndexPage : MasterDetailPage
{
    bool HasLogin;

    public MasterIndexPage ()
    {
        InitializeComponent();

    }

    protected override void OnAppearing()
    {
        base.OnAppearing();

        if(!HasLogin)
        {
            HasLogin = true;  //  here just for demo , you could change it when user login scuuess
            Navigation.PushModalAsync(new LoginPage());

        }

    }

}
</code>```

And in login page

```<code>private  void Button_Clicked(object sender, EventArgs e)
    {
        // when login success
        Navigation.PopModalAsync();

    }
</code>```

Body:
I am facing this weird issue with Xamarin Forms.

This code is working:

protected override void OnAppearing()
{
 base.OnAppearing();
 Application.Current.MainPage = new MasterIndexPage();
}

but this is not working:

private void BtnLogin_Clicked(object sender, EventArgs e)
{
 Application.Current.MainPage = new MasterIndexPage();
}

Both methods belong to the same view page. I added a break-point inside button click event, which is hitting successfully. But MasterIndexPage is not appearing, view stays on same page.

And there is one more thing... the above behavior is only when I install the app for the first time. If I close and relaunch the app, both the above codes work. There may be something really small, but I am struggling from over 4 hours and still unable to figure out.

Please help.

Update: Sharing full code sample to reproduce the issue.

MasterIndexPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  Title="Workman"
                  x:Class="Workman.MasterIndexPage">

    <MasterDetailPage.Master>

        <ContentPage Title="Menu" BackgroundColor="#FFFFFF">

        </ContentPage>

    </MasterDetailPage.Master>

    <MasterDetailPage.Detail>
        <ContentPage Title="Content" BackgroundColor="#FFFFFF">

        </ContentPage>
    </MasterDetailPage.Detail>

</MasterDetailPage>

MasterIndexPage.xaml.cs

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Workman
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MasterIndexPage : MasterDetailPage
    {

        public MasterIndexPage()
        {
            InitializeComponent();
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
        }

    }
}

LoginPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             Title="About"
             x:Class="Workman.LoginPage">

    <ContentPage.Content>

        <StackLayout Margin="20,20,20,20">

            <Button Grid.Row="8" Grid.Column="1"
                    x:Name="btnlogin" Clicked="BtnLogin_Clicked"
                    TextColor="White" FontSize="Large"
                    Text="Login" />

        </StackLayout>

    </ContentPage.Content>

</ContentPage>

LoginPage.xaml.cs

using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Workman
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class LoginPage : ContentPage
    {

        public LoginPage()
        {
            InitializeComponent();
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
        }

        private void BtnLogin_Clicked(object sender, EventArgs e)
        {
            Application.Current.MainPage = new MasterIndexPage();
            //This line is hitting but not working
        }

    }
}

I am able to reproduce the issue with two newly created pages and with above minimalist code. However, as mentioned before, the issue happens only when the app is not installed, on first run. After closing and relaunching, it works.

Body:
Your code works fine on my side . And since it works after you relaunching it, I don't think the issue is caused by your code .

As a better design , you could set the MainPage as MasterIndexPage  directly in App.xaml.cs . And login page could come as a modal page .

public partial class MasterIndexPage : MasterDetailPage
{
    bool HasLogin;

    public MasterIndexPage ()
    {
        InitializeComponent();

    }

    protected override void OnAppearing()
    {
        base.OnAppearing();

        if(!HasLogin)
        {
            HasLogin = true;  //  here just for demo , you could change it when user login scuuess
            Navigation.PushModalAsync(new LoginPage());

        }

    }

}

And in login page

private  void Button_Clicked(object sender, EventArgs e)
    {
        // when login success
        Navigation.PopModalAsync();

    }


问:
All checks have failed due to Warning: RequireJS failed. Use --force to continue
I am not a regular developer.

All I wanted was to add a language translation to select2; translated the default src/js/select2/i18n/en.js file contents, created new file with changing labels from English to non-english.

Upon submitting the pull request, I see the All checks have failed and below the CI/Linting result:

```<code>Run grunt compile lint
Running "requirejs:dist" (requirejs) task
Error: ENOENT: no such file or directory, open
'/home/runner/work/select2/select2/src/js/select2/i18n/en.js'
In module tree:
select2/core
select2/options
select2/defaults
Warning: RequireJS failed. Use --force to continue.

Aborted due to warnings.
##[error]Process completed with exit code 6.
</code>```

Same is the results with CI/Tests and CI/Minification.
What needs to be done to get the translation file successfully merged.

答:
The build of your first pull request failed as your commit had deleted the en.js file as mentioned in this PR comment. That is the error log that you have mentioned in this question of yours.

Your second pull request is failing due to the below mentioned reasons in the build log

```<code>Running "jshint:code" (jshint) task

   src/js/select2/i18n/te.js
     13 |                var message = overChars + ' అక్షరం తొలిగించండి';
                             ^ 'message' is already defined.
     16 |            return message;
                            ^ 'message' used out of scope.
     31 |                var message = 'మీరు ' + args.maximum + ' అంశాల్ని మాత్రమే ఎంచుకోగలరు';
                                                                                ^ Line is too long.
     33 |                var message = 'మీరు ' + args.maximum + ' అంశాన్ని మాత్రమే ఎంచుకోగలరు';
                                                                                ^ Line is too long.
     33 |                var message = 'మీరు ' + args.maximum + ' అంశాన్ని మాత్రమే ఎంచుకోగలరు';
                             ^ 'message' is already defined.
     36 |            return message;
                            ^ 'message' used out of scope.

>> 6 errors in 103 files
</code>```

Wherever you see 'message' is already defined and 'message' used out of scope, it is due to incorrectly defining the message variable multiple times and using the variable outside its scope. The error Line is too long is due to the particular line exceeding the max limit per line set as part of the linting config.

Change your inputTooLong function to

```<code>   inputTooLong: function (args) {
        var overChars = args.input.length - args.maximum;
        var message = overChars;

        if (overChars != 1) {
            message += ' అక్షరాలు తొలిగించండి';
        } else {
            message += ' అక్షరం తొలిగించండి';
        }

        return message;
    }
</code>```

And change your maximumSelected function to

```<code>   maximumSelected: function (args) {
        var message = 'మీరు ' + args.maximum;

        if (args.maximum != 1) {
            message += ' అంశాల్ని మాత్రమే ఎంచుకోగలరు';
        } else {
            message += ' అంశాన్ని మాత్రమే ఎంచుకోగలరు';
        }

        return message;
    }
</code>```

You also have given more indentation than what's expected. Compare the file en.js in the repo with your changes and get rid of the extra indentation too accordingly.

Note: I would advise you to run the linting build on your local machine using the command grunt compile lint as specified in their GitHub action config, so that you can get to know of any errors before pushing your change to the GitHub repository.

Body:
I am not a regular developer.

All I wanted was to add a language translation to select2; translated the default src/js/select2/i18n/en.js file contents, created new file with changing labels from English to non-english.

Upon submitting the pull request, I see the All checks have failed and below the CI/Linting result:

Run grunt compile lint
Running "requirejs:dist" (requirejs) task
Error: ENOENT: no such file or directory, open
'/home/runner/work/select2/select2/src/js/select2/i18n/en.js'
In module tree:
select2/core
select2/options
select2/defaults
Warning: RequireJS failed. Use --force to continue.

Aborted due to warnings.
##[error]Process completed with exit code 6.

Same is the results with CI/Tests and CI/Minification.
What needs to be done to get the translation file successfully merged.

Body:
The build of your first pull request failed as your commit had deleted the en.js file as mentioned in this PR comment. That is the error log that you have mentioned in this question of yours.

Your second pull request is failing due to the below mentioned reasons in the build log

Running "jshint:code" (jshint) task

   src/js/select2/i18n/te.js
     13 |                var message = overChars + ' అక్షరం తొలిగించండి';
                             ^ 'message' is already defined.
     16 |            return message;
                            ^ 'message' used out of scope.
     31 |                var message = 'మీరు ' + args.maximum + ' అంశాల్ని మాత్రమే ఎంచుకోగలరు';
                                                                                ^ Line is too long.
     33 |                var message = 'మీరు ' + args.maximum + ' అంశాన్ని మాత్రమే ఎంచుకోగలరు';
                                                                                ^ Line is too long.
     33 |                var message = 'మీరు ' + args.maximum + ' అంశాన్ని మాత్రమే ఎంచుకోగలరు';
                             ^ 'message' is already defined.
     36 |            return message;
                            ^ 'message' used out of scope.

>> 6 errors in 103 files

Wherever you see 'message' is already defined and 'message' used out of scope, it is due to incorrectly defining the message variable multiple times and using the variable outside its scope. The error Line is too long is due to the particular line exceeding the max limit per line set as part of the linting config.

Change your inputTooLong function to

   inputTooLong: function (args) {
        var overChars = args.input.length - args.maximum;
        var message = overChars;

        if (overChars != 1) {
            message += ' అక్షరాలు తొలిగించండి';
        } else {
            message += ' అక్షరం తొలిగించండి';
        }

        return message;
    }

And change your maximumSelected function to

   maximumSelected: function (args) {
        var message = 'మీరు ' + args.maximum;

        if (args.maximum != 1) {
            message += ' అంశాల్ని మాత్రమే ఎంచుకోగలరు';
        } else {
            message += ' అంశాన్ని మాత్రమే ఎంచుకోగలరు';
        }

        return message;
    }

You also have given more indentation than what's expected. Compare the file en.js in the repo with your changes and get rid of the extra indentation too accordingly.

Note: I would advise you to run the linting build on your local machine using the command grunt compile lint as specified in their GitHub action config, so that you can get to know of any errors before pushing your change to the GitHub repository.


问:
GenSA and SA giving nonsense output for Knapsack problem
I have the following CSV:

Knapsack.CSV

```<code>,gewichten(gr),waarde
Voorwerp 1,70,135
Voorwerp 2,73,139
Voorwerp 3,77,149
Voorwerp 4,80,150
Voorwerp 5,82,156
Voorwerp 6,87,163
Voorwerp 7,90,173
Voorwerp 8,94,184
Voorwerp 9,98,192
Voorwerp 10,106,201
Voorwerp 11,110,210
Voorwerp 12,113,214
Voorwerp 13,115,221
Voorwerp 14,118,229
Voorwerp 15,120,240
</code>```

I am trying to solve the Knapsack problem by using GenSA and GA. The solution for this set of data should be around 1458.

However, with this code:

```<code>install.packages("GenSA")
install.packages("GA")
require(GenSA)
library(GenSA)
require(GA)
library(GA)

#Loading data
df <- read.csv("knapsack.csv", header=TRUE, sep=",")

#Define function
knapsack <- function(x) {
  f <- sum(x * df[3])
  penalty <- sum(df[2]) * abs(sum(x*df[2]) - 750)
  f - penalty
}

init <- runif(1, -5000, 5000)

onder <- rep(-5000, length(init))
boven <- rep(5000, length(init))

controlelijst <- list(max.time=25, nb.stop.improvement = 100)

resultaatSA <- GenSA(par=init, lower = onder, upper = boven, fn=knapsack, control=controlelijst)

resultaatSA$par

# Solution num 2
SGA <- ga(type="binary", fitness=knapsack, nBits=length(df[1]), maxiter=150, run=250, popSize=100, seed=101)

SGA
SGA@solution
</code>```

I get a lot of nonsense output. GenSA for example says the solution is -5000, or sometimes 5000. Which are boundaries/constraints I have set.

SA gives 1 as solution.

What exactly am I doing wrong, and how do I need to use those two functions correctly?

答:
In the GA call you passed the wrong nBits as mentioned in the comment by user2957945

Based on: Solving the Knapsack Problem with a Simple Genetic Algorithm
<s>I got two solutions with 1449 profit and 750 Weight</s>

Edit: with more generations and bigger population size I got one solution with 1456 profit and 750 weight

```<code>library(GA)
# --------------------------------------------------------------------
# Read Data
# --------------------------------------------------------------------
my_df <- read.table(text=',gewichten(gr),waarde
Voorwerp 1,70,135
Voorwerp 2,73,139
Voorwerp 3,77,149
Voorwerp 4,80,150
Voorwerp 5,82,156
Voorwerp 6,87,163
Voorwerp 7,90,173
Voorwerp 8,94,184
Voorwerp 9,98,192
Voorwerp 10,106,201
Voorwerp 11,110,210
Voorwerp 12,113,214
Voorwerp 13,115,221
Voorwerp 14,118,229
Voorwerp 15,120,240', sep=',', header=T)

# --------------------------------------------------------------------
# Define  profit, weights, Knapsack limit, and fitness function
# --------------------------------------------------------------------
p <- my_df$waarde
w <- my_df$gewichten.gr.
W <- 750
n <- length(p)

# Define fitness function
knapsack <- function(x) {
  f <- sum(x * p)
  penalty <- sum(w) * abs(sum(x * w) - W)
  f - penalty
}

# --------------------------------------------------------------------
# Run SGA
# --------------------------------------------------------------------
SGA <- ga(type="binary",
          fitness=knapsack ,
          nBits=n,
          maxiter=500, # Maximum number of generations
          run=200,     # Stop if the best-so-far fitness
          # hasn't improved for 'run' generations
          popSize=200)

# --------------------------------------------------------------------
# see results
# --------------------------------------------------------------------
x.star <- SGA@solution
# solutions
x.star
# number of elements in each solution
rowSums(x.star)
# profit in each solution
rowSums(sweep(x.star, MARGIN=2, p, `*`))
# weight of each solution
rowSums(sweep(x.star, MARGIN=2, w, `*`))

</code>```

As for the GenSA function, I'm not an expert, but I think it was meant for more complex optimizations, and it minimizes the function (unlike ga which maximizes the function), so you can't use the same function for both methods. Another caveat is the fact that the knapsack problem is usually considered a binary problem (choose 0, 1 for nBits), but I'm not sure you can force GenSA to do that, so you'll need to find a workaround for that.

Here's my try with GenSA, returns a solution with 1456 profit and 750 weight, I used round as a workaround to get a binary output

```<code>library(GenSA)

knapsack_gensa <- function(x) {
  f <- sum(round(x) * p)
  penalty <- sum(w) * abs(sum(round(x) * w) - W)
  penalty - f
}
gensa <- GenSA(lower = rep(0, n),
               upper = rep(1, n),
               fn=knapsack_gensa)

solution <- round(gensa$par)
sum(solution)
sum(solution*p)
sum(solution*w)
</code>```

Body:
I have the following CSV:

Knapsack.CSV

,gewichten(gr),waarde
Voorwerp 1,70,135
Voorwerp 2,73,139
Voorwerp 3,77,149
Voorwerp 4,80,150
Voorwerp 5,82,156
Voorwerp 6,87,163
Voorwerp 7,90,173
Voorwerp 8,94,184
Voorwerp 9,98,192
Voorwerp 10,106,201
Voorwerp 11,110,210
Voorwerp 12,113,214
Voorwerp 13,115,221
Voorwerp 14,118,229
Voorwerp 15,120,240

I am trying to solve the Knapsack problem by using GenSA and GA. The solution for this set of data should be around 1458.

However, with this code:

install.packages("GenSA")
install.packages("GA")
require(GenSA)
library(GenSA)
require(GA)
library(GA)

#Loading data
df <- read.csv("knapsack.csv", header=TRUE, sep=",")

#Define function
knapsack <- function(x) {
  f <- sum(x * df[3])
  penalty <- sum(df[2]) * abs(sum(x*df[2]) - 750)
  f - penalty
}

init <- runif(1, -5000, 5000)

onder <- rep(-5000, length(init))
boven <- rep(5000, length(init))

controlelijst <- list(max.time=25, nb.stop.improvement = 100)

resultaatSA <- GenSA(par=init, lower = onder, upper = boven, fn=knapsack, control=controlelijst)

resultaatSA$par

# Solution num 2
SGA <- ga(type="binary", fitness=knapsack, nBits=length(df[1]), maxiter=150, run=250, popSize=100, seed=101)

SGA
SGA@solution

I get a lot of nonsense output. GenSA for example says the solution is -5000, or sometimes 5000. Which are boundaries/constraints I have set.

SA gives 1 as solution.

What exactly am I doing wrong, and how do I need to use those two functions correctly?

Body:
In the GA call you passed the wrong nBits as mentioned in the comment by user2957945

Based on: Solving the Knapsack Problem with a Simple Genetic Algorithm
<s>I got two solutions with 1449 profit and 750 Weight</s>

Edit: with more generations and bigger population size I got one solution with 1456 profit and 750 weight

library(GA)
# --------------------------------------------------------------------
# Read Data
# --------------------------------------------------------------------
my_df <- read.table(text=',gewichten(gr),waarde
Voorwerp 1,70,135
Voorwerp 2,73,139
Voorwerp 3,77,149
Voorwerp 4,80,150
Voorwerp 5,82,156
Voorwerp 6,87,163
Voorwerp 7,90,173
Voorwerp 8,94,184
Voorwerp 9,98,192
Voorwerp 10,106,201
Voorwerp 11,110,210
Voorwerp 12,113,214
Voorwerp 13,115,221
Voorwerp 14,118,229
Voorwerp 15,120,240', sep=',', header=T)

# --------------------------------------------------------------------
# Define  profit, weights, Knapsack limit, and fitness function
# --------------------------------------------------------------------
p <- my_df$waarde
w <- my_df$gewichten.gr.
W <- 750
n <- length(p)

# Define fitness function
knapsack <- function(x) {
  f <- sum(x * p)
  penalty <- sum(w) * abs(sum(x * w) - W)
  f - penalty
}

# --------------------------------------------------------------------
# Run SGA
# --------------------------------------------------------------------
SGA <- ga(type="binary",
          fitness=knapsack ,
          nBits=n,
          maxiter=500, # Maximum number of generations
          run=200,     # Stop if the best-so-far fitness
          # hasn't improved for 'run' generations
          popSize=200)

# --------------------------------------------------------------------
# see results
# --------------------------------------------------------------------
x.star <- SGA@solution
# solutions
x.star
# number of elements in each solution
rowSums(x.star)
# profit in each solution
rowSums(sweep(x.star, MARGIN=2, p, `*`))
# weight of each solution
rowSums(sweep(x.star, MARGIN=2, w, `*`))

As for the GenSA function, I'm not an expert, but I think it was meant for more complex optimizations, and it minimizes the function (unlike ga which maximizes the function), so you can't use the same function for both methods. Another caveat is the fact that the knapsack problem is usually considered a binary problem (choose 0, 1 for nBits), but I'm not sure you can force GenSA to do that, so you'll need to find a workaround for that.

Here's my try with GenSA, returns a solution with 1456 profit and 750 weight, I used round as a workaround to get a binary output

library(GenSA)

knapsack_gensa <- function(x) {
  f <- sum(round(x) * p)
  penalty <- sum(w) * abs(sum(round(x) * w) - W)
  penalty - f
}
gensa <- GenSA(lower = rep(0, n),
               upper = rep(1, n),
               fn=knapsack_gensa)

solution <- round(gensa$par)
sum(solution)
sum(solution*p)
sum(solution*w)


问:
What is function designator and actual call?
According to C99 Standard:

The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.

Could anyone explain clearly what is function designator and actual call; and what is difference between them ?

答:
I would assume that the function designator is what tells the program which function to call. It might be either a function name or an expression resulting in a function pointer.

Edit:

Here is a function pointer example:

```<code>// Two random functions
int foo(int i);
int bar(int i);

// define a function pointer type
typedef int (* func)(int)

// Array of functions

func a[] = {foo, bar}

// calling bar(123)
// (a[1]) is an expression that evaluates to a pointer to `bar`

(a[1])(123);
</code>```

Body:
I would assume that the function designator is what tells the program which function to call. It might be either a function name or an expression resulting in a function pointer.

Edit:

Here is a function pointer example:

// Two random functions
int foo(int i);
int bar(int i);

// define a function pointer type
typedef int (* func)(int)

// Array of functions

func a[] = {foo, bar}

// calling bar(123)
// (a[1]) is an expression that evaluates to a pointer to `bar`

(a[1])(123);


问:
pip installs packages successfully, but executables not found from command line
I am working on mac OS X Yosemite, version 10.10.3.

I installed python2.7 and pip using macport as done in
http://johnlaudun.org/20150512-installing-and-setting-pip-with-macports/

I can successfully install packages and import them inside my python environment and python scripts. However any executable associated with a package that can be called from the command line in the terminal are not found.

Does anyone know what might be wrong? (More details below)

For example while installing a package called "rosdep" as instructed in http://wiki.ros.org/jade/Installation/Source

I can run: sudo pip install -U rosdep
which installs without errors and corresponding files are located in /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages

However if I try to run : sudo rosdep init,
it gives an error : "sudo: rosdep: command not found"

This is not a package specific error. I get this for any package installed using pip on my computer. I even tried adding

```<code>/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
</code>```

to my $PATH.
But the executables are not found on the command line, even though the packages work perfectly from within python.

答:
Solution

Based on other answers, for linux and mac you can run the following:

echo "export PATH=\"`python3 -m site --user-base`/bin:\$PATH\"" >> ~/.bashrc
source ~/.bashrc
```
<p>instead of <code>python3</code> you can use any other link to python version: <code>python</code>, <code>python2.7</code>, <code>python3.6</code>, <code>python3.9</code>, etc.</p>
<p>instead of .bashrc, choose the rc file from your favourite shell.</p>
<h2>Explanation</h2>
<p>In order to know where the user packages are installed in the current OS (win, mac, linux), we run:</p>
<pre class="lang-sh prettyprint-override"><code>python3 -m site --user-base
</code>```

We know that the scripts go to the bin/ folder where the packages are installed.

So we concatenate the paths:

echo `python3 -m site --user-base`/bin
```
<p>Then we export that to an environment variable.</p>
<pre class="lang-sh prettyprint-override"><code>export PATH=\"`python3 -m site --user-base`/bin:\$PATH\"
</code>```

Finally, in order to avoid repeating the export command we add it to our .bashrc file and we run source to run the new changes, giving us the suggested solution mentioned at the beginning.

Body:
I am working on mac OS X Yosemite, version 10.10.3.

I installed python2.7 and pip using macport as done in
http://johnlaudun.org/20150512-installing-and-setting-pip-with-macports/

I can successfully install packages and import them inside my python environment and python scripts. However any executable associated with a package that can be called from the command line in the terminal are not found.

Does anyone know what might be wrong? (More details below)

For example while installing a package called "rosdep" as instructed in http://wiki.ros.org/jade/Installation/Source

I can run: sudo pip install -U rosdep
which installs without errors and corresponding files are located in /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages

However if I try to run : sudo rosdep init,
it gives an error : "sudo: rosdep: command not found"

This is not a package specific error. I get this for any package installed using pip on my computer. I even tried adding

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages

to my $PATH.
But the executables are not found on the command line, even though the packages work perfectly from within python.

Body:
Solution

Based on other answers, for linux and mac you can run the following:

echo "export PATH=\"`python3 -m site --user-base`/bin:\$PATH\"" >> ~/.bashrc
source ~/.bashrc

instead of python3 you can use any other link to python version: python, python2.7, python3.6, python3.9, etc.

instead of .bashrc, choose the rc file from your favourite shell.

Explanation

In order to know where the user packages are installed in the current OS (win, mac, linux), we run:

python3 -m site --user-base

We know that the scripts go to the bin/ folder where the packages are installed.

So we concatenate the paths:

echo `python3 -m site --user-base`/bin

Then we export that to an environment variable.

export PATH=\"`python3 -m site --user-base`/bin:\$PATH\"

Finally, in order to avoid repeating the export command we add it to our .bashrc file and we run source to run the new changes, giving us the suggested solution mentioned at the beginning.


答:
This one puts all the columns into a list.

```<code>res <- lapply(1:ncol(mu_t_0), function(i) mu_t_0[, i, drop=F])

head(res[[1]])
#      [,1]
# [1,]    1
# [2,]    0
# [3,]    0
# [4,]    0
# [5,]    0
# [6,]    0

head(res[[2]])
#      [,1]
# [1,]    0
# [2,]    1
# [3,]    0
# [4,]    0
# [5,]    0
# [6,]    0
</code>```

To extract the single one column matrices use list2env; the objects in the list need names beforehand.

```<code>names(res) <- paste0("m.", 1:length(res))
list2env(res, env=.GlobalEnv)
ls()
# [1] "m.1"    "m.10"   "m.2"    "m.3"    "m.4"    "m.5"    "m.6"    "m.7"    "m.8"    "m.9"    "mu_0"   "mu_t_0"
# [13] "N"      "res"    "T"
</code>```

Title: How can I convert matrix to different matrices in R?

Body:
Here I have some codes generating a matrix like this:

N = 200
T = 10
mu_0 <- matrix(diag(1, T))
dim(mu_0) <- c(T,T)
mu_t_0 <- matrix(rep(t(mu_0), N), ncol = T, byrow = TRUE)

And generally the result looks like this

   V1   V2  V3  V4  V5  V6  V7  V8  V9 V10
1   1   0   0   0   0   0   0   0   0   0
2   0   1   0   0   0   0   0   0   0   0
3   0   0   1   0   0   0   0   0   0   0
4   0   0   0   1   0   0   0   0   0   0
5   0   0   0   0   1   0   0   0   0   0
6   0   0   0   0   0   1   0   0   0   0
7   0   0   0   0   0   0   1   0   0   0
8   0   0   0   0   0   0   0   1   0   0
9   0   0   0   0   0   0   0   0   1   0
10  0   0   0   0   0   0   0   0   0   1
11  1   0   0   0   0   0   0   0   0   0
12  0   1   0   0   0   0   0   0   0   0
13  0   0   1   0   0   0   0   0   0   0
14  0   0   0   1   0   0   0   0   0   0
15  0   0   0   0   1   0   0   0   0   0
16  0   0   0   0   0   1   0   0   0   0
17  0   0   0   0   0   0   1   0   0   0
18  0   0   0   0   0   0   0   1   0   0
19  0   0   0   0   0   0   0   0   1   0
20  0   0   0   0   0   0   0   0   0   1
...

Now for later calculation I want to split this large matrix into different small matrices like this:

Matrix One:

1
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
...

Matrix Two:

0
1
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
...

I tried the split function but I cannot get what I want. Are there any solutions?

Body:
This one puts all the columns into a list.

res <- lapply(1:ncol(mu_t_0), function(i) mu_t_0[, i, drop=F])

head(res[[1]])
#      [,1]
# [1,]    1
# [2,]    0
# [3,]    0
# [4,]    0
# [5,]    0
# [6,]    0

head(res[[2]])
#      [,1]
# [1,]    0
# [2,]    1
# [3,]    0
# [4,]    0
# [5,]    0
# [6,]    0

To extract the single one column matrices use list2env; the objects in the list need names beforehand.

names(res) <- paste0("m.", 1:length(res))
list2env(res, env=.GlobalEnv)
ls()
# [1] "m.1"    "m.10"   "m.2"    "m.3"    "m.4"    "m.5"    "m.6"    "m.7"    "m.8"    "m.9"    "mu_0"   "mu_t_0"
# [13] "N"      "res"    "T"


问:
How to test HTML content with React testing library
Currently I am writing a test to test the content that is inside (HTML content), but it seems I cannot test that properly with React testing library. It can find the id value of that, but how do I get the HTML content inside that element.

import React from 'react';

export const TopBar = () => {
    return (

Dashboard Menu

    )
}

import React from "react";
import { render } from "@testing-library/react";
import { TopBar } from "./TopBar";
import { Provider } from "react-redux";
import { store } from "../../Store";
import { screen } from "@testing-library/dom";
import "@testing-library/jest-dom/extend-expect";

test("It should check if content matches", () => {
    render(
        <Provider store={store}>
            <TopBar/>
        </Provider>
    )
    const checkContent = screen.getAllByTestId("title-content");
    expect(checkContent.text()).toBe("Dashboard Menu");
});```

答:
You can use within to get the text Dashboard Menu. Try this:

test("It should check if content matches", () => {
    const { getByTestId } = render(
        <Provider store={store}>
            <TopBar/>
        </Provider>
    )
    const { getByText } = within(getByTestId('title-content'))
    expect(getByText('Dashboard Menu')).toBeInTheDocument()
});```


问:
"laravel: command not found" after installing Laravel
After I am using

```<code>composer global require laravel/installer
</code>```

it seems the installation is success. For the second time, the result is:

```<code>Changed current directory to /home/ryanadhi/.config/composer
Using version ^3.1 for laravel/installer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files
13 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
</code>```

then if I do

```<code>echo $PATH
</code>```

the result is

```<code>    ~/.composer/vendor/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/local/go/bin:/home/ryanadhi/go/bin:/home/ryanadhi/.composer/vendor/bin
</code>```

However if I try

```<code>laravel
</code>```

the result is always:

```<code>laravel: command not found

</code>```

答:
You need to add /home/ryanadhi/.config/composer/vendor/bin to your path.

The output that said "Changed current directory to /home/ryanadhi/.config/composer" means that /home/ryanadhi/.config/composer is your Composer global directory.

Body:
After I am using

composer global require laravel/installer

it seems the installation is success. For the second time, the result is:

Changed current directory to /home/ryanadhi/.config/composer
Using version ^3.1 for laravel/installer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files
13 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

then if I do

echo $PATH

the result is

    ~/.composer/vendor/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/local/go/bin:/home/ryanadhi/go/bin:/home/ryanadhi/.composer/vendor/bin

However if I try

laravel

the result is always:

laravel: command not found


问:
How do I store data from getSymbols (quantmod library) to a list?
Here's the code I'm running

```<code>library(quantmod)
library(tseries)
Stocks={}
companies=c("IOC.BO","BPCL.BO","ONGC.BO","HINDPETRO.BO","GAIL.BO")
for(i in companies){
   Stocks[i]=getSymbols(i)
}
</code>```

I'm trying to get a list of dataframes that are obtained from getSymbols to get stored in Stocks.
The problem is that getSymbols directly saves the dataframes to the global environment Stocks only saves the characters in companies in the list.

How do I save the dataframes in the Global Environment to a list?

Any help is appreciated.. Thanks in advance!

答: In my version of quantmod (0.4.0) it was necessary to set env=NULL in the functions' parameters, then the entire data frame is returned

Body:
Here's the code I'm running

library(quantmod)
library(tseries)
Stocks={}
companies=c("IOC.BO","BPCL.BO","ONGC.BO","HINDPETRO.BO","GAIL.BO")
for(i in companies){
   Stocks[i]=getSymbols(i)
}

I'm trying to get a list of dataframes that are obtained from getSymbols to get stored in Stocks.
The problem is that getSymbols directly saves the dataframes to the global environment Stocks only saves the characters in companies in the list.

How do I save the dataframes in the Global Environment to a list?

Any help is appreciated.. Thanks in advance!


问:
How to insert a string to a text field programatically in JavaScript
I would like to add a string of text to a text field using JavaScript but I don't want to use the onClick or onLoad events to do so.

I simply want the JavaScript to be executed as soon as the browser reads it and the JavaScript will be within the body of the html.

The text field is something like:

```<code><form action="" method="post" name="formname" id="user-registration-form">
    <input type="text" name="edit-form" id="edit-form" />
</form>
</code>```

I have tried something like this but it doesn't work:

```<code><script type="text/javascript"> edit-form.value="the new value"; </script>
</code>```

How can I do this?

答:
A lot of the time you don't have the luxury of all the form elements having ids.  This is how you can make it work with the field only having a name attribute:</p>

```<code>document.getElementById('user-registration-form').elements['edit-form'].value = 'new value';
</code>```

Body:
I would like to add a string of text to a text field using JavaScript but I don't want to use the onClick or onLoad events to do so.

I simply want the JavaScript to be executed as soon as the browser reads it and the JavaScript will be within the body of the html.

The text field is something like:

<form action="" method="post" name="formname" id="user-registration-form">
    <input type="text" name="edit-form" id="edit-form" />
</form>

I have tried something like this but it doesn't work:

How can I do this?

Body:
A lot of the time you don't have the luxury of all the form elements having ids.  This is how you can make it work with the field only having a name attribute:

document.getElementById('user-registration-form').elements['edit-form'].value = 'new value';


问:
Javascript get XPath of a node
Is there anyway to return an XPath string of a DOM element in Javascript?</p>

答:
I checked every solution provided here but none of them works with svg elements (code getElementByXPath(getXPathForElement(elm)) === elm returns false for svg or path elements)

So I added the Touko's svg fix to the trincot's solution and got this code:

function getXPathForElement(element) {
    const idx = (sib, name) => sib
        ? idx(sib.previousElementSibling, name||sib.localName) + (sib.localName == name)
        : 1;
    const segs = elm => !elm || elm.nodeType !== 1
        ? ['']
        : elm.id && document.getElementById(elm.id) === elm
            ? [`id("${elm.id}")`]
            : [...segs(elm.parentNode), elm instanceof HTMLElement
                ? `${elm.localName}[${idx(elm)}]`
                : `*[local-name() = "${elm.localName}"][${idx(elm)}]`];
    return segs(element).join('/');
}
```

The difference is it returns *[local-name() = "tag"][n] instead of tag[n] if element is not an instance of HTMLElement (svgs are SVGElement but I decided not to stick with checking only svg).

Example:

Before:

.../div[2]/div[2]/span[1]/svg[1]/path[1]

After:

.../div[2]/div[2]/span[1]/*[local-name() = "svg"][1]/*[local-name() = "path"][1]

Title: Javascript get XPath of a node

Body:
I checked every solution provided here but none of them works with svg elements (code getElementByXPath(getXPathForElement(elm)) === elm returns false for svg or path elements)

So I added the Touko's svg fix to the trincot's solution and got this code:

function getXPathForElement(element) {
    const idx = (sib, name) => sib
        ? idx(sib.previousElementSibling, name||sib.localName) + (sib.localName == name)
        : 1;
    const segs = elm => !elm || elm.nodeType !== 1
        ? ['']
        : elm.id && document.getElementById(elm.id) === elm
            ? [`id("${elm.id}")`]
            : [...segs(elm.parentNode), elm instanceof HTMLElement
                ? `${elm.localName}[${idx(elm)}]`
                : `*[local-name() = "${elm.localName}"][${idx(elm)}]`];
    return segs(element).join('/');
}

The difference is it returns *[local-name() = "tag"][n] instead of tag[n] if element is not an instance of HTMLElement (svgs are SVGElement but I decided not to stick with checking only svg).

Example:

Before:

.../div[2]/div[2]/span[1]/svg[1]/path[1]

After:

.../div[2]/div[2]/span[1]/*[local-name() = "svg"][1]/*[local-name() = "path"][1]


问:
MAMP PRO - specify path to .crt and .key file in for external POST call
Using MAMP Pro for local development I need to communicate with an external API. I need to specify a path to a certificate file and private key for a secure SSL connection. I got both of these files from the external party to set these up.
Using Curl this is gonna be something like;

```<code>    $ curl
--request POST
--url https://externalapitocall
--cert '/path/to/cert.crt'
--key '/path/to/key.key'
--user 'DEXNLxxxx:***********'
--header 'grant_type: client_credentials&scope=api'
--header 'content-type: application/x-www-form-urlencoded'
</code>```

So basically I only need these certificates and key when calling this external API. (So not my normal SSL certificate) I'm at a loss how to implement this using best practices. Where do I need to store the .crt and .key file, and what should my path to these files be?

答:
Looking back at this. Answered in: https://stackoverflow.com/a/25573495/4329627

It does not matter where it is stored. But the public part can be accessible for anyone. The private key part is what you need to put in a safe spot somewhere only your application /db can read the values. There is no specific file destination, at least not that I know of. Just make sure it is safely stored.

Body:
Using MAMP Pro for local development I need to communicate with an external API. I need to specify a path to a certificate file and private key for a secure SSL connection. I got both of these files from the external party to set these up.
Using Curl this is gonna be something like;

    $ curl
--request POST
--url https://externalapitocall
--cert '/path/to/cert.crt'
--key '/path/to/key.key'
--user 'DEXNLxxxx:***********'
--header 'grant_type: client_credentials&scope=api'
--header 'content-type: application/x-www-form-urlencoded'

So basically I only need these certificates and key when calling this external API. (So not my normal SSL certificate) I'm at a loss how to implement this using best practices. Where do I need to store the .crt and .key file, and what should my path to these files be?


问:
To check whether a web element is loaded on a webpage in python selenium
I want to scrape 'href' tags from a webpage which includes profile URL of the name searched on the website. Sometimes, it might even give a null result if the profile of a particular doesn't exist. I am using python selenium wherein I am inputting names from a csv file and sending the keys to the search bar on the website in a loop. But, sometimes randomly the profile URL of the previous search gets carried to the existing name search. This occurs very randomly and I have checked the logic of the code multiple times and there seems to be no error in that part.

I suspect that the webpage is not loading fully before I am pointing towards a particular element using selenium. I have tried using sleep() but it also works for some values and only sometimes. Increasing sleep time would only increase the time with no guarantee for the accuracy (tried and tested).

I actually want a way to check if the URL of the person exists on the webpage or not and if it does I want the url of that specific person and not of the previous one. Is there a solution to this. This is a small block of code which will add further clarity:

```<code># unique result with name
name = '"' + row[1] + '"'
xpath = "//*[@class='search-result__image-wrapper']/a"
search_query.send_keys(name)
search_query.send_keys(Keys.RETURN)
sleep(5)
#WebDriverWait(driver, timeout).until(EC.presence_of_element_located((By.XPATH, xpath)))
links = driver.find_elements_by_xpath(xpath)
if len(links) == 1:
   for link in links:
      url = link.get_attribute('href')
      print('name')
</code>```

P.S.: I have also gone through similar questions on stack overflow but none of them seem to work. I have also used the web driver wait method, which checks for the availability of a specific element on the website that occurs on every search but that doesn't seem to work either.

答:
Why not waiting for the first item in the name list until it is visible, and then assigning the name list and iterating over the name list. See the code below:</p>

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

name = '"' + row[1] + '"'
css_first_name = ".search-result__image-wrapper > a:nth-child(1)"
css_name_list = ".search-result__image-wrapper > a"
search_query.send_keys(name)
search_query.send_keys(Keys.RETURN)
WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.CSS_SELECTOR, css_first_name)))
links = driver.find_elements_by_css_selector(css_name_list)
for link in links:
  url = link.get_attribute('href')
  print('name')
</code>```

Body:
I want to scrape 'href' tags from a webpage which includes profile URL of the name searched on the website. Sometimes, it might even give a null result if the profile of a particular doesn't exist. I am using python selenium wherein I am inputting names from a csv file and sending the keys to the search bar on the website in a loop. But, sometimes randomly the profile URL of the previous search gets carried to the existing name search. This occurs very randomly and I have checked the logic of the code multiple times and there seems to be no error in that part.

I suspect that the webpage is not loading fully before I am pointing towards a particular element using selenium. I have tried using sleep() but it also works for some values and only sometimes. Increasing sleep time would only increase the time with no guarantee for the accuracy (tried and tested).

I actually want a way to check if the URL of the person exists on the webpage or not and if it does I want the url of that specific person and not of the previous one. Is there a solution to this. This is a small block of code which will add further clarity:

# unique result with name
name = '"' + row[1] + '"'
xpath = "//*[@class='search-result__image-wrapper']/a"
search_query.send_keys(name)
search_query.send_keys(Keys.RETURN)
sleep(5)
#WebDriverWait(driver, timeout).until(EC.presence_of_element_located((By.XPATH, xpath)))
links = driver.find_elements_by_xpath(xpath)
if len(links) == 1:
   for link in links:
      url = link.get_attribute('href')
      print('name')

P.S.: I have also gone through similar questions on stack overflow but none of them seem to work. I have also used the web driver wait method, which checks for the availability of a specific element on the website that occurs on every search but that doesn't seem to work either.

Body:
Why not waiting for the first item in the name list until it is visible, and then assigning the name list and iterating over the name list. See the code below:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

name = '"' + row[1] + '"'
css_first_name = ".search-result__image-wrapper > a:nth-child(1)"
css_name_list = ".search-result__image-wrapper > a"
search_query.send_keys(name)
search_query.send_keys(Keys.RETURN)
WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.CSS_SELECTOR, css_first_name)))
links = driver.find_elements_by_css_selector(css_name_list)
for link in links:
  url = link.get_attribute('href')
  print('name')


问:
Trying to clean up survey results with multiple name entries, some answers given as NaN
I am trying to clean up some odd survey data, which I have created an example of below:

```<code>test1 = ['sean','tom','dan','sean']
test2 = ['Y',np.nan,np.nan,np.nan]
test3 = [np.nan,'Y','N','N']

df = pd.DataFrame({'name':test1,'a':test2,'b':test3})

print(df)

   name    a    b
0  sean    Y  NaN
1   tom  NaN    Y
2   dan  NaN    N
3  sean  NaN    N
</code>```

I want to have the results combined so that 'sean' only appears once (so unique values only in the name column) and the answers from both entries of the name have been combined as such:

```<code>   name    a    b
0  sean    Y    N
1   tom  NaN    Y
2   dan  NaN    N
</code>```

Thanks :)

答:
If there is always only one non missing value or all missing values per groups is possible use GroupBy.first:

```<code>df = df.groupby('name', as_index=False, sort=False).first()
print(df)
   name    a  b
0  sean    Y  N
1   tom  NaN  Y
2   dan  NaN  N
</code>```

Body:
I am trying to clean up some odd survey data, which I have created an example of below:

test1 = ['sean','tom','dan','sean']
test2 = ['Y',np.nan,np.nan,np.nan]
test3 = [np.nan,'Y','N','N']

df = pd.DataFrame({'name':test1,'a':test2,'b':test3})

print(df)

   name    a    b
0  sean    Y  NaN
1   tom  NaN    Y
2   dan  NaN    N
3  sean  NaN    N

I want to have the results combined so that 'sean' only appears once (so unique values only in the name column) and the answers from both entries of the name have been combined as such:

   name    a    b
0  sean    Y    N
1   tom  NaN    Y
2   dan  NaN    N

Thanks :)

Body:
If there is always only one non missing value or all missing values per groups is possible use GroupBy.first:

df = df.groupby('name', as_index=False, sort=False).first()
print(df)
   name    a  b
0  sean    Y  N
1   tom  NaN  Y
2   dan  NaN  N


问:
Align an element to bottom with flexbox
I have a div with some children:

```<code><div class="content">
  <h1>heading 1</h1>
  <h2>heading 2</h2>
  <p>Some more or less text</p>
  <a href="/" class="button">Click me</a>
</div>
</code>```

and I want the following layout:

```<code> -------------------
|heading 1          |
|heading 2          |
|paragraph text     |
|can have many      |
|rows               |
|                   |
|                   |
|                   |
|link-button        |
 -------------------
</code>```

Regardless how much text is in the p I want to stick the .button always at the bottom without taking it out of the flow. I've heard this can be achievable with Flexbox but I can't get it to work.

答:
When setting your display to flex, you could simply use the flex property to mark which content can grow and which content cannot.

Flex property

div.content {
 height: 300px;
 display: flex;
 flex-direction: column;
}

div.up {
  flex: 1;
}

div.down {
  flex: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
  <div class="up">
    <h1>heading 1</h1>
    <h2>heading 2</h2>
    <p>Some more or less text</p>
  </div>

  <div class="down">
    Click me
  </div>
</div></code>```

Title: Align an element to bottom with flexbox

Body:
I have a div with some children:

heading 1

heading 2

Some more or less text

  Click me

and I want the following layout:

 -------------------
|heading 1          |
|heading 2          |
|paragraph text     |
|can have many      |
|rows               |
|                   |
|                   |
|                   |
|link-button        |
 -------------------

Regardless how much text is in the p I want to stick the .button always at the bottom without taking it out of the flow. I've heard this can be achievable with Flexbox but I can't get it to work.

Body:
When setting your display to flex, you could simply use the flex property to mark which content can grow and which content cannot.

Flex property

div.content {
 height: 300px;
 display: flex;
 flex-direction: column;
}

div.up {
  flex: 1;
}

div.down {
  flex: none;
}

<div class="content">
  <div class="up">
    <h1>heading 1</h1>
    <h2>heading 2</h2>
    <p>Some more or less text</p>
  </div>

  <div class="down">
    <a href="/" class="button">Click me</a>
  </div>
</div>


问:
How to parse json with unknown keys in android
Hi I am using retrofit to send and receive data from server.How to parse if the keys are different.

Can any one help me how to parse json with below keys.

```<code>{"users": {"19x1": "Admin","19x5": "Manager"}}
</code>```

答:
Your json structure is not correct. Basically you are having an array of users but you return object that has two fields 19x1 and 19x2.

It's not possible to use Retrofit and Gson to parse a dynamic key response. The only way to do is to use Plain Json Parsing in Android. but you will need to know where is the data in the list so you can do something like.

jsonArray.getObject(index)

if you want to get a list of objects then change your json to this structure

```<code>"users": [
    {
        "role_id": "19x1",
        "description": "Admin"
    },
    {
        "role_id": "19x5",
        "description": "Manager"
    }
]
</code>```

Body:
Hi I am using retrofit to send and receive data from server.How to parse if the keys are different.

Can any one help me how to parse json with below keys.

{"users": {"19x1": "Admin","19x5": "Manager"}}

Body:
Your json structure is not correct. Basically you are having an array of users but you return object that has two fields 19x1 and 19x2.

It's not possible to use Retrofit and Gson to parse a dynamic key response. The only way to do is to use Plain Json Parsing in Android. but you will need to know where is the data in the list so you can do something like.

jsonArray.getObject(index)

if you want to get a list of objects then change your json to this structure

"users": [
    {
        "role_id": "19x1",
        "description": "Admin"
    },
    {
        "role_id": "19x5",
        "description": "Manager"
    }
]


问:
How to separate contents of a file into columns based on keyword using Bash
I have a file.txt that has contents in the following format:

```<code>co001 done
co002 done
co003 not run
co004 running
</code>```

I want to read the file.txt and sort the lines into columns based on whether they contain "done", "not run" or "running" and display the following on screen

```<code>co001 done     co003 not run     co004 running
co002 done
</code>```

So far I know I can use grep to extract the "done" or "not run" lines, but I don't know how to sort the grep results into columns. I figured that the "column" command will help somehow, but cannot think of how to go about doing it.

This should be an one-liner thing right?

答:
How about combining the paste command with the process substitution provided by bash:

```<code>paste <(grep "done" file.txt) <(grep "not run" file.txt) <(grep "running" file.txt)
</code>```

Body:
I have a file.txt that has contents in the following format:

co001 done
co002 done
co003 not run
co004 running

I want to read the file.txt and sort the lines into columns based on whether they contain "done", "not run" or "running" and display the following on screen

co001 done     co003 not run     co004 running
co002 done

So far I know I can use grep to extract the "done" or "not run" lines, but I don't know how to sort the grep results into columns. I figured that the "column" command will help somehow, but cannot think of how to go about doing it.

This should be an one-liner thing right?

Body:
How about combining the paste command with the process substitution provided by bash:

paste <(grep "done" file.txt) <(grep "not run" file.txt) <(grep "running" file.txt)


问:
Get array from nested array in Python and store it into a separate array
I need help for my code. I have two arrays, one obtained randomly.

For example:
Let’s say the two arrays are:

randm and r_q

```<code>randm = [1 0 1]
r_q = [[3 5 2]
       [5 4 3]
       [5 2 2]]
</code>```

By multiplying the values above and transposing its product, I got:

```<code>multi_trans_output =   [[3 0 5]
                        [5 0 2]
                        [2 0 2]]
</code>```

What I need to do now is to store the values in multi_trans_output into another arrays like:

```<code>r1 = [3 0 5]
r2 = [5 0 2]
r3 = [2 0 2]
</code>```

Then get their sums:

```<code>r1_sum = [8]
r2_sum = [7]
r3_sum = [4]
</code>```

So far, my code looks like this:

```<code>multi_trans_output = populations*r_q_active.T
# loop for storing of values in r(x)
for d in multiplied_output:
.
.
print(r(x))
r(x)_sum = numpy.sum(r(x), axis=1)
</code>```

Any help/suggestion would be very much appreciated! Thanks in advance.

答:
You can store each rows in a dictionary with their respective name as keys</p>

```<code>import numpy as np

# input two matrices
randm = np.array([1,0,1])
r_q = np.array([[3, 5, 2],[5, 4, 3],[5, 2, 2]])
# This will return dot product
res = randm*r_q.T

# print resulted matrix
dic_for_arrays = {}
dic_for_sum  = {}
for index,lst in enumerate(res):
    dic_for_arrays['row'+str(index+1)] = lst
    dic_for_sum['row'+str(index+1)] = np.sum(lst)
for i in dic_for_arrays:
    print(f"{i} = {dic_for_arrays[i]} \nsum of {i} = {dic_for_sum[i]}")

# Output:
row1 = [3 0 5]
sum of row1 = 8
row2 = [5 0 2]
sum of row2 = 7
row3 = [2 0 2]
sum of row3 = 4
</code>```

Body:
I need help for my code. I have two arrays, one obtained randomly.

For example:
Let’s say the two arrays are:

randm and r_q

randm = [1 0 1]
r_q = [[3 5 2]
       [5 4 3]
       [5 2 2]]

By multiplying the values above and transposing its product, I got:

multi_trans_output =   [[3 0 5]
                        [5 0 2]
                        [2 0 2]]

What I need to do now is to store the values in multi_trans_output into another arrays like:

r1 = [3 0 5]
r2 = [5 0 2]
r3 = [2 0 2]

Then get their sums:

r1_sum = [8]
r2_sum = [7]
r3_sum = [4]

So far, my code looks like this:

multi_trans_output = populations*r_q_active.T
# loop for storing of values in r(x)
for d in multiplied_output:
.
.
print(r(x))
r(x)_sum = numpy.sum(r(x), axis=1)

Any help/suggestion would be very much appreciated! Thanks in advance.

Body:
You can store each rows in a dictionary with their respective name as keys

import numpy as np

# input two matrices
randm = np.array([1,0,1])
r_q = np.array([[3, 5, 2],[5, 4, 3],[5, 2, 2]])
# This will return dot product
res = randm*r_q.T

# print resulted matrix
dic_for_arrays = {}
dic_for_sum  = {}
for index,lst in enumerate(res):
    dic_for_arrays['row'+str(index+1)] = lst
    dic_for_sum['row'+str(index+1)] = np.sum(lst)
for i in dic_for_arrays:
    print(f"{i} = {dic_for_arrays[i]} \nsum of {i} = {dic_for_sum[i]}")

# Output:
row1 = [3 0 5]
sum of row1 = 8
row2 = [5 0 2]
sum of row2 = 7
row3 = [2 0 2]
sum of row3 = 4


问:
wpf use ellipse for progress
curious about using ellipse for showing progress, probably as the progress bar uses IsIndeterminate. I'll have ellipse where either color or opacity create an effect of moving
from left to right, but instead of a sold bar, ellipse controls spread apart. I'm not looking
for a working example, just hoping for some direction in the best way to pursue this.</p>

```<code><Canvas VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Name="canvas1" >
    <Ellipse Height="15" Name="ellipse1" Fill="DodgerBlue"  Stroke="DodgerBlue" Width="15" />
    <Ellipse Height="15" Name="ellipse3" Fill="DimGray"  Stroke="DodgerBlue" Width="15" Canvas.Left="21" Canvas.Top="0" />
    <Ellipse Height="15" Name="ellipse2" Fill="DimGray" Stroke="DodgerBlue" Width="15" Canvas.Left="42" Canvas.Top="0" />
</Canvas>
</code>```

答:
I'd probably start by creating a UserControl that contains an animated ellipse that "pulses" -- becomes brighter and then fades back, waits a second, and then brightens again, and so on.

I'd put multiple instances of that control into a UniformGrid.

To get the desired effect of left-to-right, you'd want to expose some property that would be bound to the start time for the animation, so that the leftmost instance starts at 0, next slightly later, next slightly later, and so on. I'd expect to play with that timing until I get the desired left-to-right "flow".

Title: wpf use ellipse for progress

Body:
curious about using ellipse for showing progress, probably as the progress bar uses IsIndeterminate. I'll have ellipse where either color or opacity create an effect of moving
from left to right, but instead of a sold bar, ellipse controls spread apart. I'm not looking
for a working example, just hoping for some direction in the best way to pursue this.

<Canvas VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Name="canvas1" >
    <Ellipse Height="15" Name="ellipse1" Fill="DodgerBlue"  Stroke="DodgerBlue" Width="15" />
    <Ellipse Height="15" Name="ellipse3" Fill="DimGray"  Stroke="DodgerBlue" Width="15" Canvas.Left="21" Canvas.Top="0" />
    <Ellipse Height="15" Name="ellipse2" Fill="DimGray" Stroke="DodgerBlue" Width="15" Canvas.Left="42" Canvas.Top="0" />
</Canvas>