问:
Pandas: Create a new column based on a another column which is a list of objects
I am trying to create/add a new column into the following dataframe (df_new):

I want this new column (df['category']) to be feed from df['tags'].

The tags columns, is a list of objects, and the value that I want to retrieve is the category, and if there is no category I want to set it as unknown.

This is a sample of my JSON file

```<code>{"submissionTime":"2019-02-25T09:26:00","b_data":{"bName":"Masato","b_Acc":[{"id":0,"transactions":[{"date":"2019-12-19","text":"PERIODICAL PAYMENT","amount":3397,"type":"","tags":[{"institution":"University of MC"},{"lenderType":"private"},{"category":"birdy"},{"creditDebit":"credit"}]},{"date":"2019-12-03","text":"LINE FEE","amount":-460.21,"type":"Overdrawn Fees","tags":[{"category":"Overdrawn"},{"creditDebit":"debit"}]},{"date":"2019-12-31","text":"INTEREST","amount":-871.62,"type":"Interest Charge","tags":[{"category":"Fees"},{"creditDebit":"debit"}]},{"date":"2019-12-31","text":"LOAN SERVICE FEE","amount":-120,"type":"Loan Related Fees","tags":[{"category":"Fees"},{"creditDebit":"debit"}]},{"date":"2019-12-18","text":"PERIODICAL PAYMENT","amount":3397,"type":"","tags":[{"institution":"University of MC"},{"lenderType":"private"},{"category":"birdy"},{"creditDebit":"credit"}]},{"date":"2019-12-02","text":"LINE FEE","amount":-498.34,"type":"Overdrawn Fees","tags":[{"category":"Overdrawn"},{"creditDebit":"debit"}]},{"date":"2019-11-29","text":"INTEREST","amount":-794.4,"type":"Interest Charge","tags":[{"category":"Fees"},{"creditDebit":"debit"}]},{"date":"2019-11-19","text":"PERIODICAL PAYMENT","amount":3397,"type":"","tags":[{"institution":"University of MC"},{"lenderType":"private"},{"category":"birdy"},{"creditDebit":"credit"}]},{"date":"2019-11-01","text":"LINE FEE","amount":-484.87,"type":"Overdrawn Fees","tags":[{"category":"Overdrawn"},{"creditDebit":"debit"}]},{"date":"2019-10-31","text":"INTEREST","amount":-882.04,"type":"Interest Charge","tags":[{"category":"Fees"},{"creditDebit":"debit"}]},{"date":"2019-10-21","text":"PERIODICAL PAYMENT","amount":3397,"type":"","tags":[{"institution":"University of MC"},{"lenderType":"private"},{"category":"birdy"},{"creditDebit":"credit"}]},{"date":"2019-10-01","text":"LINE FEE","amount":-503.59,"type":"Overdrawn Fees","tags":[{"category":"Overdrawn"},{"creditDebit":"debit"}]},{"date":"2019-09-30","text":"INTEREST","amount":-916.98,"type":"Interest Charge","tags":[{"category":"Fees"},{"creditDebit":"debit"}]},{"date":"2019-09-30","text":"LOAN SERVICE FEE","amount":-120,"type":"Loan Related Fees","tags":[{"category":"Fees"},{"creditDebit":"debit"}]},{"date":"2019-09-19","text":"PERIODICAL PAYMENT","amount":3397,"type":"","tags":[{"institution":"University of MC"},{"lenderType":"private"},{"category":"birdy"},{"creditDebit":"credit"}]},{"date":"2019-09-02","text":"LINE FEE","amount":-489.65,"type":"Overdrawn Fees","tags":[{"category":"Overdrawn"},{"creditDebit":"debit"}]},{"date":"2019-08-30","text":"INTEREST","amount":-892.13,"type":"Interest Charge","tags":[{"category":"Fees"},{"creditDebit":"debit"}]}]}]}}
</code>```

and this is how I have been able to do so far:

```<code>import json
import numpy as np
import pandas as pd

with open('question.json') as json_data:
    d = json.load(json_data)

df = pd.json_normalize(d['b_data']['b_Acc'])

frames = []

#https://pandas.pydata.org/pandas-docs/stable/merging.html
for index, row in df.iterrows():
    frames = frames + row['transactions']

df_new = pd.DataFrame(frames)

df['category'] = df_new['tags'].apply(pd.Series)[0]
</code>```

This chould potentially work if category is always the first element of that array, however in raw 0 the first element is institution, the second raw is creditDebit (which i would like to be unknow as there is no category)

答:
This will do what you did in for loop</p>

```<code>s=pd.DataFrame(pd.DataFrame(df.transactions.tolist()).stack().str['tags'].tolist())
</code>```

Body:
I am trying to create/add a new column into the following dataframe (df_new):

I want this new column (df['category']) to be feed from df['tags'].

The tags columns, is a list of objects, and the value that I want to retrieve is the category, and if there is no category I want to set it as unknown.

This is a sample of my JSON file

{"submissionTime":"2019-02-25T09:26:00","b_data":{"bName":"Masato","b_Acc":[{"id":0,"transactions":[{"date":"2019-12-19","text":"PERIODICAL PAYMENT","amount":3397,"type":"","tags":[{"institution":"University of MC"},{"lenderType":"private"},{"category":"birdy"},{"creditDebit":"credit"}]},{"date":"2019-12-03","text":"LINE FEE","amount":-460.21,"type":"Overdrawn Fees","tags":[{"category":"Overdrawn"},{"creditDebit":"debit"}]},{"date":"2019-12-31","text":"INTEREST","amount":-871.62,"type":"Interest Charge","tags":[{"category":"Fees"},{"creditDebit":"debit"}]},{"date":"2019-12-31","text":"LOAN SERVICE FEE","amount":-120,"type":"Loan Related Fees","tags":[{"category":"Fees"},{"creditDebit":"debit"}]},{"date":"2019-12-18","text":"PERIODICAL PAYMENT","amount":3397,"type":"","tags":[{"institution":"University of MC"},{"lenderType":"private"},{"category":"birdy"},{"creditDebit":"credit"}]},{"date":"2019-12-02","text":"LINE FEE","amount":-498.34,"type":"Overdrawn Fees","tags":[{"category":"Overdrawn"},{"creditDebit":"debit"}]},{"date":"2019-11-29","text":"INTEREST","amount":-794.4,"type":"Interest Charge","tags":[{"category":"Fees"},{"creditDebit":"debit"}]},{"date":"2019-11-19","text":"PERIODICAL PAYMENT","amount":3397,"type":"","tags":[{"institution":"University of MC"},{"lenderType":"private"},{"category":"birdy"},{"creditDebit":"credit"}]},{"date":"2019-11-01","text":"LINE FEE","amount":-484.87,"type":"Overdrawn Fees","tags":[{"category":"Overdrawn"},{"creditDebit":"debit"}]},{"date":"2019-10-31","text":"INTEREST","amount":-882.04,"type":"Interest Charge","tags":[{"category":"Fees"},{"creditDebit":"debit"}]},{"date":"2019-10-21","text":"PERIODICAL PAYMENT","amount":3397,"type":"","tags":[{"institution":"University of MC"},{"lenderType":"private"},{"category":"birdy"},{"creditDebit":"credit"}]},{"date":"2019-10-01","text":"LINE FEE","amount":-503.59,"type":"Overdrawn Fees","tags":[{"category":"Overdrawn"},{"creditDebit":"debit"}]},{"date":"2019-09-30","text":"INTEREST","amount":-916.98,"type":"Interest Charge","tags":[{"category":"Fees"},{"creditDebit":"debit"}]},{"date":"2019-09-30","text":"LOAN SERVICE FEE","amount":-120,"type":"Loan Related Fees","tags":[{"category":"Fees"},{"creditDebit":"debit"}]},{"date":"2019-09-19","text":"PERIODICAL PAYMENT","amount":3397,"type":"","tags":[{"institution":"University of MC"},{"lenderType":"private"},{"category":"birdy"},{"creditDebit":"credit"}]},{"date":"2019-09-02","text":"LINE FEE","amount":-489.65,"type":"Overdrawn Fees","tags":[{"category":"Overdrawn"},{"creditDebit":"debit"}]},{"date":"2019-08-30","text":"INTEREST","amount":-892.13,"type":"Interest Charge","tags":[{"category":"Fees"},{"creditDebit":"debit"}]}]}]}}

and this is how I have been able to do so far:

import json
import numpy as np
import pandas as pd

with open('question.json') as json_data:
    d = json.load(json_data)

df = pd.json_normalize(d['b_data']['b_Acc'])

frames = []

#https://pandas.pydata.org/pandas-docs/stable/merging.html
for index, row in df.iterrows():
    frames = frames + row['transactions']

df_new = pd.DataFrame(frames)

df['category'] = df_new['tags'].apply(pd.Series)[0]

This chould potentially work if category is always the first element of that array, however in raw 0 the first element is institution, the second raw is creditDebit (which i would like to be unknow as there is no category)

Body:
This will do what you did in for loop

s=pd.DataFrame(pd.DataFrame(df.transactions.tolist()).stack().str['tags'].tolist())


来源: stackexchange

问:
Automatically increment value by search /compare and match two columns in Google Sheets Script
I currently have to manually enter Sheet1 column B, but I'd like to auto increment it every time the script runs.

I am using a Google Sheets script.

This part is working.

How it works:
Sheet2 column A is a drop down list imported from Sheet1 column A

if Sheet2 column B is anniversary of todays date Sheet 2 column F is automated to be 'reset'

the working script then deletes the rows in Sheet 2 where F is 'reset' and adds new rows for each to the bottom

Currently using this script

```<code>function writeupReset() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  var s = ss.getSheetByName('Sheet2');
  var r = s.getRange('C:C');
  var v = r.getValues();

  for(var i=v.length-1;i>=0;i--){
    if(v[0,i]=='reset'){
      s.insertRowsAfter(251,1);
      s.deleteRow(i+1);
    }
  }
}
</code>```

Example of the working bits using todays date - 6/2/20

```<code>      Sheet1                Sheet2  (before script)           Sheet2  (after script)

      A      B              A       B         C               A       B         C
  |---------------|     |-------------------------|       |-------------------------|
1 | name | resets |   1 | name  |  date   | delet |     1 | name  |  date   | delet |
  |---------------|     |-------------------------|       |-------------------------|
2 | bill |   1    |   2 | bill  | 6/2/19  | reset |     2 | alex  |  9/5/19 |       |
  |---------------|     |-------------------------|       |-------------------------|
3 | mark |   5    |   3 | alex  |  9/5/19 |       |     3 | adam  | 11/6/19 |       |
  |---------------|     |-------------------------|       |-------------------------|
4 | holy |   2    |   4 | adam  | 11/6/19 |       |     4 | tony  | 12/1/19 |       |
  |---------------|     |-------------------------|       |-------------------------|
5 | tony |   0    |   5 | mark  | 6/2/19  | reset |     5 |       |         |       |
  |---------------|     |-------------------------|       |-------------------------|
6 | alex |   2    |   6 | tony  | 12/1/19 |       |     6 |       |         |       |
  |---------------|     |-------------------------|       |-------------------------|
7 | june |   1    |   7 |       |         |       |     7 |       |         |       |
  |---------------|     |-------------------------|       |-------------------------|
8 | jack |   0    |   to 252 rows (last two hidden)     to 252 rows (last two hidden)
  |---------------|
9 | adam |   2    |
  |---------------|
</code>```

So how can I edit the script to automatically increment Sheet1 column B when the script deletes those 'reset' rows in Sheet1?

答:
I believe your goal as follows.

You want to increase the values of the column "B", that the name is the same , in "Sheet1" when the rows with reset in "Sheet2" are deleted by the script.

In your case, the same names are included in the column "A" in "Sheet2".

You want to achieve this by modifying your script in your question.

For this, how about this answer?

Modification points:

In this case, it is required to know the values of "Sheet1" and compare them with the values of "Sheet2". The flow is as follows.

Delete rows in "Sheet2".

At that time, an object including the information of the deleted rows is created.

Increase values of the column "B" in "Sheet1".

The values of the column "B" are updated using the object, and the updated values are put to the sheet.

When above points are reflected to your script, it becomes as follows.

Modified script:

```<code>function writeupReset() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // 1. Delete rows in Sheet2.
  var s = ss.getSheetByName('Sheet2');
  var r = s.getRange('A1:C' + s.getLastRow());  // Modified
  var v = r.getValues();
  var obj = {};  // Added
  for(var i=v.length-1;i>=0;i--){
    if(v[i][2] == 'reset') {  // Modified
      s.insertRowsAfter(251,1);
      s.deleteRow(i+1);
      var name = v[i][0]  // Added
      obj[name] = obj[name] ? obj[name] + 1 : 1;  // Added
    }
  }

  // I added below script.
  // 2. Increase values of the column "B" in Sheet1.
  var sheet = ss.getSheetByName("Sheet1");
  var range = sheet.getRange("A2:B" + sheet.getLastRow());
  var values = range.getValues().map(([a, b]) => ([obj[a] ? b += obj[a] : b]));
  range.offset(0, 1, values.length, 1).setValues(values);
}
</code>```

Note:

In this modified script, it supposes that each value of the column "A" in "Sheet1" is the unique value in all values. From your question, I could understand like this.

If the sheet names of "Sheet1" and "Sheet2" are different from your actual situation, please modify them.

If your actual situation is different from the structure of your sample values in your question, this modified script might not work. So please be careful this.

References:

map()

setValues(values)

ContentLicense: CC BY-SA 4.0

Body:
I currently have to manually enter Sheet1 column B, but I'd like to auto increment it every time the script runs.

I am using a Google Sheets script.

This part is working.

How it works:
Sheet2 column A is a drop down list imported from Sheet1 column A

if Sheet2 column B is anniversary of todays date Sheet 2 column F is automated to be 'reset'

the working script then deletes the rows in Sheet 2 where F is 'reset' and adds new rows for each to the bottom

Currently using this script

function writeupReset() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  var s = ss.getSheetByName('Sheet2');
  var r = s.getRange('C:C');
  var v = r.getValues();

  for(var i=v.length-1;i>=0;i--){
    if(v[0,i]=='reset'){
      s.insertRowsAfter(251,1);
      s.deleteRow(i+1);
    }
  }
}

Example of the working bits using todays date - 6/2/20

      Sheet1                Sheet2  (before script)           Sheet2  (after script)

      A      B              A       B         C               A       B         C
  |---------------|     |-------------------------|       |-------------------------|
1 | name | resets |   1 | name  |  date   | delet |     1 | name  |  date   | delet |
  |---------------|     |-------------------------|       |-------------------------|
2 | bill |   1    |   2 | bill  | 6/2/19  | reset |     2 | alex  |  9/5/19 |       |
  |---------------|     |-------------------------|       |-------------------------|
3 | mark |   5    |   3 | alex  |  9/5/19 |       |     3 | adam  | 11/6/19 |       |
  |---------------|     |-------------------------|       |-------------------------|
4 | holy |   2    |   4 | adam  | 11/6/19 |       |     4 | tony  | 12/1/19 |       |
  |---------------|     |-------------------------|       |-------------------------|
5 | tony |   0    |   5 | mark  | 6/2/19  | reset |     5 |       |         |       |
  |---------------|     |-------------------------|       |-------------------------|
6 | alex |   2    |   6 | tony  | 12/1/19 |       |     6 |       |         |       |
  |---------------|     |-------------------------|       |-------------------------|
7 | june |   1    |   7 |       |         |       |     7 |       |         |       |
  |---------------|     |-------------------------|       |-------------------------|
8 | jack |   0    |   to 252 rows (last two hidden)     to 252 rows (last two hidden)
  |---------------|
9 | adam |   2    |
  |---------------|

So how can I edit the script to automatically increment Sheet1 column B when the script deletes those 'reset' rows in Sheet1?

Body:
I believe your goal as follows.

You want to increase the values of the column "B", that the name is the same , in "Sheet1" when the rows with reset in "Sheet2" are deleted by the script.

In your case, the same names are included in the column "A" in "Sheet2".

You want to achieve this by modifying your script in your question.

For this, how about this answer?

Modification points:

In this case, it is required to know the values of "Sheet1" and compare them with the values of "Sheet2". The flow is as follows.

Delete rows in "Sheet2".

At that time, an object including the information of the deleted rows is created.

Increase values of the column "B" in "Sheet1".

The values of the column "B" are updated using the object, and the updated values are put to the sheet.

When above points are reflected to your script, it becomes as follows.

Modified script:

function writeupReset() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // 1. Delete rows in Sheet2.
  var s = ss.getSheetByName('Sheet2');
  var r = s.getRange('A1:C' + s.getLastRow());  // Modified
  var v = r.getValues();
  var obj = {};  // Added
  for(var i=v.length-1;i>=0;i--){
    if(v[i][2] == 'reset') {  // Modified
      s.insertRowsAfter(251,1);
      s.deleteRow(i+1);
      var name = v[i][0]  // Added
      obj[name] = obj[name] ? obj[name] + 1 : 1;  // Added
    }
  }

  // I added below script.
  // 2. Increase values of the column "B" in Sheet1.
  var sheet = ss.getSheetByName("Sheet1");
  var range = sheet.getRange("A2:B" + sheet.getLastRow());
  var values = range.getValues().map(([a, b]) => ([obj[a] ? b += obj[a] : b]));
  range.offset(0, 1, values.length, 1).setValues(values);
}

Note:

In this modified script, it supposes that each value of the column "A" in "Sheet1" is the unique value in all values. From your question, I could understand like this.

If the sheet names of "Sheet1" and "Sheet2" are different from your actual situation, please modify them.

If your actual situation is different from the structure of your sample values in your question, this modified script might not work. So please be careful this.

References:

map()

setValues(values)


问:
Name Data does not import into Rstudio as intended
I'm currently trying to import a data set of names into RStudio. I have the data saved as a .csv file with 276 rows. In Microsoft Excel it looks like this:

When I try to import into RStudio, (from Text), it gives me this window:

Then, when trying to import the data I receive the following error:

"Error in read.table(file = file, header = header, sep = sep, quote = quote,  :
    duplicate 'row.names' are not allowed"

The data appears in RStudio like this:

If a person has 3 names (a few do) they appear on the next line by themselves. Why is my data doing this? I want both first and last names to be in the same column with the heading "person".

Thank you in advance for any help you can provide!

答:
If you want to use RStudio's Import Data > From Text you need to set Row names to "Use numbers" and Separator to "Semicolon".

Row names set to "Automatic" is what is causing the error you're referencing.  By being set to "Automatic", RStudio is importing what it interprets as the first column as row labels for the data frame.  In this case, RStudio is trying to use first names as the row labels for your data (more on why this is happening below).  This is an issue because your data contains multiple individuals with the same first name.  Put another way, a data frame cannot have two row 1's therefore it cannot have two row John's.

Separator set to "Whitespace" is splitting your names where ever there is white space in the data; the spaces between names count as white space. Setting Separator to "Semicolon" ensures full names are not split.

Note: using "Comma" can split names that have a suffix (such as "Josh Smith, Jr." which would be separated to be "John Smith" and "Jr.").

Alternatively, you can use the read.csv() function like this:

```<code>df <- read.csv("starpower.csv", row.names = FALSE, sep = ";")
</code>```

The above line of code will import your .csv file located at path starpower.csv, it tells RStudio your data does not have row labels (therefore RStudio will default to numbering each row itself), and it changes the default way of reading your data from entries in a row being separated by commas (,) to semicolons (;).  Again, semicolons are likely a better separator for you to use since your data is a single column that may contain commas.

Note: if your data contains multiple columns you must set Seperator when using RStudio's Import Data tool and sep = when using the read.csv() function to the symbol that is used to separate rows in your data.  The default for .csv files is commas (,).

I hope this helps!

Body:
If you want to use RStudio's Import Data > From Text you need to set Row names to "Use numbers" and Separator to "Semicolon".

Row names set to "Automatic" is what is causing the error you're referencing.  By being set to "Automatic", RStudio is importing what it interprets as the first column as row labels for the data frame.  In this case, RStudio is trying to use first names as the row labels for your data (more on why this is happening below).  This is an issue because your data contains multiple individuals with the same first name.  Put another way, a data frame cannot have two row 1's therefore it cannot have two row John's.

Separator set to "Whitespace" is splitting your names where ever there is white space in the data; the spaces between names count as white space. Setting Separator to "Semicolon" ensures full names are not split.

Note: using "Comma" can split names that have a suffix (such as "Josh Smith, Jr." which would be separated to be "John Smith" and "Jr.").

Alternatively, you can use the read.csv() function like this:

df <- read.csv("starpower.csv", row.names = FALSE, sep = ";")

The above line of code will import your .csv file located at path starpower.csv, it tells RStudio your data does not have row labels (therefore RStudio will default to numbering each row itself), and it changes the default way of reading your data from entries in a row being separated by commas (,) to semicolons (;).  Again, semicolons are likely a better separator for you to use since your data is a single column that may contain commas.

Note: if your data contains multiple columns you must set Seperator when using RStudio's Import Data tool and sep = when using the read.csv() function to the symbol that is used to separate rows in your data.  The default for .csv files is commas (,).

I hope this helps!


问:
Trying to print out step by step in a recursive function without printing them out all at once in Javascript
I'm trying to make an N-Queens visualizer and I hooked up my solver to the html doc. My issue is that I'm trying to display everything step by step with intervals of 1 second each for the place function, rather than showing the completed solutions right away.

In other words, I want to show each move done step by step.

My placing function, is also hooked up to the tables on the DOM so when it's being placed on the board, it also places it on the html table.

```<code>function place(board, row, col, val, table) {
  const newRow = board[row].split('');
  newRow[col] = val;
  board[row] = newRow.join('');
  //place on DOM as well
  table.childNodes[row].childNodes[col].innerHTML = val;
}
</code>```

and the code I have for my solver is this

```<code>function solver(board, row, col, solutions) {
  if (col === board.length) {
    solutions.push([...board]);
    return;
  }

  const currentTable = listOfTables[solutions.length];

  for (let i = 0; i < board.length; i++) {
    if (canPlace(board, i, col)) {
      place(board, i, col, 'Q', currentTable);
      solver(board, row, col + 1, solutions);
      place(board, i, col, '.', currentTable);
    }
  }
}
</code>```

I was trying to wrap a setTimeout inside the solver function but that still runs the code all at once, when the timeout hits.

The currentTable variable is the used to know which of the tables in the DOM is currently going to be in use.

Here's the CodePen with all the code if anyone needs it https://codepen.io/vvus/pen/KKVKMrq?editors=1111

答:
you can adjust the code bellow to your liking

you add the display="none" to all your tables and then you deactivate the attribute in a time interval using this code

```<code>var i=0

setInterval(() => {
          for(z=i;z<listOfTables.length;z++)  {
    const x=document.getElementsByClassName('new-table')[z]
          if (x.style.display === "none") {
              x.style.display = "";
                       i++
          }
               break
                       }
            }, 3000);
</code>```

so your final code may look like this

```<code>const button = document.getElementById("button-click");
    const selection = document.getElementById("selection");
    let tablesContainer = document.getElementById("tables-container");
    let listOfTables = tablesContainer.childNodes;

    button.addEventListener("click", () => {
      console.log(nQueens(Number(selection.value)));

      listOfTables = tablesContainer.childNodes;
     // add this code to your eventlistner or anywhre you want to show something in time interval
      var i=0
       setInterval(() => {

          for(z=i;z<listOfTables.length;z++)  {
    const x=document.getElementsByClassName('new-table')[z]

          console.log(z)
          if (x.style.display === "none") {
              x.style.display = "";
                       i++
          }
               break
                       }
            }, 3000);

    });

    selection.addEventListener("change", (e) => {
      let numOfTables = e.target.value;

      if (numOfTables === 1) numOfTables = 1;
      else if (numOfTables === 4) numOfTables = 3;
      else if (numOfTables === 8) numOfTables = 93;

      const rowsCols = e.target.value;
      for (let allTables = 1; allTables < numOfTables; allTables++) {
        const newTable = document.createElement("table");
        newTable.classList = "new-table";
        newTable.style.display="none"// add this attribute to all your tables
        for (let i = 0; i < rowsCols; i++) {
          const row = document.createElement("tr");

          for (let j = 0; j < rowsCols; j++) {
            const th = document.createElement("th");
            th.innerHTML = ".";
            row.appendChild(th);
          }
          newTable.appendChild(row);
        }
        tablesContainer.appendChild(newTable);
      }
    });
</code>```

Body:
I'm trying to make an N-Queens visualizer and I hooked up my solver to the html doc. My issue is that I'm trying to display everything step by step with intervals of 1 second each for the place function, rather than showing the completed solutions right away.

In other words, I want to show each move done step by step.

My placing function, is also hooked up to the tables on the DOM so when it's being placed on the board, it also places it on the html table.

function place(board, row, col, val, table) {
  const newRow = board[row].split('');
  newRow[col] = val;
  board[row] = newRow.join('');
  //place on DOM as well
  table.childNodes[row].childNodes[col].innerHTML = val;
}

and the code I have for my solver is this

function solver(board, row, col, solutions) {
  if (col === board.length) {
    solutions.push([...board]);
    return;
  }

  const currentTable = listOfTables[solutions.length];

  for (let i = 0; i < board.length; i++) {
    if (canPlace(board, i, col)) {
      place(board, i, col, 'Q', currentTable);
      solver(board, row, col + 1, solutions);
      place(board, i, col, '.', currentTable);
    }
  }
}

I was trying to wrap a setTimeout inside the solver function but that still runs the code all at once, when the timeout hits.

The currentTable variable is the used to know which of the tables in the DOM is currently going to be in use.

Here's the CodePen with all the code if anyone needs it https://codepen.io/vvus/pen/KKVKMrq?editors=1111

Body:
you can adjust the code bellow to your liking

you add the display="none" to all your tables and then you deactivate the attribute in a time interval using this code

var i=0

setInterval(() => {
          for(z=i;z<listOfTables.length;z++)  {
    const x=document.getElementsByClassName('new-table')[z]
          if (x.style.display === "none") {
              x.style.display = "";
                       i++
          }
               break
                       }
            }, 3000);

so your final code may look like this

const button = document.getElementById("button-click");
    const selection = document.getElementById("selection");
    let tablesContainer = document.getElementById("tables-container");
    let listOfTables = tablesContainer.childNodes;

    button.addEventListener("click", () => {
      console.log(nQueens(Number(selection.value)));

      listOfTables = tablesContainer.childNodes;
     // add this code to your eventlistner or anywhre you want to show something in time interval
      var i=0
       setInterval(() => {

          for(z=i;z<listOfTables.length;z++)  {
    const x=document.getElementsByClassName('new-table')[z]

          console.log(z)
          if (x.style.display === "none") {
              x.style.display = "";
                       i++
          }
               break
                       }
            }, 3000);

    });

    selection.addEventListener("change", (e) => {
      let numOfTables = e.target.value;

      if (numOfTables === 1) numOfTables = 1;
      else if (numOfTables === 4) numOfTables = 3;
      else if (numOfTables === 8) numOfTables = 93;

      const rowsCols = e.target.value;
      for (let allTables = 1; allTables < numOfTables; allTables++) {
        const newTable = document.createElement("table");
        newTable.classList = "new-table";
        newTable.style.display="none"// add this attribute to all your tables
        for (let i = 0; i < rowsCols; i++) {
          const row = document.createElement("tr");

          for (let j = 0; j < rowsCols; j++) {
            const th = document.createElement("th");
            th.innerHTML = ".";
            row.appendChild(th);
          }
          newTable.appendChild(row);
        }
        tablesContainer.appendChild(newTable);
      }
    });


问:
run-time error 287 - Outlook when set inspector.wordeditor
```<code>Set oApp = CreateObject("Outlook.Application")

Set oMailItem = oApp.CreateItem(0)

oMailItem.BodyFormat = olFormatRichText

Set oInspector = oMailItem.GetInspector

oInspector.Display

MsgBox "IsWordMail = " & oInspector.IsWordMail & vbLf & "EditorType = " & (oInspector.EditorType = olEditorWord) ' Both are true.
</code>```

Set wdDoc = oInspector.WordEditor '<--Run-time error '287' Appication-Defined or Object-Defined Error

option-mail- composer message in this format is "HTML"
outlook reference 16.0 is set up

答:
If the code suddenly stopped working after migrating to Office 365 or for any other reasons, please refer to the code below. Comments have been added for easy understanding and implementation.

If you have administrative rights then you can also try the registry changes given at below link:
https://support.microsoft.com/en-au/help/926512/information-for-administrators-about-e-mail-security-settings-in-outlo

However, I recommend a code that's Excel version independent of making system changes because system changes will be required on each end user's machine as well.

```<code>Option Explicit

Sub Create_Email(ByVal strTo As String, ByVal strSubject As String)

    Dim rngToPicture As Range
    Dim outlookApp As Object
    Dim Outmail As Object
    Dim strTempFilePath As String
    Dim strTempFileName As String

    'Name it anything, doesn't matter
    strTempFileName = "RangeAsPNG"

    'rngToPicture is defined as NAMED RANGE in the workbook, do modify this name before use
    Set rngToPicture = Range("rngToPicture")
    Set outlookApp = CreateObject("Outlook.Application")
    Set Outmail = outlookApp.CreateItem(olMailItem)

    'Create an email
    With Outmail
        .To = strTo
        .Subject = strSubject

        'Create the range as a PNG file and store it in temp folder
        Call createPNG(rngToPicture, strTempFileName)

        'Embed the image in Outlook
        strTempFilePath = Environ$("temp") & "\" & strTempFileName & ".png"
        .Attachments.Add strTempFilePath, olByValue, 0

        'Change the HTML below to add Header (Dear John) or signature (Kind Regards) using newline tag (<br />)
        .HTMLBody = "<img src='cid:DashboardFile.png' style='border:0'>"

        .Display

    End With

    Set Outmail = Nothing
    Set outlookApp = Nothing
    Set rngToPicture = Nothing

End Sub

Sub createPNG(ByRef rngToPicture As Range, nameFile As String)

    Dim wksName As String

    wksName = rngToPicture.Parent.Name

    'Delete the existing PNG file of same name, if exists
    On Error Resume Next
        Kill Environ$("temp") & "\" & nameFile & ".png"
    On Error GoTo 0

    'Copy the range as picture
    rngToPicture.CopyPicture

    'Paste the picture in Chart area of same dimensions
    With ThisWorkbook.Worksheets(wksName).ChartObjects.Add(rngToPicture.Left, rngToPicture.Top, rngToPicture.Width, rngToPicture.Height)
        .Activate
        .Chart.Paste
        'Export the chart as PNG File to Temp folder
        .Chart.Export Environ$("temp") & "\" & nameFile & ".png", "PNG"
    End With
    Worksheets(wksName).ChartObjects(Worksheets(wksName).ChartObjects.Count).Delete

End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Set oApp = CreateObject("Outlook.Application")

Set oMailItem = oApp.CreateItem(0)

oMailItem.BodyFormat = olFormatRichText

Set oInspector = oMailItem.GetInspector

oInspector.Display

MsgBox "IsWordMail = " & oInspector.IsWordMail & vbLf & "EditorType = " & (oInspector.EditorType = olEditorWord) ' Both are true.

Set wdDoc = oInspector.WordEditor '<--Run-time error '287' Appication-Defined or Object-Defined Error

option-mail- composer message in this format is "HTML"
outlook reference 16.0 is set up

Body:
If the code suddenly stopped working after migrating to Office 365 or for any other reasons, please refer to the code below. Comments have been added for easy understanding and implementation.

If you have administrative rights then you can also try the registry changes given at below link:
https://support.microsoft.com/en-au/help/926512/information-for-administrators-about-e-mail-security-settings-in-outlo

However, I recommend a code that's Excel version independent of making system changes because system changes will be required on each end user's machine as well.

Option Explicit

Sub Create_Email(ByVal strTo As String, ByVal strSubject As String)

    Dim rngToPicture As Range
    Dim outlookApp As Object
    Dim Outmail As Object
    Dim strTempFilePath As String
    Dim strTempFileName As String

    'Name it anything, doesn't matter
    strTempFileName = "RangeAsPNG"

    'rngToPicture is defined as NAMED RANGE in the workbook, do modify this name before use
    Set rngToPicture = Range("rngToPicture")
    Set outlookApp = CreateObject("Outlook.Application")
    Set Outmail = outlookApp.CreateItem(olMailItem)

    'Create an email
    With Outmail
        .To = strTo
        .Subject = strSubject

        'Create the range as a PNG file and store it in temp folder
        Call createPNG(rngToPicture, strTempFileName)

        'Embed the image in Outlook
        strTempFilePath = Environ$("temp") & "\" & strTempFileName & ".png"
        .Attachments.Add strTempFilePath, olByValue, 0

        'Change the HTML below to add Header (Dear John) or signature (Kind Regards) using newline tag (<br />)
        .HTMLBody = "<img src='cid:DashboardFile.png' style='border:0'>"

        .Display

    End With

    Set Outmail = Nothing
    Set outlookApp = Nothing
    Set rngToPicture = Nothing

End Sub

Sub createPNG(ByRef rngToPicture As Range, nameFile As String)

    Dim wksName As String

    wksName = rngToPicture.Parent.Name

    'Delete the existing PNG file of same name, if exists
    On Error Resume Next
        Kill Environ$("temp") & "\" & nameFile & ".png"
    On Error GoTo 0

    'Copy the range as picture
    rngToPicture.CopyPicture

    'Paste the picture in Chart area of same dimensions
    With ThisWorkbook.Worksheets(wksName).ChartObjects.Add(rngToPicture.Left, rngToPicture.Top, rngToPicture.Width, rngToPicture.Height)
        .Activate
        .Chart.Paste
        'Export the chart as PNG File to Temp folder
        .Chart.Export Environ$("temp") & "\" & nameFile & ".png", "PNG"
    End With
    Worksheets(wksName).ChartObjects(Worksheets(wksName).ChartObjects.Count).Delete

End Sub


问:
Ext js combobox does not display all items in menu
Can someone tell me how to get rid of the feature that filters combo box items.
when i click on the trigger of the combo, i want to display ALL menu items regardless of what text is already in the box, NOT filtered. I've tried several different config options with no luck.
make sense ?

for example, if i have 'View' as my text in the combo, and i click on the trigger, it will only show 'View1' and 'View2' items, i want it to include all the others...

Thanks!

heres my current config

```<code>    {
...
   items: [{
   xtype: 'combo',
   id: 'myViewsCombo',
   emptyText: 'Select View',
   selectOnFocus: true,
   listeners: {
   select: function(combo, record, index) {
            L3.handlers.loadView(combo.value);
  }},
   store: ['View1', 'View2','blahblah']
    }]
 }
</code>```

答: Setting triggerAction: "all" solved the same problem for me.

ContentLicense: CC BY-SA 2.5

Body:
Can someone tell me how to get rid of the feature that filters combo box items.
when i click on the trigger of the combo, i want to display ALL menu items regardless of what text is already in the box, NOT filtered. I've tried several different config options with no luck.
make sense ?

for example, if i have 'View' as my text in the combo, and i click on the trigger, it will only show 'View1' and 'View2' items, i want it to include all the others...

Thanks!

heres my current config

    {
...
   items: [{
   xtype: 'combo',
   id: 'myViewsCombo',
   emptyText: 'Select View',
   selectOnFocus: true,
   listeners: {
   select: function(combo, record, index) {
            L3.handlers.loadView(combo.value);
  }},
   store: ['View1', 'View2','blahblah']
    }]
 }


问:
Error: SyntaxError: Unexpected strict mode reserved word(…)..
app.template.html

```<code><div class="container">
   <div class="row">
      <div class="col-md-6 ">
         <button class= "btn btn-primary" (click)="onAddMessage()">RANDOM BUTTON</button>
      </div>
   </div>
</div>
<div class="container">
   <div class="row">
      <div class="col-md-6 ">
         <article class="panel panel-default" *ngFor = "let latestmessage of messages" >
            <div class="panel-body">
               {{ latestmessage.content }}
            </div>
         </article>
      </div>
   </div>
</div>
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';
import { Message } from './message.model';

@Component({
    moduleId: module.id,
    selector: 'my-app',
    templateUrl: 'app.template.html'
})
export class AppComponent {
    messages: Message[] = [
        new Message('hello')
    ];

    onAddMessage() {
        const rnd = Math.ceil(Math.random() * 100);
        const msg = new Message(rnd + ' is a awsome number');
        this.messages.push(msg);
    }
}
</code>```

message.model.ts

```<code>import { Component } from '@angular/core';

export class Message(){
    constructor(public content: string){}
}
</code>```

This code is build in angularjs2 and nodejs .I created a button.when i click on button it give me response like this hello     99 number is an awesome number.what is reserved word in this code?? anyone can help??

答: I got a similar error when I was using await but the nearest parent function was not async.

Body:
app.template.html

         <button class= "btn btn-primary" (click)="onAddMessage()">RANDOM BUTTON</button>

               {{ latestmessage.content }}

app.component.ts

import { Component } from '@angular/core';
import { Message } from './message.model';

@Component({
    moduleId: module.id,
    selector: 'my-app',
    templateUrl: 'app.template.html'
})
export class AppComponent {
    messages: Message[] = [
        new Message('hello')
    ];

    onAddMessage() {
        const rnd = Math.ceil(Math.random() * 100);
        const msg = new Message(rnd + ' is a awsome number');
        this.messages.push(msg);
    }
}

message.model.ts

import { Component } from '@angular/core';

export class Message(){
    constructor(public content: string){}
}

This code is build in angularjs2 and nodejs .I created a button.when i click on button it give me response like this hello     99 number is an awesome number.what is reserved word in this code?? anyone can help??


问:
Programmatically determine pip 'user install' location Scripts directory
As explained in pip's documentation a user can install packages in his personal account using pip install --user <pkg>.

How can I programmatically determine the user install location for scripts installed like this? I am talking about the directory that should be added to the PATH so that installed packages can be invoked from command line.

For example, in Windows when installing pip install -U pylint --user I get the following warning because I don't have 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts' in my PATH:

```<code>...
Installing collected packages: wrapt, six, typed-ast, lazy-object-proxy, astroid, mccabe, isort, colorama, toml, pylint
  Running setup.py install for wrapt ... done
  WARNING: The script isort.exe is installed in 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts epylint.exe, pylint.exe, pyreverse.exe and symilar.exe are installed in 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts' which is not on PATH.
</code>```

Is there some python code I can use to determine that location programmatically (that will work on Windows/Linux/Darwin/etc)? Something like:

```<code>def get_user_install_scripts_dir():
    ...
    # would return 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts'
    # on Windows with Python 3.7.x, '/home/myusername/.local/bin' in Linux, etc
    return platform_scripts_dir
</code>```

As a fallback, is there some command I can run to obtain this location? Something like (but for the script location not the site's base directory):

```<code>PS C:\Users\myusername\> python -m site --user-base
C:\Users\myusername\AppData\Roaming\Python

$ python -m site --user-base
/home/myusername/.local
</code>```

答:
Command-line:

```<code>python -c "import os, site; print(os.path.join(site.USER_BASE, 'Scripts' if os.name == 'nt' else 'bin'))"
</code>```

Function:

```<code>import os, site

if os.name == 'nt':
    bin_dir = 'Scripts'
else:
    bin_dir = 'bin'

def get_user_install_bin_dir():
    return os.path.join(site.USER_BASE, bin_dir)
</code>```

Body:
As explained in pip's documentation a user can install packages in his personal account using pip install --user <pkg>.

How can I programmatically determine the user install location for scripts installed like this? I am talking about the directory that should be added to the PATH so that installed packages can be invoked from command line.

For example, in Windows when installing pip install -U pylint --user I get the following warning because I don't have 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts' in my PATH:

...
Installing collected packages: wrapt, six, typed-ast, lazy-object-proxy, astroid, mccabe, isort, colorama, toml, pylint
  Running setup.py install for wrapt ... done
  WARNING: The script isort.exe is installed in 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts epylint.exe, pylint.exe, pyreverse.exe and symilar.exe are installed in 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts' which is not on PATH.

Is there some python code I can use to determine that location programmatically (that will work on Windows/Linux/Darwin/etc)? Something like:

def get_user_install_scripts_dir():
    ...
    # would return 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts'
    # on Windows with Python 3.7.x, '/home/myusername/.local/bin' in Linux, etc
    return platform_scripts_dir

As a fallback, is there some command I can run to obtain this location? Something like (but for the script location not the site's base directory):

PS C:\Users\myusername\> python -m site --user-base
C:\Users\myusername\AppData\Roaming\Python

$ python -m site --user-base
/home/myusername/.local

Body:
Command-line:

python -c "import os, site; print(os.path.join(site.USER_BASE, 'Scripts' if os.name == 'nt' else 'bin'))"

Function:

import os, site

if os.name == 'nt':
    bin_dir = 'Scripts'
else:
    bin_dir = 'bin'

def get_user_install_bin_dir():
    return os.path.join(site.USER_BASE, bin_dir)


问:
Which UserControl's calling Event MouseEnter?
I have a list of UserControl and I want to know which UserControl is calling event MouseEnter. I add multiple UserControls on TableLayoutPanel.

List<MyUserControl> form = new List<MyUserControl>();

for (int x = 0; x < dt.Rows.Count; x++)
{
    tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 200));
    if (x == 0)
       tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
    form.Add(new MyUserControl());
}

for (int x = 0; x < form.Count; x++)
{
    form[x].MouseEnter += new EventHandler(Form_MouseEnter);
    tableLayoutPanel1.Controls.Add(form[x], x, 0);
}
```

How do I find out which UserControl activated the event?

答:
The thing that should make the biggest difference is if you give a Name to your new MyUserControl because the default Name is an empty string. Could you try changing your code to this and see if it helps?

```<code>List<MyUserControl> form = new List<MyUserControl>();

for (int x = 0; x < 5; x++)
{
    tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 200));
    if (x == 0)
        tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));

    // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    // Here are the changes
    MyUserControl myUserControl = new MyUserControl();
    myUserControl.Name = "MyUserControl_" + x.ToString("D2"); // Name it! (Default is "")
    myUserControl.MouseEnter += MyUserControl_MouseEnter;     // Hook the MouseEnter here
    myUserControl.Codigo = 1000 + x;                          // Example to set Codigo
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    form.Add(myUserControl); // NOTE! This is changed from 'new MyUserControl()'.
}

for (int x = 0; x < form.Count; x++)
{
    tableLayoutPanel1.Controls.Add(form[x], x, 0);
}
</code>```

Now the handler looks like this:

```<code>private void MyUserControl_MouseEnter(object sender, EventArgs e)
{
    MyUserControl myUserControl = (MyUserControl)sender;
    Debug.WriteLine(
        "MouseEnter Detected: " + myUserControl.Name +
        " - Value of Codigo is: " + myUserControl.Codigo);
}
</code>```

... where (based on your comment about Codigo) ...

```<code>class MyUserControl : UserControl
{
    public int Codigo
    {
        set
        {
            test = value;
        }
        get
        {
            return test;
        }
    }
    int test = 0;
    // Of course there is more implementation of MyUserControl that follows...
}
</code>```

I really hope this helps you fix the problem you're having.

Body:
I have a list of UserControl and I want to know which UserControl is calling event MouseEnter. I add multiple UserControls on TableLayoutPanel.

List<MyUserControl> form = new List<MyUserControl>();

for (int x = 0; x < dt.Rows.Count; x++)
{
    tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 200));
    if (x == 0)
       tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
    form.Add(new MyUserControl());
}

for (int x = 0; x < form.Count; x++)
{
    form[x].MouseEnter += new EventHandler(Form_MouseEnter);
    tableLayoutPanel1.Controls.Add(form[x], x, 0);
}

How do I find out which UserControl activated the event?

Body:
The thing that should make the biggest difference is if you give a Name to your new MyUserControl because the default Name is an empty string. Could you try changing your code to this and see if it helps?

List<MyUserControl> form = new List<MyUserControl>();

for (int x = 0; x < 5; x++)
{
    tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 200));
    if (x == 0)
        tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));

    // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    // Here are the changes
    MyUserControl myUserControl = new MyUserControl();
    myUserControl.Name = "MyUserControl_" + x.ToString("D2"); // Name it! (Default is "")
    myUserControl.MouseEnter += MyUserControl_MouseEnter;     // Hook the MouseEnter here
    myUserControl.Codigo = 1000 + x;                          // Example to set Codigo
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    form.Add(myUserControl); // NOTE! This is changed from 'new MyUserControl()'.
}

for (int x = 0; x < form.Count; x++)
{
    tableLayoutPanel1.Controls.Add(form[x], x, 0);
}

Now the handler looks like this:

private void MyUserControl_MouseEnter(object sender, EventArgs e)
{
    MyUserControl myUserControl = (MyUserControl)sender;
    Debug.WriteLine(
        "MouseEnter Detected: " + myUserControl.Name +
        " - Value of Codigo is: " + myUserControl.Codigo);
}

... where (based on your comment about Codigo) ...

class MyUserControl : UserControl
{
    public int Codigo
    {
        set
        {
            test = value;
        }
        get
        {
            return test;
        }
    }
    int test = 0;
    // Of course there is more implementation of MyUserControl that follows...
}

I really hope this helps you fix the problem you're having.


问:
How to change a TouchableOpacity color with MapView region change?
Consider this code:

    import React, { useState, useEffect } from 'react';
    import { StyleSheet, Image, View, ScrollView, Text, FlatList, TouchableOpacity } from 'react-native';
    import MapView, { Marker } from 'react-native-maps';
    import {requestPermissionsAsync, getCurrentPositionAsync} from 'expo-location';
    import { TouchableHighlight, TextInput } from 'react-native-gesture-handler';
    import { MaterialIcons } from '@expo/vector-icons';

    import SearchBar from '../../components/searchInput';

    function Main(){
    const[currentRegion, setCurrentRegion ] = useState(null);
        var color = 'red';
        function changeColor(){
            color = 'blue';
        };

        useEffect(()=>{
            async function loadInitialPosition() {
                const { granted } = await requestPermissionsAsync();

                if(granted){
                    const { coords } = await getCurrentPositionAsync({
                        enableHighAccuracy: true,
                    });

                    const { latitude, longitude } = coords;
                    userCoords = coords;
                    setCurrentRegion({
                        latitude,
                        longitude,
                        latitudeDelta: 0.01,
                        longitudeDelta: 0.01,
                    })
                }
            }
        return (
        <>
            <MapView
            ref = {(mapView) => { map = mapView; }}
            onRegionChange={()=>{
                changeColor()
            }}
            initialRegion={ currentRegion }
            style={styles.map}
             customMapStyle={Mapstyle}
             showsMyLocationButton={true}
             showsUserLocation={true}
             >
                 {satiros.localizarSatiros()}

            </MapView>
            <View style={styles.searchContainer}>
                <SearchBar/>
            </View>
            <View style={styles.extraMap}>
                <TouchableHighlight onPress={() => {}} style={styles.touchable}>
                    <MaterialIcons name="search" size={25} color="#9BAED4"  />
                </TouchableHighlight>
                <TouchableHighlight onPress={()=>{
                   mapboxModule.centralizarLocalizacao(map,userCoords.latitude,userCoords.longitude,60)
                }} style={styles.touchable2}>
                    <MaterialIcons name="my-location" size={25} color="#9BAED4"  />
                </TouchableHighlight>
            </View>
            <ScrollView pagingEnabled horizontal style={styles.scrollCards} showsHorizontalScrollIndicator={false}>
                {
                    images.map((item, index) => (
                        <TouchableOpacity
                        activeOpacity={0.6}
                        style={[styles.cardSlide,{backgroundColor:color}]}
                        >
                            <Image key={index} source={{ uri: item}}
                            style={styles.imagesCard}/>
                            <Text style={styles.cardTitle}>{MapSlide.card.nome}</Text>
                            <Text style={styles.cardSubTitle}>{MapSlide.card.desc}</Text>
                        </TouchableOpacity >
                    ))
                }
            </ScrollView>
        </>
        );
    }

    const styles = StyleSheet.create(styleJaja)

    export default Main;
```

I want to change backgroundColor value of TouchableOpacity when user moves the map.
To detect if he's moving, I use 'onRegionChange', which calls the function 'changeColor', than changes 'color' variable to blue. So far so good. 'color' variable value really changes.

But that change doesn't affect the color of backgroundColor, only the variable.
Any idea?

答:
Maybe you could try to create a new useState to control and set color like :

const[color, setColor ] = useState('red');
```

<p>and</p>

<pre class="lang-js prettyprint-override"><code>changeColor(){ setColor ('blue'); };
</code>```

Body:
Consider this code:

    import React, { useState, useEffect } from 'react';
    import { StyleSheet, Image, View, ScrollView, Text, FlatList, TouchableOpacity } from 'react-native';
    import MapView, { Marker } from 'react-native-maps';
    import {requestPermissionsAsync, getCurrentPositionAsync} from 'expo-location';
    import { TouchableHighlight, TextInput } from 'react-native-gesture-handler';
    import { MaterialIcons } from '@expo/vector-icons';

    import SearchBar from '../../components/searchInput';

    function Main(){
    const[currentRegion, setCurrentRegion ] = useState(null);
        var color = 'red';
        function changeColor(){
            color = 'blue';
        };

        useEffect(()=>{
            async function loadInitialPosition() {
                const { granted } = await requestPermissionsAsync();

                if(granted){
                    const { coords } = await getCurrentPositionAsync({
                        enableHighAccuracy: true,
                    });

                    const { latitude, longitude } = coords;
                    userCoords = coords;
                    setCurrentRegion({
                        latitude,
                        longitude,
                        latitudeDelta: 0.01,
                        longitudeDelta: 0.01,
                    })
                }
            }
        return (
        <>
            <MapView
            ref = {(mapView) => { map = mapView; }}
            onRegionChange={()=>{
                changeColor()
            }}
            initialRegion={ currentRegion }
            style={styles.map}
             customMapStyle={Mapstyle}
             showsMyLocationButton={true}
             showsUserLocation={true}
             >
                 {satiros.localizarSatiros()}

            </MapView>
            <View style={styles.searchContainer}>
                <SearchBar/>
            </View>
            <View style={styles.extraMap}>
                <TouchableHighlight onPress={() => {}} style={styles.touchable}>
                    <MaterialIcons name="search" size={25} color="#9BAED4"  />
                </TouchableHighlight>
                <TouchableHighlight onPress={()=>{
                   mapboxModule.centralizarLocalizacao(map,userCoords.latitude,userCoords.longitude,60)
                }} style={styles.touchable2}>
                    <MaterialIcons name="my-location" size={25} color="#9BAED4"  />
                </TouchableHighlight>
            </View>
            <ScrollView pagingEnabled horizontal style={styles.scrollCards} showsHorizontalScrollIndicator={false}>
                {
                    images.map((item, index) => (
                        <TouchableOpacity
                        activeOpacity={0.6}
                        style={[styles.cardSlide,{backgroundColor:color}]}
                        >
                            <Image key={index} source={{ uri: item}}
                            style={styles.imagesCard}/>
                            <Text style={styles.cardTitle}>{MapSlide.card.nome}</Text>
                            <Text style={styles.cardSubTitle}>{MapSlide.card.desc}</Text>
                        </TouchableOpacity >
                    ))
                }
            </ScrollView>
        </>
        );
    }

    const styles = StyleSheet.create(styleJaja)

    export default Main;

I want to change backgroundColor value of TouchableOpacity when user moves the map.
To detect if he's moving, I use 'onRegionChange', which calls the function 'changeColor', than changes 'color' variable to blue. So far so good. 'color' variable value really changes.

But that change doesn't affect the color of backgroundColor, only the variable.
Any idea?

Body:
Maybe you could try to create a new useState to control and set color like :

const[color, setColor ] = useState('red');

and

changeColor(){ setColor ('blue'); };


问:
Create a view which joins on a comma separated value
I request help for my homework in SQL.

I have a table with musical instruments:

```<code>id  instrument_name         instrument_at_shops
-----------------------------------------------
1   Electric Guitar         1;2;3;4;
2   Midi Keyboard           1;3;
3   Tom Drum                2;
4   Electric Guitar         1;
5   Electric Guitar         0;
</code>```

And a table with shops:

```<code>shop_id  shop_name  shop_address
-----------------------------------------------
1        Shop1      City1 Street 1, building 1
2        Shop2      City1 Street 5, building 4
3        Shop3      City2 Street 4, building 4
4        Shop4      City3 Street 10, building 7
</code>```

In my musical instruments table I have several numbers which represent id's of the shops that have the particular instrument.

The problem is: how to create a view which contains a shop name and an instrument which is in this shop?

The logic is this:

```<code>SELECT shop_name, instrument_name
FROM Shop
CROSS JOIN Instrument
WHERE instrumet_at_shops CONTAINS shop_id
</code>```

But I cannot create an appropriate query or view design.

Thank you in advance!

答:
You should really put your effort into fixing the data model.  It is broken, broken, broken:

Do not store multiple values in a string.

Do not store numbers are strings.

Foreign key relationships should be properly declared.

SQL has lousy string handling functionality.

SQL has a GREAT way to store lists -- it is called a table.

If you are stuck with a really, really bad data mode. . . . well, you should try to fix it.  But if not, you can use string manipulations:

```<code>select i.*, s.shop_name
from instrument i join
     shops s
     on concat(';', i.instrument_at_shops, ';') like concat('%;', shop_id, ';%');
</code>```

Unfortunately, there is really no way to optimize this query

Body:
I request help for my homework in SQL.

I have a table with musical instruments:

id  instrument_name         instrument_at_shops
-----------------------------------------------
1   Electric Guitar         1;2;3;4;
2   Midi Keyboard           1;3;
3   Tom Drum                2;
4   Electric Guitar         1;
5   Electric Guitar         0;

And a table with shops:

shop_id  shop_name  shop_address
-----------------------------------------------
1        Shop1      City1 Street 1, building 1
2        Shop2      City1 Street 5, building 4
3        Shop3      City2 Street 4, building 4
4        Shop4      City3 Street 10, building 7

In my musical instruments table I have several numbers which represent id's of the shops that have the particular instrument.

The problem is: how to create a view which contains a shop name and an instrument which is in this shop?

The logic is this:

SELECT shop_name, instrument_name
FROM Shop
CROSS JOIN Instrument
WHERE instrumet_at_shops CONTAINS shop_id

But I cannot create an appropriate query or view design.

Thank you in advance!

Body:
You should really put your effort into fixing the data model.  It is broken, broken, broken:

Do not store multiple values in a string.

Do not store numbers are strings.

Foreign key relationships should be properly declared.

SQL has lousy string handling functionality.

SQL has a GREAT way to store lists -- it is called a table.

If you are stuck with a really, really bad data mode. . . . well, you should try to fix it.  But if not, you can use string manipulations:

select i.*, s.shop_name
from instrument i join
     shops s
     on concat(';', i.instrument_at_shops, ';') like concat('%;', shop_id, ';%');

Unfortunately, there is really no way to optimize this query


问:
Calling delegate methods in custom UITextField class
So this might be basic Swift knowledge but I'm struggling to find this info anywhere online.  I'm trying to create a custom text field glass with global styles that utilizes UITextFieldDelegate methods.  In particular I'm trying to use the function textFieldDidBeginEditing().  In my example below I'm just trying to print "hello" when a text field is being edited, however nothing is being printed to the console when I begin typing in my custom text field.

If I'm doing anything incorrectly please let me know, as I don't work with Swift too much.  Thank you!

```<code>class LoFMTextField: UITextField {

    override init(frame: CGRect) {
        super.init(frame: frame)
        styleTextField()
    }

    required init?(coder LoFMDecoder: NSCoder) {
        super.init(coder: LoFMDecoder)
        styleTextField()
    }

    func styleTextField() {
        layer.cornerRadius = 5.0
        layer.borderWidth = 1.0
        layer.borderColor = UIColor.white.cgColor
        backgroundColor = UIColor.white
    }

}

extension UITextFieldDelegate {

    func textFieldDidBeginEditing(textField: UITextField!) {
        print("hello")
    }

}
</code>```

答:
Add this line inside styleTextField

```<code>self.delegate = self
</code>```

Then

```<code>extension LoFMTextField : UITextFieldDelegate {
   func textFieldDidBeginEditing(_ textField: UITextField) {
      print("hello")
   }
}
</code>```

Note: it's (_ textField: UITextField) not (textField: UITextField!)

Body:
So this might be basic Swift knowledge but I'm struggling to find this info anywhere online.  I'm trying to create a custom text field glass with global styles that utilizes UITextFieldDelegate methods.  In particular I'm trying to use the function textFieldDidBeginEditing().  In my example below I'm just trying to print "hello" when a text field is being edited, however nothing is being printed to the console when I begin typing in my custom text field.

If I'm doing anything incorrectly please let me know, as I don't work with Swift too much.  Thank you!

class LoFMTextField: UITextField {

    override init(frame: CGRect) {
        super.init(frame: frame)
        styleTextField()
    }

    required init?(coder LoFMDecoder: NSCoder) {
        super.init(coder: LoFMDecoder)
        styleTextField()
    }

    func styleTextField() {
        layer.cornerRadius = 5.0
        layer.borderWidth = 1.0
        layer.borderColor = UIColor.white.cgColor
        backgroundColor = UIColor.white
    }

}

extension UITextFieldDelegate {

    func textFieldDidBeginEditing(textField: UITextField!) {
        print("hello")
    }

}

Body:
Add this line inside styleTextField

self.delegate = self

Then

extension LoFMTextField : UITextFieldDelegate {
   func textFieldDidBeginEditing(_ textField: UITextField) {
      print("hello")
   }
}

Note: it's (_ textField: UITextField) not (textField: UITextField!)


问:
CSS not displaying properly after transferred to IIS 7 in IE 9
When running on dev server through VS 2010 all CSS displays properly.  I publish to win server 2008 r2 with IIS 7, and when I open in IE 9 the inline-block doesnt work, the gradients dont work, and the box-shadow doesnt work.  It strips out most of the CSS formatting, I load the same page in firefox and it looks the same as it does in IE 9 under the dev server.  Code below:
CSS file:

```<code>body {
}
#opsChartContainer
{
    background: #FFFFFF;
margin: auto;
width: 600px;
padding-top: 15px;
font-family: helvetica, arial, sans-serif;
display: inline-table;
}
#oldestActiveCon
{
    background: #FFFFFF;
    margin: auto;
    width: 300px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}
#incVolumeCon
{
    background: #FFFFFF;
    margin: auto;
    width: 700px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}
#reqSLACon
{
    background: #FFFFFF;
    margin: auto;
    width: 400px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}

h1
{
    background: #e3e3e3;
    background: -moz-linear-gradient(top, #fcfdfe, #8bb7e3);
    background: -webkit-gradient(linear, left top, left bottom, from(#fcfdfe), to(#8bb7e3));
    padding: 10px 20px;
    margin-left: -20px;
    margin-top: 0;
    position: relative;
    width: 70%;
    -moz-box-shadow: 1px 1px 3px #292929;
    -webkit-box-shadow: 1px 1px 3px #292929;
    box-shadow: 3px 3px 3px #292929;
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fcfdfe,     endColorstr=#8bb7e3)";
    color: #454545;
    text-shadow: 0 1px 0 white;
    font-size: small;
    font-weight: bold;
}
h2
{
    background: #dde3d5;
    padding: 10px 20px;
    margin-left: 5px;
    margin-top: 10px;
    position: relative;
    -moz-box-shadow: 1px 1px 3px #292929;
    -webkit-box-shadow: 1px 1px 3px #292929;
    box-shadow: 3px 3px 3px #b5baae;
    color: #454545;
    text-shadow: 0 1px 0 white;
    font-size: small;
    font-style: normal;
}
.mGrid {
    width: 100%;
    margin: 5px 0 10px 0;
    border: solid 1px #525252;
    border-collapse:collapse;
}
.mGrid td {
    padding: 2px;

}
.header
{
    padding: 4px 2px;
    color: #ffffff;
    background: #4289c6 url('../grd_head.png') repeat-x top;
}
.alt
{
    background: #FFFFFF url('../grd_alt.png') repeat-x top;
    font-size: smaller;
    font-family: Arial;
    font-style: normal;
}
.rst
{
    background: #FFFFFF url('../grd_firstt.png') repeat-x top;
    font-size: smaller;
    font-family: Arial;
    font-style: normal;
}

ul#testy li
{
    list-style-type: none;
    display: inline-block;
    vertical-align: top;
    padding-left: 50px;
}
</code>```

ASPX front end:

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"     CodeBehind="test.aspx.cs" Inherits="test.test" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div id="opsChartContainer"><h1>TEXT</h1><h2>FLASHFILE</h2></div>
<div id="oldestActiveCon"><h1>TEXT</h1>
<h2>
    <asp:GridView ID="GridView1" runat="server" CellPadding="4"
        ForeColor="#333333"
        GridLines="None" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" Width="200px">
        <AlternatingRowStyle CssClass="alt" />
        <Columns>
            <asp:BoundField DataField="Status" HeaderText="Status"
                SortExpression="Status" />
            <asp:BoundField DataField="Team" HeaderText="Team" SortExpression="Team" />
            <asp:BoundField DataField="Time" HeaderText="Time" ReadOnly="True"
                SortExpression="Time" />
            <asp:TemplateField HeaderText="Request ID">
                <ItemTemplate>
                    <asp:HyperLink ID="HyperLink1" runat="server" Target="_blank"     NavigateUrl='<%    # "link"+ Eval("Request") + "&"%>'><%#Eval("Request")%></asp:HyperLink>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>

        <HeaderStyle CssClass="header" />

<RowStyle CssClass="rst"></RowStyle>

    </asp:GridView>
</h2>
</div>

<div id="incVolumeCon">
    <h1>text</h1>
    <h2>
        flashfile
    </h2>
</div>
<div id="reqSLACon">
    <h1> text</h1>
        <h2>
        <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
        DataSourceID="blahblah" CellPadding="4" ForeColor="#333333"
        GridLines="None" CssClass="mGrid" AlternatingRowStyle-CssClass="alt" RowStyle-CssClass="rst" Width = "400">
        <Columns>
            <asp:BoundField DataField="text" HeaderText="text" ReadOnly="True"
                SortExpression="text" />
            <asp:BoundField DataField="Dueby Time" HeaderText="text" ReadOnly="True"
                SortExpression="text" />
            <asp:BoundField DataField="text" HeaderText="text"
                ReadOnly="True" SortExpression="text" />
            <asp:BoundField DataField="text" HeaderText="text"
                ReadOnly="True" SortExpression="text" />
            <asp:BoundField DataField="Expr1" HeaderText="text" ReadOnly="True"
                SortExpression="Expr1" />
            <asp:TemplateField HeaderText="Request ID" >
            <ItemTemplate>
                    <asp:HyperLink ID="HyperLink1" runat="server" Target="_blank" NavigateUrl='<%# "link"+ Eval("Request ID") + "&"%>'><%#Eval("Request ID")%></asp:HyperLink>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>

</asp:GridView>

test
    </h2>
</div>
</code>```

ANY ideas?  What is causing the disparity between when I view it in IE 9 through dev server from vs 2010 and when I view it in IE 9 on production server?

答:
Your page is running with a Document Mode other than "IE 9 Standards".

Hit F12 to bring up the Developer Tools to see which it actually is.

See here for instructions to work out why this is happening: http://hsivonen.iki.fi/doctype/#ie8modes

Otherwise, you can fix it by adding this to the top of your :

```<code><meta http-equiv="X-UA-Compatible" content="IE=Edge" />
</code>```

This will force IE to use its most up-to-date rendering engine.

This can be done in IIS server also by settings in HTTP Response Header.
IN the Name field put "X-UA-Compatible" and in the Value field put "IE=Edge"
in EDIT Custom HTTP Response Header as below image.

Body:
When running on dev server through VS 2010 all CSS displays properly.  I publish to win server 2008 r2 with IIS 7, and when I open in IE 9 the inline-block doesnt work, the gradients dont work, and the box-shadow doesnt work.  It strips out most of the CSS formatting, I load the same page in firefox and it looks the same as it does in IE 9 under the dev server.  Code below:
CSS file:

body {
}
#opsChartContainer
{
    background: #FFFFFF;
margin: auto;
width: 600px;
padding-top: 15px;
font-family: helvetica, arial, sans-serif;
display: inline-table;
}
#oldestActiveCon
{
    background: #FFFFFF;
    margin: auto;
    width: 300px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}
#incVolumeCon
{
    background: #FFFFFF;
    margin: auto;
    width: 700px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}
#reqSLACon
{
    background: #FFFFFF;
    margin: auto;
    width: 400px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}

h1
{
    background: #e3e3e3;
    background: -moz-linear-gradient(top, #fcfdfe, #8bb7e3);
    background: -webkit-gradient(linear, left top, left bottom, from(#fcfdfe), to(#8bb7e3));
    padding: 10px 20px;
    margin-left: -20px;
    margin-top: 0;
    position: relative;
    width: 70%;
    -moz-box-shadow: 1px 1px 3px #292929;
    -webkit-box-shadow: 1px 1px 3px #292929;
    box-shadow: 3px 3px 3px #292929;
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fcfdfe,     endColorstr=#8bb7e3)";
    color: #454545;
    text-shadow: 0 1px 0 white;
    font-size: small;
    font-weight: bold;
}
h2
{
    background: #dde3d5;
    padding: 10px 20px;
    margin-left: 5px;
    margin-top: 10px;
    position: relative;
    -moz-box-shadow: 1px 1px 3px #292929;
    -webkit-box-shadow: 1px 1px 3px #292929;
    box-shadow: 3px 3px 3px #b5baae;
    color: #454545;
    text-shadow: 0 1px 0 white;
    font-size: small;
    font-style: normal;
}
.mGrid {
    width: 100%;
    margin: 5px 0 10px 0;
    border: solid 1px #525252;
    border-collapse:collapse;
}
.mGrid td {
    padding: 2px;

}
.header
{
    padding: 4px 2px;
    color: #ffffff;
    background: #4289c6 url('../grd_head.png') repeat-x top;
}
.alt
{
    background: #FFFFFF url('../grd_alt.png') repeat-x top;
    font-size: smaller;
    font-family: Arial;
    font-style: normal;
}
.rst
{
    background: #FFFFFF url('../grd_firstt.png') repeat-x top;
    font-size: smaller;
    font-family: Arial;
    font-style: normal;
}

ul#testy li
{
    list-style-type: none;
    display: inline-block;
    vertical-align: top;
    padding-left: 50px;
}

ASPX front end:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"     CodeBehind="test.aspx.cs" Inherits="test.test" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

TEXT

FLASHFILE

TEXT

    <asp:GridView ID="GridView1" runat="server" CellPadding="4"
        ForeColor="#333333"
        GridLines="None" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" Width="200px">
        <AlternatingRowStyle CssClass="alt" />
        <Columns>
            <asp:BoundField DataField="Status" HeaderText="Status"
                SortExpression="Status" />
            <asp:BoundField DataField="Team" HeaderText="Team" SortExpression="Team" />
            <asp:BoundField DataField="Time" HeaderText="Time" ReadOnly="True"
                SortExpression="Time" />
            <asp:TemplateField HeaderText="Request ID">
                <ItemTemplate>
                    <asp:HyperLink ID="HyperLink1" runat="server" Target="_blank"     NavigateUrl='<%    # "link"+ Eval("Request") + "&"%>'><%#Eval("Request")%></asp:HyperLink>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>

        <HeaderStyle CssClass="header" />

<RowStyle CssClass="rst"></RowStyle>

    </asp:GridView>

text

        flashfile

 text

        <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
        DataSourceID="blahblah" CellPadding="4" ForeColor="#333333"
        GridLines="None" CssClass="mGrid" AlternatingRowStyle-CssClass="alt" RowStyle-CssClass="rst" Width = "400">
        <Columns>
            <asp:BoundField DataField="text" HeaderText="text" ReadOnly="True"
                SortExpression="text" />
            <asp:BoundField DataField="Dueby Time" HeaderText="text" ReadOnly="True"
                SortExpression="text" />
            <asp:BoundField DataField="text" HeaderText="text"
                ReadOnly="True" SortExpression="text" />
            <asp:BoundField DataField="text" HeaderText="text"
                ReadOnly="True" SortExpression="text" />
            <asp:BoundField DataField="Expr1" HeaderText="text" ReadOnly="True"
                SortExpression="Expr1" />
            <asp:TemplateField HeaderText="Request ID" >
            <ItemTemplate>
                    <asp:HyperLink ID="HyperLink1" runat="server" Target="_blank" NavigateUrl='<%# "link"+ Eval("Request ID") + "&"%>'><%#Eval("Request ID")%></asp:HyperLink>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>

</asp:GridView>

test

ANY ideas?  What is causing the disparity between when I view it in IE 9 through dev server from vs 2010 and when I view it in IE 9 on production server?

Body:
Your page is running with a Document Mode other than "IE 9 Standards".

Hit F12 to bring up the Developer Tools to see which it actually is.

See here for instructions to work out why this is happening: http://hsivonen.iki.fi/doctype/#ie8modes

Otherwise, you can fix it by adding this to the top of your <head>:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

This will force IE to use its most up-to-date rendering engine.

This can be done in IIS server also by settings in HTTP Response Header.
IN the Name field put "X-UA-Compatible" and in the Value field put "IE=Edge"
in EDIT Custom HTTP Response Header as below image.


问:
Trouble setting up Boost library with GCC-6 in Clion
I am not able to build a simple Hello World program in GCC-6 but it works fine with Clang in Clion.

Now I try to build and run the first example of Boost Date Time here

Boost Date time Example

My CMake looks like

```<code>cmake_minimum_required(VERSION 3.16)
project(Boost_Run_2)

set(CMAKE_CXX_STANDARD 11)

find_package(Boost REQUIRED COMPONENTS date_time)

add_executable(Boost_Run_2 main.cpp)
target_link_libraries(Boost_Run_2 PRIVATE Boost::date_time)
</code>```

But it throws linker error as

```<code>====================[ Build | Boost_Run_2 | Debug ]=============================
/Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake --build /Users/alihasan/Documents/GSOC/Boost_Run_2/cmake-build-debug --target Boost_Run_2 -- -j 4
Scanning dependencies of target Boost_Run_2
[ 50%] Building CXX object CMakeFiles/Boost_Run_2.dir/main.cpp.o
[100%] Linking CXX executable Boost_Run_2
Undefined symbols for architecture x86_64:
  "boost::gregorian::greg_month::get_month_map_ptr[abi:cxx11]()", referenced from:
      unsigned short boost::date_time::month_str_to_ushort<boost::gregorian::greg_month>(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) in main.cpp.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
make[3]: *** [Boost_Run_2] Error 1
make[2]: *** [CMakeFiles/Boost_Run_2.dir/all] Error 2
make[1]: *** [CMakeFiles/Boost_Run_2.dir/rule] Error 2
make: *** [Boost_Run_2] Error 2
</code>```

When I run the same program with Clang I am able to run it. No linker errors. So I am assuming my Boost Libraries are set up properly.

I want to be able to run the same program using GCC-6/G++-6.

I have a macOS Mojave 10.14.3 and I used brew install boost to install Boost libraries.

答:
I was able to fix this issue.

I realized my Boost libraries were not installed properly.

For some reason, Homebrew does not install Boost libraries properly and you've got to install it the way it's mentioned in their documentation.

Getting Started on Unix Variants

StackOverflow question How do you install Boost on MacOS?

Thanks to snies answer https://stackoverflow.com/a/11297605/8093027.

Body:
I am not able to build a simple Hello World program in GCC-6 but it works fine with Clang in Clion.

Now I try to build and run the first example of Boost Date Time here

Boost Date time Example

My CMake looks like

cmake_minimum_required(VERSION 3.16)
project(Boost_Run_2)

set(CMAKE_CXX_STANDARD 11)

find_package(Boost REQUIRED COMPONENTS date_time)

add_executable(Boost_Run_2 main.cpp)
target_link_libraries(Boost_Run_2 PRIVATE Boost::date_time)

But it throws linker error as

====================[ Build | Boost_Run_2 | Debug ]=============================
/Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake --build /Users/alihasan/Documents/GSOC/Boost_Run_2/cmake-build-debug --target Boost_Run_2 -- -j 4
Scanning dependencies of target Boost_Run_2
[ 50%] Building CXX object CMakeFiles/Boost_Run_2.dir/main.cpp.o
[100%] Linking CXX executable Boost_Run_2
Undefined symbols for architecture x86_64:
  "boost::gregorian::greg_month::get_month_map_ptr[abi:cxx11]()", referenced from:
      unsigned short boost::date_time::month_str_to_ushort<boost::gregorian::greg_month>(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) in main.cpp.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
make[3]: *** [Boost_Run_2] Error 1
make[2]: *** [CMakeFiles/Boost_Run_2.dir/all] Error 2
make[1]: *** [CMakeFiles/Boost_Run_2.dir/rule] Error 2
make: *** [Boost_Run_2] Error 2

When I run the same program with Clang I am able to run it. No linker errors. So I am assuming my Boost Libraries are set up properly.

I want to be able to run the same program using GCC-6/G++-6.

I have a macOS Mojave 10.14.3 and I used brew install boost to install Boost libraries.


问:
Remove one out of two legends from Seaborn Scatterplot
Using the 'tips' dataset as a toy model, I generate the following plot:

```<code>import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

cmap = sns.cubehelix_palette(dark=.3, light=.8, as_cmap=True)
g = sns.scatterplot(x="total_bill", y="sex", hue="smoker", size = 'tip',sizes=(320, 600), data=tips)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize=13)
plt.show(g)
</code>```

This image is exactly what I need. However, I want to remove the size = 'tip' from the legend and only keep the smoker. Essentially, remove those black circles labeled 0.0 to 12.0. How do I ensure my legend has only one variable of my choosing?

答:
I was able to find a fix by indexing the labels in the legend.

```<code>import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

cmap = sns.cubehelix_palette(dark=.3, light=.8, as_cmap=True)
g = sns.scatterplot(x="total_bill", y="sex", hue="smoker", size = 'tip',sizes=(320, 600), data=tips)
h,l = g.get_legend_handles_labels()
plt.legend(h[0:3],l[0:3],bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize=13)
plt.show(g)
</code>```

Body:
Using the 'tips' dataset as a toy model, I generate the following plot:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

cmap = sns.cubehelix_palette(dark=.3, light=.8, as_cmap=True)
g = sns.scatterplot(x="total_bill", y="sex", hue="smoker", size = 'tip',sizes=(320, 600), data=tips)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize=13)
plt.show(g)

This image is exactly what I need. However, I want to remove the size = 'tip' from the legend and only keep the smoker. Essentially, remove those black circles labeled 0.0 to 12.0. How do I ensure my legend has only one variable of my choosing?

Body:
I was able to find a fix by indexing the labels in the legend.

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

cmap = sns.cubehelix_palette(dark=.3, light=.8, as_cmap=True)
g = sns.scatterplot(x="total_bill", y="sex", hue="smoker", size = 'tip',sizes=(320, 600), data=tips)
h,l = g.get_legend_handles_labels()
plt.legend(h[0:3],l[0:3],bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize=13)
plt.show(g)


问:
How to calculate when inventory will run out using pandas?
Suppose I have a DataFrame like so:

```<code>Item        Check Date   Inventory
Apple       1/1/2020     50
Banana      1/1/2020     80
Apple       1/2/2020     75
Banana      1/2/2020     300
Apple       2/1/2020     100
Apple       2/2/2020     98
Banana      2/2/2020     341
Apple       2/3/2020     95
Banana      2/3/2020     328
Apple       2/4/2020     90
Apple       2/5/2020     85
Banana      2/5/2020     325
</code>```

I want to find the average rate of change in the inventory for a given item starting from the max inventory count, then use that to compute what day the inventory will reach zero.
So for apples it would be starting from 2/1: 2+3+5+5/4 = 3.75, similarly for bananas starting from 2/2 13+3/2 = 8.

Since there are different items, I have used:

apples = df[df["Item"] == "apples"]

to get a dataframe for just the apples, then used:

apples["Inventory"].idxmax()

to find the row with the max inventory count.

However, this gives me the row label of the row for the original dataframe. So I'm not sure where to go from here since my plan was to then get the date off the row with the max inventory count, then ignore any dates before that.

答:
You can still use the idxmax but with transform

```<code>s=df[df.index>=df.groupby('Item').Inventory.transform('idxmax')]
out=s.groupby('Item')['Inventory'].apply(lambda  x : -x.diff().mean())
Item
Apple     3.75
Banana    8.00
Name: Inventory, dtype: float64
</code>```

Body:
Suppose I have a DataFrame like so:

Item        Check Date   Inventory
Apple       1/1/2020     50
Banana      1/1/2020     80
Apple       1/2/2020     75
Banana      1/2/2020     300
Apple       2/1/2020     100
Apple       2/2/2020     98
Banana      2/2/2020     341
Apple       2/3/2020     95
Banana      2/3/2020     328
Apple       2/4/2020     90
Apple       2/5/2020     85
Banana      2/5/2020     325

I want to find the average rate of change in the inventory for a given item starting from the max inventory count, then use that to compute what day the inventory will reach zero.
So for apples it would be starting from 2/1: 2+3+5+5/4 = 3.75, similarly for bananas starting from 2/2 13+3/2 = 8.

Since there are different items, I have used:

apples = df[df["Item"] == "apples"]

to get a dataframe for just the apples, then used:

apples["Inventory"].idxmax()

to find the row with the max inventory count.

However, this gives me the row label of the row for the original dataframe. So I'm not sure where to go from here since my plan was to then get the date off the row with the max inventory count, then ignore any dates before that.

Body:
You can still use the idxmax but with transform

s=df[df.index>=df.groupby('Item').Inventory.transform('idxmax')]
out=s.groupby('Item')['Inventory'].apply(lambda  x : -x.diff().mean())
Item
Apple     3.75
Banana    8.00
Name: Inventory, dtype: float64


问:
This version of Microsoft.AspNetCore.All is only compatible with the netcoreapp2.1 target framework
When I try to publish my application to the web server after upgrading to .NET Core 2.1 from 2.0, I get this message: "This version of Microsoft.AspNetCore.All is only compatible with the netcoreapp2.1 target framework. Please target netcoreapp2.1 or choose a version of Microsoft.AspNetCore.All compatible with netcoreapp2.0."

It runs fine on my development machine.

Here is my project file:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <RunPostBuildEvent>Always</RunPostBuildEvent>
</PropertyGroup>
<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.4" />
</ItemGroup>
</Project>
</code>```

I have seen this, but it does not seem to be the problem.  I have also experimented with the prerelease 2.1 version of CodeGeneration.Tools, but I was not able to install it.

EDIT:  I did install dotnet 2.1 on the server.

Here's what I see on the server:

```<code>D:\>dotnet --info
Host (useful for support):
  Version: 2.1.0
  Commit:  caa7b7e2ba

.NET Core SDKs installed:
  No SDKs were found.

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.1.0 [C:\Program Files (x86)\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.1.0 [C:\Program Files (x86)\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.0.5 [C:\Program Files (x86)\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.0.6 [C:\Program Files (x86)\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.1.0 [C:\Program Files (x86)\dotnet\shared\Microsoft.NETCore.App]
</code>```

答: I deleted my obj folder inside project which had json files pointing to 2.2 version from previous build. </p>

Body:
When I try to publish my application to the web server after upgrading to .NET Core 2.1 from 2.0, I get this message: "This version of Microsoft.AspNetCore.All is only compatible with the netcoreapp2.1 target framework. Please target netcoreapp2.1 or choose a version of Microsoft.AspNetCore.All compatible with netcoreapp2.0."

It runs fine on my development machine.

Here is my project file:

<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <RunPostBuildEvent>Always</RunPostBuildEvent>
</PropertyGroup>
<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.4" />
</ItemGroup>
</Project>

I have seen this, but it does not seem to be the problem.  I have also experimented with the prerelease 2.1 version of CodeGeneration.Tools, but I was not able to install it.

EDIT:  I did install dotnet 2.1 on the server.

Here's what I see on the server:

D:\>dotnet --info
Host (useful for support):
  Version: 2.1.0
  Commit:  caa7b7e2ba

.NET Core SDKs installed:
  No SDKs were found.

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.1.0 [C:\Program Files (x86)\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.1.0 [C:\Program Files (x86)\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.0.5 [C:\Program Files (x86)\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.0.6 [C:\Program Files (x86)\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.1.0 [C:\Program Files (x86)\dotnet\shared\Microsoft.NETCore.App]


问:
Last record per transaction
I am trying to select the last record per sales order.

My query is simple in SQL Server management.

```<code>SELECT *
FROM DOCSTATUS
</code>```

The problem is that this database has tens of thousands of records, as it tracks all SO steps.

```<code>ID    SO    SL      Status        Reason      Attach    Name   Name       Systemdate
22  951581  3     Processed       Customer      NULL    NULL    BW  2016-12-05 13:33:27.857
23  951581  3     Submitted       Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
24  947318  1        Hold         Customer      NULL    NULL    bw  2016-12-05 13:54:27.173
25  947318  1   Invoices Submit   Customer      NULL    NULL    bw  2016-13-05 13:54:27.300
26  947318  1        Ship         Customer      NULL    NULL    bw  2016-14-05 13:54:27.440
</code>```

I would to see the most recent record per the SO

```<code> ID    SO    SL       Status          Reason      Attach    Name   Name       Systemdate
 23  951581  4       Submitted        Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
 26  947318  1         Ship           Customer      NULL    NULL    bw  2016-14-05 13:54:27.440
</code>```

答:
I think you can keep it this simple:

```<code>SELECT *
FROM DOCSTATUS
WHERE ID IN (SELECT MAX(ID)
             FROM DOCSTATUS
             GROUP BY SO)
</code>```

You want only the maximum ID from each SO.

Title: Last record per transaction

Body:
I am trying to select the last record per sales order.

My query is simple in SQL Server management.

SELECT *
FROM DOCSTATUS

The problem is that this database has tens of thousands of records, as it tracks all SO steps.

ID    SO    SL      Status        Reason      Attach    Name   Name       Systemdate
22  951581  3     Processed       Customer      NULL    NULL    BW  2016-12-05 13:33:27.857
23  951581  3     Submitted       Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
24  947318  1        Hold         Customer      NULL    NULL    bw  2016-12-05 13:54:27.173
25  947318  1   Invoices Submit   Customer      NULL    NULL    bw  2016-13-05 13:54:27.300
26  947318  1        Ship         Customer      NULL    NULL    bw  2016-14-05 13:54:27.440

I would to see the most recent record per the SO

 ID    SO    SL       Status          Reason      Attach    Name   Name       Systemdate
 23  951581  4       Submitted        Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
 26  947318  1         Ship           Customer      NULL    NULL    bw  2016-14-05 13:54:27.440

Body:
I think you can keep it this simple:

SELECT *
FROM DOCSTATUS
WHERE ID IN (SELECT MAX(ID)
             FROM DOCSTATUS
             GROUP BY SO)

You want only the maximum ID from each SO.


问:
PHP strip unknown file extension
I understand that using PHP's basename() function you can strip a known file extension from a path like so,

```<code>basename('path/to/file.php','.php')
</code>```

but what if you didn't know what extension the file had or the length of that extension? How would I accomplish this?

Thanks in advance!

答:
You can extract the extension using pathinfo and cut it off.

```<code>// $filepath = '/path/to/some/file.txt';
$ext = pathinfo($filepath, PATHINFO_EXTENSION);
$basename = basename($filepath, ".$ext");
</code>```

Note the . before $ext

Title: PHP strip unknown file extension

Body:
I understand that using PHP's basename() function you can strip a known file extension from a path like so,

basename('path/to/file.php','.php')

but what if you didn't know what extension the file had or the length of that extension? How would I accomplish this?

Thanks in advance!

Body:
You can extract the extension using pathinfo and cut it off.

// $filepath = '/path/to/some/file.txt';
$ext = pathinfo($filepath, PATHINFO_EXTENSION);
$basename = basename($filepath, ".$ext");

Note the . before $ext


问:
How do I Print an Array of names as pairs
```<code>let players = ["Greg", "Jenn", "Steve", "Anthony", "Krista", "Marti", "Erin", "Brandon",].shuffled()
</code>```

I want to loop over the array and have it print out all pairs after being shuffled...  so if the above was the outcome after being shuffled... it would print out

Greg, Jenn

Steve, Anthony

Krista, Marti

Erin, Brandon

答:
you could use this: </p>

```<code>    if !players.isEmpty {
        let arrTpl = stride(from: 1, to: players.count, by: 2).map { (players[$0-1], players[$0]) }
        print("\(arrTpl)")
    }
</code>```

Body:
let players = ["Greg", "Jenn", "Steve", "Anthony", "Krista", "Marti", "Erin", "Brandon",].shuffled()

I want to loop over the array and have it print out all pairs after being shuffled...  so if the above was the outcome after being shuffled... it would print out

Greg, Jenn

Steve, Anthony

Krista, Marti

Erin, Brandon

Body:
you could use this:

    if !players.isEmpty {
        let arrTpl = stride(from: 1, to: players.count, by: 2).map { (players[$0-1], players[$0]) }
        print("\(arrTpl)")
    }


问:
get the minimum column between columns values pyspark
i have a dataframe with x,y,z columns and with 3 X columns and 3 Xd columns and i want to  get the minimum Xd column with his X in a new column called id.</p>

```<code>df:
x  y  z  a ad b  bd  c  cd
4  8  1  1 2  2  8   3  5
7  5  6  1 6  2  3   3  1
7  3  5  1 9  2  4   3  7

result:
x  y  z  id
4  8  1  1
7  5  6  3
7  3  5  2
</code>```

答:
Try this, using arrays_zip, higher order function filter, and array_min.

```<code>from pyspark.sql import functions as F

df.withColumn("zip", F.arrays_zip(F.array('a','b','c'),F.array('ad','bd','cd')))\
  .withColumn("id", F.expr("""filter(zip,x-> x.`1`=array_min(array(ad,bd,cd)))"""))\
  .select("x","y","z", (F.col("id.0")[0]).alias("id")).show()

#+---+---+---+---+
#|  x|  y|  z| id|
#+---+---+---+---+
#|  4|  8|  1|  1|
#|  7|  5|  6|  3|
#|  7|  3|  5|  2|
#+---+---+---+---+
</code>```

Body:
i have a dataframe with x,y,z columns and with 3 X columns and 3 Xd columns and i want to  get the minimum Xd column with his X in a new column called id.

df:
x  y  z  a ad b  bd  c  cd
4  8  1  1 2  2  8   3  5
7  5  6  1 6  2  3   3  1
7  3  5  1 9  2  4   3  7

result:
x  y  z  id
4  8  1  1
7  5  6  3
7  3  5  2

Body:
Try this, using arrays_zip, higher order function filter, and array_min.

from pyspark.sql import functions as F

df.withColumn("zip", F.arrays_zip(F.array('a','b','c'),F.array('ad','bd','cd')))\
  .withColumn("id", F.expr("""filter(zip,x-> x.`1`=array_min(array(ad,bd,cd)))"""))\
  .select("x","y","z", (F.col("id.0")[0]).alias("id")).show()

#+---+---+---+---+
#|  x|  y|  z| id|
#+---+---+---+---+
#|  4|  8|  1|  1|
#|  7|  5|  6|  3|
#|  7|  3|  5|  2|
#+---+---+---+---+


问:
check database row object exist or not for a given primary key?
Hi
I access row object through Zend_Db_Table like

```<code>$id = $_GET['id'];
$userTb = new Model_DbTable_Users(); //Here Model_DbTable_Users is subclass of Zend_Db_Table
$user = $userTb->find($id)->current();
</code>```

Now how can I check using $user row object that whether $id is valid or not like what if that 'id' does not exist in database.
Earlier I used to do

```<code>if($user->find($id)->count() > 0 )
{
//id is valid so
$user = $user->find($id)->current();
}
</code>```

clearly this way is long I need short way of doing the same .

答:
If there are no rows in the rowset, current() returns null:

```<code>$user = $userTb->find($id)->current();
if ($user) {
    // $user is a valid row
}
else {
    // no rows found
}
</code>```

Body:
Hi
I access row object through Zend_Db_Table like

$id = $_GET['id'];
$userTb = new Model_DbTable_Users(); //Here Model_DbTable_Users is subclass of Zend_Db_Table
$user = $userTb->find($id)->current();

Now how can I check using $user row object that whether $id is valid or not like what if that 'id' does not exist in database.
Earlier I used to do

if($user->find($id)->count() > 0 )
{
//id is valid so
$user = $user->find($id)->current();
}

clearly this way is long I need short way of doing the same .

Body:
If there are no rows in the rowset, current() returns null:

$user = $userTb->find($id)->current();
if ($user) {
    // $user is a valid row
}
else {
    // no rows found
}