问:
Toggle menu trouble
I am trying to create a toggle menu I placed an onclick event listener on my HTML page. The problems occur when I test out the menu, the console tells me that uncaught ReferenceError: myFnc is not defined at HTMLDivelement.onclick.

HTML code

```<code><body>

  <header>

      <img src="img/medical.png" alt="">

      <div class="container" onclick="myFnc(this)">

          <div class="line-1"></div>

          <div class="line-2"></div>

          <div class="line-3"></div>

      </div>

      <nav>

   <ul>

       <li><a href="pages/patent.php">Patients</a></li>

       <li><a href="pages/schedule.php">Schedule</a></li>

       <li><a href="pages/notes.php">Documents</a></li>

       <li><a href="pages/email.php">E-mail</a></li>

       <li><a href="pages/register.php">Register</a></li>

       <li><a href="pages/login.php">Login</a></li>

   </ul>

      </nav>

  </header>

  <main></main>

  <script

  src="https://code.jquery.com/jquery-3.5.1.min.js"

  integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="

  crossorigin="anonymous"></script>

  <script src="js/script.js"></script>

</body>
</code>```

Javascript

```<code>function myFnc(e) {

  var elem = document.getElementsByName("nav");

  style = window.getComputedStyle("elem");

  right = style.getPropertyValue("right");

  if (right == "0px") {

    elem.style.right = "-260px";

  } else {

    elem.style.right = "0px";

  }

}
</code>```

答:
Updated for new code: better to use document.querySelector("nav"). documnet.getElementsByName() returns a node list, while .querySelector returns a single element so it's easier to work with in this case. Other than that, in style = window.getComputedStyle("elem");, you are passing in "elem", but you should pass only elem (without quotation marks) as you are referencing a variable.

Here is a working DEMO, note that you have to use position: relative or position: absolute for the right:-700px to have an effect.

function myFnc(e) {

  var elem = document.querySelector("nav");

  style = window.getComputedStyle(elem);

  right = style.getPropertyValue("right");

  if (right == "0px") {

    elem.style.right = "-260px";

  } else {

    elem.style.right = "0px";

  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 50px;
  height: 50px;
  background: gray;
}

nav {
  position: relative;
}</code>```

 CLICK ME

Patients

Schedule

Documents

E-mail

Register

Login

```

Title: Toggle menu trouble

Body:
I am trying to create a toggle menu I placed an onclick event listener on my HTML page. The problems occur when I test out the menu, the console tells me that uncaught ReferenceError: myFnc is not defined at HTMLDivelement.onclick.

HTML code

Patients

Schedule

Documents

E-mail

Register

Login

Javascript

function myFnc(e) {

  var elem = document.getElementsByName("nav");

  style = window.getComputedStyle("elem");

  right = style.getPropertyValue("right");

  if (right == "0px") {

    elem.style.right = "-260px";

  } else {

    elem.style.right = "0px";

  }

}

Body:
Updated for new code: better to use document.querySelector("nav"). documnet.getElementsByName() returns a node list, while .querySelector returns a single element so it's easier to work with in this case. Other than that, in style = window.getComputedStyle("elem");, you are passing in "elem", but you should pass only elem (without quotation marks) as you are referencing a variable.

Here is a working DEMO, note that you have to use position: relative or position: absolute for the right:-700px to have an effect.

function myFnc(e) {

  var elem = document.querySelector("nav");

  style = window.getComputedStyle(elem);

  right = style.getPropertyValue("right");

  if (right == "0px") {

    elem.style.right = "-260px";

  } else {

    elem.style.right = "0px";

  }

}

.container {
  width: 50px;
  height: 50px;
  background: gray;
}

nav {
  position: relative;
}

<body>

  <header>

  <img src="img/medical.png" alt="">

  <div class="container" onclick="myFnc(this)"> CLICK ME

      <div class="line-1"></div>

      <div class="line-2"></div>

      <div class="line-3"></div>

  </div>

  <nav>

   <ul>

   <li><a href="pages/patent.php">Patients</a></li>

   <li><a href="pages/schedule.php">Schedule</a></li>

   <li><a href="pages/notes.php">Documents</a></li>

   <li><a href="pages/email.php">E-mail</a></li>

   <li><a href="pages/register.php">Register</a></li>

   <li><a href="pages/login.php">Login</a></li>

   </ul>

      </nav>

  </header>

  <main></main>

  <script

  src="https://code.jquery.com/jquery-3.5.1.min.js"

  integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="

  crossorigin="anonymous"></script>

  <script src="js/script.js"></script>

</body>


来源: stackexchange

问:
Syntax error (missing operator) in query expression 'System.Byte[]'
Hi i was using stored procedure in SQL Server to pass parameters to the query ,
but now I'm changing my database to ms access and it's my first time to deal with.

how can i pass byte[] to sql query ?
bacause i got this error
Syntax error (missing operator) in query expression 'System.Byte[]'.

this is my code

```<code>    public static int EditWhois(object ID,object Image, object Ranswer, object Fanswer1, object Fanswer2, object Fanswer3)
    {
        int result = 0;
        String sql = "UPDATE Whois SET [Image]="+@Image+", Ranswer=" + Ranswer + ", Fanswer1=" + Fanswer1 + ",Fanswer2=" + Fanswer2 + ",Fanswer3=" + Fanswer3 + " WHERE ID=" + ID;
        System.Windows.Forms.MessageBox.Show(sql);
        cmd = new OleDbCommand(sql, con);

        //cmd.Parameters.AddWithValue("@ID", ID);
        //cmd.Parameters.AddWithValue("@Image", Image);
        //cmd.Parameters.AddWithValue("@Ranswer", Ranswer);
        //cmd.Parameters.AddWithValue("@Fanswer1", Fanswer1);
        //cmd.Parameters.AddWithValue("@Fanswer2", Fanswer2);
        //cmd.Parameters.AddWithValue("@Fanswer3", Fanswer3);

        if (con.State != ConnectionState.Open)
        {
            con.Open();
            result = cmd.ExecuteNonQuery();
            con.Close();
        }
        return result;
    }
</code>```

答:
result is still 0;
i know the problem where it was .
if the connection is closed the query will be executed successfully , but if it is opend it will not be executed due to this condition .

```<code>if (con.State != ConnectionState.Open)
{
    con.Open();
    result = cmd.ExecuteNonQuery();
    con.Close();
}
</code>```

it must be

```<code>if (con.State != ConnectionState.Open)
{
    con.Open();
}
    result = cmd.ExecuteNonQuery();
    con.Close();
</code>```

thanks all .

ContentLicense: CC BY-SA 3.0

Body:
Hi i was using stored procedure in SQL Server to pass parameters to the query ,
but now I'm changing my database to ms access and it's my first time to deal with.

how can i pass byte[] to sql query ?
bacause i got this error
Syntax error (missing operator) in query expression 'System.Byte[]'.

this is my code

    public static int EditWhois(object ID,object Image, object Ranswer, object Fanswer1, object Fanswer2, object Fanswer3)
    {
        int result = 0;
        String sql = "UPDATE Whois SET [Image]="+@Image+", Ranswer=" + Ranswer + ", Fanswer1=" + Fanswer1 + ",Fanswer2=" + Fanswer2 + ",Fanswer3=" + Fanswer3 + " WHERE ID=" + ID;
        System.Windows.Forms.MessageBox.Show(sql);
        cmd = new OleDbCommand(sql, con);

        //cmd.Parameters.AddWithValue("@ID", ID);
        //cmd.Parameters.AddWithValue("@Image", Image);
        //cmd.Parameters.AddWithValue("@Ranswer", Ranswer);
        //cmd.Parameters.AddWithValue("@Fanswer1", Fanswer1);
        //cmd.Parameters.AddWithValue("@Fanswer2", Fanswer2);
        //cmd.Parameters.AddWithValue("@Fanswer3", Fanswer3);

        if (con.State != ConnectionState.Open)
        {
            con.Open();
            result = cmd.ExecuteNonQuery();
            con.Close();
        }
        return result;
    }

Body:
result is still 0;
i know the problem where it was .
if the connection is closed the query will be executed successfully , but if it is opend it will not be executed due to this condition .

if (con.State != ConnectionState.Open)
{
    con.Open();
    result = cmd.ExecuteNonQuery();
    con.Close();
}

it must be

if (con.State != ConnectionState.Open)
{
    con.Open();
}
    result = cmd.ExecuteNonQuery();
    con.Close();

thanks all .


问:
Pandas | How to effectively filter a column
I'm looking for a way to quickly and effectively filter through a dataframe column and remove values that don't meet a condition.

Say, I have a column with the numbers 4, 5 and 10. I want to filter the column and replace any numbers above 7 with 0. How would I go about this?

答:
You're talking about two separate things - filtering and value replacement. They both have uses and end up being similar in nature but for filtering I'll point to this great answer.

Let's say our data frame is called df and looks like

```<code>   A   B
1  4   10
2  4   2
3  10   1
4  5   9
5  10  3
</code>```

Column A fits your statement of a column only having values 4, 5, 10. If you wanted to replace numbers above 7 with 0, this would do it:

df["A"] = [0 if x > 7 else x for x in df["A"]]
```

<p>If you read through the right-hand side it cleanly explains what it is doing. It helps to include parentheses to separate out the "what to do" with the "what you're doing it over":</p>

<pre class="lang-py prettyprint-override"><code>df["A"] = [(0 if x > 7 else x) for x in df["A"]]
</code>```

If you want to do a manipulation over multiple columns, then utilizing zip allows you to do it easily. For example, if you want the sum of columns A and B then:

df["sum"] = [x[0] + x[1] for x in zip(df["A"], df["B"])]
```

Take care when you overwrite data - this removes information. It's a good practice to have the transformed data in other columns so you can trace back when something inevitably goes wonky.

ContentLicense: CC BY-SA 4.0

Body:
You're talking about two separate things - filtering and value replacement. They both have uses and end up being similar in nature but for filtering I'll point to this great answer.

Let's say our data frame is called df and looks like

   A   B
1  4   10
2  4   2
3  10   1
4  5   9
5  10  3

Column A fits your statement of a column only having values 4, 5, 10. If you wanted to replace numbers above 7 with 0, this would do it:

df["A"] = [0 if x > 7 else x for x in df["A"]]

If you read through the right-hand side it cleanly explains what it is doing. It helps to include parentheses to separate out the "what to do" with the "what you're doing it over":

df["A"] = [(0 if x > 7 else x) for x in df["A"]]

If you want to do a manipulation over multiple columns, then utilizing zip allows you to do it easily. For example, if you want the sum of columns A and B then:

df["sum"] = [x[0] + x[1] for x in zip(df["A"], df["B"])]

Take care when you overwrite data - this removes information. It's a good practice to have the transformed data in other columns so you can trace back when something inevitably goes wonky.


问:
How do I use C++ STL list without iterator?
I need to get to the items in the STL list. I believe those items are of type list_item or ListItem. I need 'next' and 'prev' of each item. how do I do that?</p>

答: may be  you can use another method to do something ,then make it looks like next and prev.</p>


问:
Do recursive and iterative solutions to a problem have same worst time complexity?
If there is a theory existing that proves this, what is it to prove that both would give the same worst case time complexity? It has been showed that both can provide solutions to a problem, but nothing about both giving same worst case time complexity. </p>

答: It completely depends on the problem. But generally, recursive solutions can be made more time-efficient by using dynamic programming.</p>


问:
Storing and updating symmetrical many-to-many relationships between observations in R
I've got a Shiny app I'm using to view and manage some data with lots of related observations. Because of a technical limitation at the original source each observation is initially only tied to one other observation, with larger groups made by chaining things together (A related to B, B related to C, C related to B).

Here's a simplified example, minus the Shiny GUI:

```<code>#How the data comes from the original source
original_data<-tribble(
  ~observation,         ~related_to,
    "A",                     "B",
    "B",                     "C",
    "C",                     "E",
    "D",                     NA,
    "E",                     "D"
)

#After I go through by hand and tally up related cases
my_handtyped_data<-tribble(
  ~observation,       ~related_to,
  "A",                "B,C,D,E",
  "B",                "A,C,D,E",
  "C",                "A,B,D,E",
  "D",                "A,B,C,E",
  "E",                "A,B,C,D"
</code>```

My current method is going through by hand and just typing out related cases as a string. What I want to find is a way to programmatically clean up transitive A-to-B-to-C situations as well as keep all relation data up to date when new rows of data are entered or existing relations are updated.

I've come up with a potential data.table and dplyr approach for propagating changes to related cases that will work on the same or separate table, but I want to be sure there there isn't a package or function already more suited to this. Or that this isn't more SQLite's territory, which is available since I already use a local SQLite file for persistent storage.

```<code>#in actual use these three will be taken from shiny session values
selected_row<-2
selected_observation<-my_handtyped_data$observation[[selected_row]]
related_list<-list("replace", "with", "something")

#data.table approach
my_handtyped_data[observation %in% related_list, related_to := c(related_list, selected_observation)]
my_handtyped_data[selected_row, related_to:=related_list]

#dplyr approach, anti_join->bind_rows might be written wrong
my_handtyped_data %<>%
  filter(observation %in% c(related_list,selected_observation))
  mutate(
    related_to=
     if_else(
      observation==selected_observation,
      related_list,
      c(related_list,selected_observation)
      ) %>%
  anti_join(related_cases_table,.)%>%
  bind_rows(.,related_cases_table)
  )

</code>```

答:
I altered your data a bit (introducing node 'Q', so we get two groups nof nodes...)

Using the igraph [ackage, you can easily get groups of nodes that are related to eachother..

```<code>**sample data**
original_data<-tribble(
  ~observation,         ~related_to,
  "A",                     "Q",       #  <-- !!
  "B",                     "C",
  "C",                     "E",
  "D",                     NA,
  "E",                     "D"
)

library( tibble )
library( igraph )

#get df of nodes
nodes <- tibble( name = unique( na.omit( stack( original_data )$values ) ) )
#create list of edges
edges <- original_data[ complete.cases( original_data ), ]
#build igraph
g <- graph_from_data_frame(d = edges, vertices = nodes, directed = FALSE)
</code>```

looks like this

and the groups are...

```<code>#get groups of nodes
groups(components(g) )

# $`1`
# [1] "A" "Q"
#
# $`2`
# [1] "B" "C" "D" "E"
</code>```

Body:
I've got a Shiny app I'm using to view and manage some data with lots of related observations. Because of a technical limitation at the original source each observation is initially only tied to one other observation, with larger groups made by chaining things together (A related to B, B related to C, C related to B).

Here's a simplified example, minus the Shiny GUI:

#How the data comes from the original source
original_data<-tribble(
  ~observation,         ~related_to,
    "A",                     "B",
    "B",                     "C",
    "C",                     "E",
    "D",                     NA,
    "E",                     "D"
)

#After I go through by hand and tally up related cases
my_handtyped_data<-tribble(
  ~observation,       ~related_to,
  "A",                "B,C,D,E",
  "B",                "A,C,D,E",
  "C",                "A,B,D,E",
  "D",                "A,B,C,E",
  "E",                "A,B,C,D"

My current method is going through by hand and just typing out related cases as a string. What I want to find is a way to programmatically clean up transitive A-to-B-to-C situations as well as keep all relation data up to date when new rows of data are entered or existing relations are updated.

I've come up with a potential data.table and dplyr approach for propagating changes to related cases that will work on the same or separate table, but I want to be sure there there isn't a package or function already more suited to this. Or that this isn't more SQLite's territory, which is available since I already use a local SQLite file for persistent storage.

#in actual use these three will be taken from shiny session values
selected_row<-2
selected_observation<-my_handtyped_data$observation[[selected_row]]
related_list<-list("replace", "with", "something")

#data.table approach
my_handtyped_data[observation %in% related_list, related_to := c(related_list, selected_observation)]
my_handtyped_data[selected_row, related_to:=related_list]

#dplyr approach, anti_join->bind_rows might be written wrong
my_handtyped_data %<>%
  filter(observation %in% c(related_list,selected_observation))
  mutate(
    related_to=
     if_else(
      observation==selected_observation,
      related_list,
      c(related_list,selected_observation)
      ) %>%
  anti_join(related_cases_table,.)%>%
  bind_rows(.,related_cases_table)
  )

Body:
I altered your data a bit (introducing node 'Q', so we get two groups nof nodes...)

Using the igraph [ackage, you can easily get groups of nodes that are related to eachother..

**sample data**
original_data<-tribble(
  ~observation,         ~related_to,
  "A",                     "Q",       #  <-- !!
  "B",                     "C",
  "C",                     "E",
  "D",                     NA,
  "E",                     "D"
)

library( tibble )
library( igraph )

#get df of nodes
nodes <- tibble( name = unique( na.omit( stack( original_data )$values ) ) )
#create list of edges
edges <- original_data[ complete.cases( original_data ), ]
#build igraph
g <- graph_from_data_frame(d = edges, vertices = nodes, directed = FALSE)

looks like this

and the groups are...

#get groups of nodes
groups(components(g) )

# $`1`
# [1] "A" "Q"
#
# $`2`
# [1] "B" "C" "D" "E"


问:
SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81
I am currently new to robot framework.I am currently using latest window version of chrome and chromedriver which is 80 but when i try to run the test it gives the message "SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81" in pycharm but currently beta version of 81 is only available. I have tried uninstalling everthing and reinstalling it again but nothing works can anyone help me with this.Thank you!

Screenshots below:

答:
Do below steps :

Check the version of chrome browser.

download chromedriver of same version from https://sites.google.com/chromium.org/driver/home

Give correct path in the pycharm and run the code.


问:
Can't access property from object in Javascript
EDIT: Re-structured question, cleaer, and cleaner:

I have a data object from Sequelize that is sent by node-express:

```<code>{
    "page": 0,
    "limit": 10,
    "total": 4,
    "data": [
        {
            "id": 1,
            "title": "movies",
            "isActive": true,
            "createdAt": "2020-05-30T19:26:04.000Z",
            "updatedAt": "2020-05-30T19:26:04.000Z",
            "questions": [
                {
                    "questionsCount": 4
                }
            ]
        }
    ]
}
</code>```

The BIG question is, how do I get the value of questionsCount?
The PROBLEM is, I just can't extract it, these two methods give me undefined result:

category.questions[0].questionsCount

category.questions[0]['questionsCount']

I WAS ABLE to get it using toJSON() (From Sequelize lib I think), like so:

```<code>category.questions[0].toJSON().questionsCount
</code>```

But I'd like to know the answer to the question, or at least a clear explanation of why do I have to use toJSON() just to get the questionsCount?

More context:

I have this GET in my controller:

```<code>exports.getCategories = (req, res) => {
  const page = myUtil.parser.tryParseInt(req.query.page, 0)
  const limit = myUtil.parser.tryParseInt(req.query.limit, 10)

  db.Category.findAndCountAll({
    where: {},
    include: [
      {
        model: db.Question,
        as: "questions",
        attributes: [[db.Sequelize.fn('COUNT', 'id'), 'questionsCount']]
      }
    ],
    offset: limit * page,
    limit: limit,
    order: [["id", "ASC"]],
  })
    .then(data => {

      data.rows.forEach(function(category) {
        console.log("------ May 31 ----> " + JSON.stringify(category.questions[0]) + " -->" + category.questions[0].hasOwnProperty('questionsCount'))
        console.log(JSON.stringify(category))
        console.log(category.questions[0].toJSON().questionsCount)
      })

      res.json(myUtil.response.paging(data, page, limit))
    })
    .catch(err => {
      console.log("Error get categories: " + err.message)
      res.status(500).send({
        message: "An error has occured while retrieving data."
      })
    })
}
</code>```

I loop through the data.rows to get each category object.

The console.log outputs are:

```<code>------ May 31 ----> {"questionsCount":4} -->false

{"id":1,"title":"movies","isActive":true,"createdAt":"2020-05-30T19:26:04.000Z","updatedAt":"2020-05-30T19:26:04.000Z","questions":[{"questionsCount":4}]}

4
</code>```

答:
https://github.com/sequelize/sequelize/blob/master/docs/manual/core-concepts/model-querying-finders.md

By default, the results of all finder methods are instances of the model class (as opposed to being just plain JavaScript objects). This means that after the database returns the results, Sequelize automatically wraps everything in proper instance objects. In a few cases, when there are too many results, this wrapping can be inefficient. To disable this wrapping and receive a plain response instead, pass { raw: true } as an option to the finder method.

(emphasis by me)

Or directly in the source code, https://github.com/sequelize/sequelize/blob/59b8a7bfa018b94ccfa6e30e1040de91d1e3d3dd/lib/model.js#L2028

@returns {Promise<{count: number, rows: Model[]}>}

So the thing is that you get an array of Model objects which you could navigate with their get() method. It's an unfortunate coincidence that you expected an array, and got an array so you thought it is "that" array. Try the {raw:true} thing, I guess it looks something like this:

```<code>db.Category.findAndCountAll({
    where: {},
    include: [
      {
        model: db.Question,
        as: "questions",
        attributes: [[db.Sequelize.fn('COUNT', 'id'), 'questionsCount']]
      }
    ],
    offset: limit * page,
    limit: limit,
    order: [["id", "ASC"]],
    raw: true                            // <--- hopefully it is this simple
  }) [...]
</code>```

toJSON() is nearby too, https://github.com/sequelize/sequelize/blob/59b8a7bfa018b94ccfa6e30e1040de91d1e3d3dd/lib/model.js#L4341

```<code>  /**
   * Convert the instance to a JSON representation.
   * Proxies to calling `get` with no keys.
   * This means get all values gotten from the DB, and apply all custom getters.
   *
   * @see
   * {@link Model#get}
   *
   * @returns {object}
   */
  toJSON() {
    return _.cloneDeep(
      this.get({
        plain: true
      })
    );
  }
</code>```

So it worked exactly because it did what you needed, removed the get() stuff and provided an actual JavaScript object matching your structure (POJSO? - sorry, I could not resist). I rarely use it and thus always forget, but the key background "trick" is that a bit contrary to its name, toJSON() is not expected to create the actual JSON string, but to provide a replacement object which still gets stringified by JSON.stringify(). (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON_behavior)

Body:
EDIT: Re-structured question, cleaer, and cleaner:

I have a data object from Sequelize that is sent by node-express:

{
    "page": 0,
    "limit": 10,
    "total": 4,
    "data": [
        {
            "id": 1,
            "title": "movies",
            "isActive": true,
            "createdAt": "2020-05-30T19:26:04.000Z",
            "updatedAt": "2020-05-30T19:26:04.000Z",
            "questions": [
                {
                    "questionsCount": 4
                }
            ]
        }
    ]
}

The BIG question is, how do I get the value of questionsCount?
The PROBLEM is, I just can't extract it, these two methods give me undefined result:

category.questions[0].questionsCount

category.questions[0]['questionsCount']

I WAS ABLE to get it using toJSON() (From Sequelize lib I think), like so:

category.questions[0].toJSON().questionsCount

But I'd like to know the answer to the question, or at least a clear explanation of why do I have to use toJSON() just to get the questionsCount?

More context:

I have this GET in my controller:

exports.getCategories = (req, res) => {
  const page = myUtil.parser.tryParseInt(req.query.page, 0)
  const limit = myUtil.parser.tryParseInt(req.query.limit, 10)

  db.Category.findAndCountAll({
    where: {},
    include: [
      {
        model: db.Question,
        as: "questions",
        attributes: [[db.Sequelize.fn('COUNT', 'id'), 'questionsCount']]
      }
    ],
    offset: limit * page,
    limit: limit,
    order: [["id", "ASC"]],
  })
    .then(data => {

      data.rows.forEach(function(category) {
        console.log("------ May 31 ----> " + JSON.stringify(category.questions[0]) + " -->" + category.questions[0].hasOwnProperty('questionsCount'))
        console.log(JSON.stringify(category))
        console.log(category.questions[0].toJSON().questionsCount)
      })

      res.json(myUtil.response.paging(data, page, limit))
    })
    .catch(err => {
      console.log("Error get categories: " + err.message)
      res.status(500).send({
        message: "An error has occured while retrieving data."
      })
    })
}

I loop through the data.rows to get each category object.

The console.log outputs are:

------ May 31 ----> {"questionsCount":4} -->false

{"id":1,"title":"movies","isActive":true,"createdAt":"2020-05-30T19:26:04.000Z","updatedAt":"2020-05-30T19:26:04.000Z","questions":[{"questionsCount":4}]}

4

Body:
https://github.com/sequelize/sequelize/blob/master/docs/manual/core-concepts/model-querying-finders.md

By default, the results of all finder methods are instances of the model class (as opposed to being just plain JavaScript objects). This means that after the database returns the results, Sequelize automatically wraps everything in proper instance objects. In a few cases, when there are too many results, this wrapping can be inefficient. To disable this wrapping and receive a plain response instead, pass { raw: true } as an option to the finder method.

(emphasis by me)

Or directly in the source code, https://github.com/sequelize/sequelize/blob/59b8a7bfa018b94ccfa6e30e1040de91d1e3d3dd/lib/model.js#L2028

@returns {Promise<{count: number, rows: Model[]}>}

So the thing is that you get an array of Model objects which you could navigate with their get() method. It's an unfortunate coincidence that you expected an array, and got an array so you thought it is "that" array. Try the {raw:true} thing, I guess it looks something like this:

db.Category.findAndCountAll({
    where: {},
    include: [
      {
        model: db.Question,
        as: "questions",
        attributes: [[db.Sequelize.fn('COUNT', 'id'), 'questionsCount']]
      }
    ],
    offset: limit * page,
    limit: limit,
    order: [["id", "ASC"]],
    raw: true                            // <--- hopefully it is this simple
  }) [...]

toJSON() is nearby too, https://github.com/sequelize/sequelize/blob/59b8a7bfa018b94ccfa6e30e1040de91d1e3d3dd/lib/model.js#L4341

  /**
   * Convert the instance to a JSON representation.
   * Proxies to calling `get` with no keys.
   * This means get all values gotten from the DB, and apply all custom getters.
   *
   * @see
   * {@link Model#get}
   *
   * @returns {object}
   */
  toJSON() {
    return _.cloneDeep(
      this.get({
        plain: true
      })
    );
  }

So it worked exactly because it did what you needed, removed the get() stuff and provided an actual JavaScript object matching your structure (POJSO? - sorry, I could not resist). I rarely use it and thus always forget, but the key background "trick" is that a bit contrary to its name, toJSON() is not expected to create the actual JSON string, but to provide a replacement object which still gets stringified by JSON.stringify(). (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON_behavior)


问:
Create-react-app not working - packages looking for funding
I installed node, then I ran npm install create-react-app, then ran npx create-react-app hello-world.

The last command did not go through because of some package funding, whatever that means.

How do I fix this?

I am using windows. Here is how my command prompt looks like:

答:
When you do "npm install create-react-app" you're installing in the current folder a CLI to ease up creating a React template for your projects. Doing "npx create-react-app hello-world" is redundant as you've already downloaded the create-react-app module, if you do not wish to save the CLI software and only create the template then it's a better approach.

Using the "-g" flag will allow you to use the CLI globally to create React projects on your computer ("npm install -g create-react-app" this might require certain permissions) instead of only the specific folder you're on.

Once you're done you must use the command "create-react-app 'your_project_name'" to use create-react-app to create your project. More information here https://reactjs.org/docs/create-a-new-react-app.html#create-react-app, to start the project just head inside the created folder and do "npm start".

Packages looking for funding is exactly what it says, the developers of these modules are looking for funding.


问:
solc --bin "faucet.sol" is not found
I try to compile my .sol file with solc --bin, but Terminal shows me "faucet.sol is not found".
The problem is that file exist in that location. I try to move them to other directory, but effect is the same.

I'm just added a screenshot which presents operation which I tried to accomplish.

I will be very grateful for some hint.

答:
Thanks for help. Solution is create a file in a root location ~ and run command

```<code>sudo solc --bin faucet.sol
</code>```

Title: solc --bin "faucet.sol" is not found

Body:
Thanks for help. Solution is create a file in a root location ~ and run command

sudo solc --bin faucet.sol


问:
Why am I getting an error "TypeError: system() takes at most 1 argument (3 given)"
I'm trying to make a script that takes information and stores it in a file for a different program

My code is this,

```<code>import os

currentinfo = input("Enter username: ")

os.system('echo', "Username:", currentinfo, ">> info.txt")

</code>```

The error I'm getting is,

```<code>os.system('echo', "Username:", currentinfo)
TypeError: system() takes at most 1 argument (3 given)
</code>```

How do I fix this?

I'm new to python, so bear with me.

答:
The problem is that Python sees 'echo', "Username:", currentinfo, and ">> info.txt" as different arguments instead of a concatenated string like you were hoping for. Variables passed to a function separated by commas are interpreted as arguments.

To fix this, either concatenate your string with the + operator or use a formated string(a much cleaner option).

Using the + operator:

```<code>os.system('echo Username: ' + currentinfo + ' >> info.txt')
</code>```

Using a formatted string:

```<code>os.system(f'echo Username: {currentinfo} >> info.txt')
</code>```

or:

```<code>os.system('echo Username: {} >> info.txt'.format(currentinfo))
</code>```

Body:
I'm trying to make a script that takes information and stores it in a file for a different program

My code is this,

import os

currentinfo = input("Enter username: ")

os.system('echo', "Username:", currentinfo, ">> info.txt")

The error I'm getting is,

os.system('echo', "Username:", currentinfo)
TypeError: system() takes at most 1 argument (3 given)

How do I fix this?

I'm new to python, so bear with me.

Body:
The problem is that Python sees 'echo', "Username:", currentinfo, and ">> info.txt" as different arguments instead of a concatenated string like you were hoping for. Variables passed to a function separated by commas are interpreted as arguments.

To fix this, either concatenate your string with the + operator or use a formated string(a much cleaner option).

Using the + operator:

os.system('echo Username: ' + currentinfo + ' >> info.txt')

Using a formatted string:

os.system(f'echo Username: {currentinfo} >> info.txt')

or:

os.system('echo Username: {} >> info.txt'.format(currentinfo))


问:
catch R tryCatch() out of bounds exception in order to ignore execption
Problem:

R tryCatch() needed to handle known error.

I am working with a word vector matrix to run the the vector word location. I am seeking to add a R tryCatch() to handle, or catch this subscript out of bounds. It is expected behavior for the word search.
What is the exact method to catch, to ignore, an exception in R? What exception code should I use to catch out of bounds?

For example:

```<code>word1 = 'This'
word2 = 'Happy'
</code>```

This combination would NOT be expected to match in this contextual search inside the word vector. So subscript out of bounds indicates that this match does not exist.

Code:

```<code>'''
    word_vectors[word1, , drop=FALSE] + word_vectors[word2, , drop=FALSE]
'''
</code>```

Error Message:

```<code>'''
run_glove_search(word1, word2, word_vectors)
Error in word_vectors[word1, , drop = FALSE] : subscript out of bounds
> View(word_vectors)
'''
</code>```

The error is due to the subscript out of bounds, which IS EXPECTED on word combinations that do not  match. Therefore, this is expected beharior.

Data example:
Note: the word matrix is a large matrix 75800, so I only show 1 row of statistics example

```<code>'''
This    0.175438308 0.1229126933    -0.792327086    -0.698233553    0.407953490 0.362040523 0.258780885 0.352198675 -0.170637061    -0.512016098    0.408881291 -0.0866425339   0.0510299517    -0.150036589    0.002336813 0.390699917 -0.635815296    -0.295312958
'''
</code>```

答:
Code solution:
TryCatch() with error = function(e) and do nothing, since I know and expect that this error will occur, so I can just assign NULL to the e of function(e) since I do not need any error message. </p>

```<code>  tryCatch({
    gws <- word_vectors[word1, , drop=FALSE] + word_vectors[word2, , drop=FALSE]
    cos_sim = sim2(x = word_vectors, y = gws, method = "cosine", norm = "l2")
    head(sort(cos_sim[,1], decreasing = TRUE), 7)
    },
    error = function(e){e=NULL}
  )
</code>```

Body:
Problem:

R tryCatch() needed to handle known error.

I am working with a word vector matrix to run the the vector word location. I am seeking to add a R tryCatch() to handle, or catch this subscript out of bounds. It is expected behavior for the word search.
What is the exact method to catch, to ignore, an exception in R? What exception code should I use to catch out of bounds?

For example:

word1 = 'This'
word2 = 'Happy'

This combination would NOT be expected to match in this contextual search inside the word vector. So subscript out of bounds indicates that this match does not exist.

Code:

'''
    word_vectors[word1, , drop=FALSE] + word_vectors[word2, , drop=FALSE]
'''

Error Message:

'''
run_glove_search(word1, word2, word_vectors)
Error in word_vectors[word1, , drop = FALSE] : subscript out of bounds
> View(word_vectors)
'''

The error is due to the subscript out of bounds, which IS EXPECTED on word combinations that do not  match. Therefore, this is expected beharior.

Data example:
Note: the word matrix is a large matrix 75800, so I only show 1 row of statistics example

'''
This    0.175438308 0.1229126933    -0.792327086    -0.698233553    0.407953490 0.362040523 0.258780885 0.352198675 -0.170637061    -0.512016098    0.408881291 -0.0866425339   0.0510299517    -0.150036589    0.002336813 0.390699917 -0.635815296    -0.295312958
'''

Body:
Code solution:
TryCatch() with error = function(e) and do nothing, since I know and expect that this error will occur, so I can just assign NULL to the e of function(e) since I do not need any error message.

  tryCatch({
    gws <- word_vectors[word1, , drop=FALSE] + word_vectors[word2, , drop=FALSE]
    cos_sim = sim2(x = word_vectors, y = gws, method = "cosine", norm = "l2")
    head(sort(cos_sim[,1], decreasing = TRUE), 7)
    },
    error = function(e){e=NULL}
  )


问:
Prevent sort trigger on a table column when resizing it
How can I prevent the sort being triggered on a table column when resizing the column with the resizable component? When the mouseup event occurs over the th that's being resized it triggers the sort. I tried to prevent it in the nzResizeEnd event but I guess thats's too late. Can some one help me please? Example https://stackblitz.com/edit/angular-jqs53u?embed=1&file=src/app/app.component.ts

Went to file the issue in the library repo and someone already has 11 days ago. Let's hope for a quick fix. https://github.com/NG-ZORRO/ng-zorro-antd/issues/5199

答:
Solved the issue by disabling pointer events while resizing.

Component.ts:
resizing: boolean = false;

Template:

```<code><th
  [class.pointer-events-none]="resizing"
  (nzResizeStart)="resizing = true"
  (nzResizeEnd)="resizing = false"
>
</code>```

Style:

```<code>.pointer-events-none {
  pointer-events: none;
}
</code>```

The stackblitz shows the working state. Now resizing doesn't cause a change in sort direction.

Found out about css pointer-events in another StackOverflow answer.

Also want to thank you Poul Kruijt for your help.

Body:
Solved the issue by disabling pointer events while resizing.

Component.ts:
resizing: boolean = false;

Template:

<th
  [class.pointer-events-none]="resizing"
  (nzResizeStart)="resizing = true"
  (nzResizeEnd)="resizing = false"
>

Style:

.pointer-events-none {
  pointer-events: none;
}

The stackblitz shows the working state. Now resizing doesn't cause a change in sort direction.

Found out about css pointer-events in another StackOverflow answer.

Also want to thank you Poul Kruijt for your help.


问:
Turkish Vowel Letter Recognition
I would like to generate code;
When you enter sentence, the system will display only consonant letters for these sentence.

I generated code but the code does not recognize Special Turkish Vowel Letter
 like  İ,Ü,Ö as a Constant letter. Only recognize English Latin vowel letter.

How can I fix that?

```<code>#include <stdio.h>
#include <string.h>
#include <time.h>
#include <wchar.h>

int vowel (char);

int main ()
{
    setlocale(LC_ALL, "Turkish");
    char s[100], t[100];
    int c, d = 0;
    printf ("Enter sentence vowels will ve removed:\n");
    gets (s);
    for (c = 0; s[c] != '\0'; c++)
    {
        if (vowel (s[c]) == 0)
        {
            t[d] = s[c];
            d++;
        }
    }
    t[d] = '\0';
    strcpy (s, t);
    printf ("Letters without vowels: %s\n", s);
    return 0;
}

int vowel (char ch)
{
    if (ch == 'a' || ch == 'A'
     || ch == 'e' || ch == 'E'
     || ch == 'ı' || ch == 'I'
     || ch == 'i' || ch == 'İ'
     || ch == 'o' || ch == 'O'
     || ch == 'ö;' || ch == 'Ö'
     || ch == 'u' || ch == 'U'
     || ch == 'ü' || ch == 'Ü')
      return 1;
    else
      return 0;
}
</code>```

答:
Dear @algrebe thank you very much for your quick reply. I had run code on https://onlinegdb.com/BkxnoKZ2L  but Turkish vowels shows as questionmark at onlinegdb</p>

```<code>Enter sentence vowels will ve removed:
avbcdxyÖÜ
setters without vowels: vbcdxys��
</code>```

Title: Turkish Vowel Letter Recognition

Body:
I would like to generate code;
When you enter sentence, the system will display only consonant letters for these sentence.

I generated code but the code does not recognize Special Turkish Vowel Letter
 like  İ,Ü,Ö as a Constant letter. Only recognize English Latin vowel letter.

How can I fix that?

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <wchar.h>

int vowel (char);

int main ()
{
    setlocale(LC_ALL, "Turkish");
    char s[100], t[100];
    int c, d = 0;
    printf ("Enter sentence vowels will ve removed:\n");
    gets (s);
    for (c = 0; s[c] != '\0'; c++)
    {
        if (vowel (s[c]) == 0)
        {
            t[d] = s[c];
            d++;
        }
    }
    t[d] = '\0';
    strcpy (s, t);
    printf ("Letters without vowels: %s\n", s);
    return 0;
}

int vowel (char ch)
{
    if (ch == 'a' || ch == 'A'
     || ch == 'e' || ch == 'E'
     || ch == 'ı' || ch == 'I'
     || ch == 'i' || ch == 'İ'
     || ch == 'o' || ch == 'O'
     || ch == 'ö;' || ch == 'Ö'
     || ch == 'u' || ch == 'U'
     || ch == 'ü' || ch == 'Ü')
      return 1;
    else
      return 0;
}

Body:
Dear @algrebe thank you very much for your quick reply. I had run code on https://onlinegdb.com/BkxnoKZ2L  but Turkish vowels shows as questionmark at onlinegdb

Enter sentence vowels will ve removed:
avbcdxyÖÜ
setters without vowels: vbcdxys��


问:
How to let a java program comunicate with a different java program
I am trying to build a system that loadbalances minecraft players across multiple servers and creates new minecraft servers. I made a plugin to loadbalance players and it works like a charm. But now I want to make a system that creates new servers based on the data it receives from the plugin.

This system is completely seperate from the plugin. But how do I make it so the plugin sends some sort of command to the server system so it knows to create a new server. I have looked into Sockets but was wondering if this is the best solution. Maybe a Rest api will work aswell?

答:
In my opinion the best solution is sockets based on your own protocol, it will be much more productive, than http or something else.
I can suggest using this lightweight socket library written by me -
Sonder.
It's working directly on sockets using nio.</p>


问:
ASP.NET MVC 5 Form AJAX Post Without Page Refresh
I have a basic ASP.NET MVC 5 page with an @HTML.BeginForm object on it. This form is going to be very dynamic and is going to have various things added to it as the user is using it.

I want to have several buttons within this form that are going to before AJAX Post calls to the controller to gather data from a database (for populating select boxes) but I don't want them to actually submit the form. I want a single button at the bottom of the form which says "Submit" and actually submits the entire form when the user is done.

I want to have additional buttons within the @HTML.BeginForm object that are able to post to the server to gather data from a database without actually submitting the entire form. I have the jquery.unobtrusive-ajax.min.js library added to my page but that doesn't seem to help.

Any time a button is clicked in the form it instantly attempts to submit the entire form and refreshes the page. How do I work around this?

答: I figured this out on my own. You must have the jquery.unobtrusive-ajax.min.js library, but on top of that you must use an <input /> element rather than a <button /> element. I believe any <button /> element within an @HTML.BeginForm element will automatically submit the form. I switched from <button /> to <input /> and it's working properly now.


问:
How to combine two flat lists into one nested object
I have three lists which contains three same properties in each collection. I want to combine a result into one collection. Ex classes structure is as below

```<code>public class Order
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }

    // Few other Properties of OrderDetail
}
public class PaymentDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form PaymentDetail
}

public class CouponUsageDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form CouponUsageDetail
}
</code>```

This type of output is coming from one API service where each class is in form of list object (JSON format) and we need to perform some operations on this. All three properties (ProductId,CustomerId, OrderId) contains same values in each collection which means all three properties are repeated in each collection. We need to perform some look ups on these collections. So in normal way what we can do with it is as - start a foreach from Order list and filter all three matching properties of PaymentDetail and CouponUsageDetail. But it would be costlier in term of performance when the data size is increased. So thought of making nesting structure upfront and avoid lookups. If we make the output nested as below this will help to avoid lookups on PaymentDetail and CouponUsageDetail.
Ex - we are receiving JOSN in below format

```<code>{"Orders":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"PaymentDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"CouponUsageDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}]}
</code>```

and with this output we want to form object as

```<code>public class OrderDetails
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties of OrderDetail

    List<PaymentDetail> PaymentDetail { get; set; }
    List<CouponUsageDetail> CouponUsageDetail { get; set; }
}
</code>```

Can you guide, what would be the best optimum usage of linq where we can combine all these three matching properties and make it just one nested structure better?
Thank You!
 Note: I know this structure needs to be normalized but please ignore the normalization rule here as this is not in our control.

答:
What are you describing sounds like two standard multi-key LINQ group joins. They are quite efficient (LINQ to Objects implementation uses prepared fast hash based lookups), so no further optimizations are needed:</p>

```<code>var orderDetails = (
    from o in data.Orders
    join p in data.PaymentDetails
        on new { o.ProductId, o.CustomerId, o.OrderId }
        equals new { p.ProductId, p.CustomerId, p.OrderId }
        into orderPaymentDetails
    join c in data.CouponUsageDetails
        on new { o.ProductId, o.CustomerId, o.OrderId }
        equals new { c.ProductId, c.CustomerId, c.OrderId }
        into orderCouponUsageDetails
    select new OrderDetails
    {
        ProductId = o.ProductId,
        CustomerId = o.CustomerId,
        OrderId = o.OrderId,
        // Few other Properties of OrderDetail
        PaymentDetail = orderPaymentDetails.ToList(),
        CouponUsageDetail = orderCouponUsageDetails.ToList(),
    })
    .ToList();
</code>```

Body:
I have three lists which contains three same properties in each collection. I want to combine a result into one collection. Ex classes structure is as below

public class Order
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }

    // Few other Properties of OrderDetail
}
public class PaymentDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form PaymentDetail
}

public class CouponUsageDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form CouponUsageDetail
}

This type of output is coming from one API service where each class is in form of list object (JSON format) and we need to perform some operations on this. All three properties (ProductId,CustomerId, OrderId) contains same values in each collection which means all three properties are repeated in each collection. We need to perform some look ups on these collections. So in normal way what we can do with it is as - start a foreach from Order list and filter all three matching properties of PaymentDetail and CouponUsageDetail. But it would be costlier in term of performance when the data size is increased. So thought of making nesting structure upfront and avoid lookups. If we make the output nested as below this will help to avoid lookups on PaymentDetail and CouponUsageDetail.
Ex - we are receiving JOSN in below format

{"Orders":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"PaymentDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"CouponUsageDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}]}

and with this output we want to form object as

public class OrderDetails
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties of OrderDetail

    List<PaymentDetail> PaymentDetail { get; set; }
    List<CouponUsageDetail> CouponUsageDetail { get; set; }
}

Can you guide, what would be the best optimum usage of linq where we can combine all these three matching properties and make it just one nested structure better?
Thank You!
 Note: I know this structure needs to be normalized but please ignore the normalization rule here as this is not in our control.

Body:
What are you describing sounds like two standard multi-key LINQ group joins. They are quite efficient (LINQ to Objects implementation uses prepared fast hash based lookups), so no further optimizations are needed:

var orderDetails = (
    from o in data.Orders
    join p in data.PaymentDetails
        on new { o.ProductId, o.CustomerId, o.OrderId }
        equals new { p.ProductId, p.CustomerId, p.OrderId }
        into orderPaymentDetails
    join c in data.CouponUsageDetails
        on new { o.ProductId, o.CustomerId, o.OrderId }
        equals new { c.ProductId, c.CustomerId, c.OrderId }
        into orderCouponUsageDetails
    select new OrderDetails
    {
        ProductId = o.ProductId,
        CustomerId = o.CustomerId,
        OrderId = o.OrderId,
        // Few other Properties of OrderDetail
        PaymentDetail = orderPaymentDetails.ToList(),
        CouponUsageDetail = orderCouponUsageDetails.ToList(),
    })
    .ToList();


问:
MongoDB aggregate query how to split the array element
In my mongodb, i have few collections, i want to create a new collection by comparing the collection 1 and collection 2 using pymongo.

```<code>Collection 1 :
Object id       timestamp                          Prof_Name   SUBJECT
abc67478898k  ISODate("2018-01-03T09:26:37.541Z")   ABDC      "sub1, sub2, sub3"
jjjjjjjjjj    ISODate("2018-01-03T09:26:37.541Z")   XYZ       "sub2, sub4, sub8"

Collection 2 :
Object id   timestamp               UUID   SUBJECT_ID            rating score
3333333    ISODate("2018-01-03TZ")  7897  "sub1,sub4, sub7"     7      10
444444     ISODate("2018-01-03TZ")  4532   "sub2"               4      6
777777     ISODate("2018-01-03TZ")  7876  "sub1,sub2,sub3"      8      8
1111111    ISODate("2018-01-03TZ")   654   "sub1,sub3"          7      8
</code>```

Json is as below :

```<code>data1 :
{ "_id" : ObjectId("7a563a5a5560fd08da86dc44"), "Prof_Name" : "Jack", "timestamp" : ISODate("2018-01-10T16:08:26.613Z"), "SUBJECT" : ["Maths", "Chemistry", "Machinery1", "Ele1"] }
{ "_id" : ObjectId("7a563a5a5560fd08da86dc45"), "Prof_Name" : "Mac", "timestamp" : ISODate("2018-01-10T16:08:26.613Z"), "SUBJECT" : ["Chemistry", "CS", "German"] }
{ "_id" : ObjectId("7a563a5a5560fd08da86dc46"), "Prof_Name" : "Bill", "timestamp" : ISODate("2018-01-10T16:08:26.613Z"), "SUBJECT" : ["German"] }

data2 :
{ "_id" : ObjectId("7a563a5a5560fd08da86dc46"), "Rating" : 6, "UUID" : 8123, "timestamp" : ISODate("2018-01-10T16:08:26.613Z"), "SUBJECT_ID" : "Maths", "ID" : "OI-123" }
{ "_id" : ObjectId("7a563a5a5560fd08da86dc47"), "Rating" : 7, "UUID" : 8123, "timestamp" : ISODate("2018-01-10T16:08:26.613Z"), "SUBJECT_ID" : "Machinery1, Maths, French, German", "ID" : "OI-98" }
</code>```

I'm trying to generate 3rd collection, where for each subject by Prof_name find matching subjects in collection2 and the UUID and UUID_count between a certain timestamp and my mongo query is as below:

```<code>db.data1.aggregate([
  {"$lookup":{
    "from":"data2",
    "let":{"subject":{"$split":["$SUBJECT",", "]}},
    "pipeline":[
      {"$match": {"expr":{"$and":[{"$eq":[{"$year":"$timestamp"}, 2016]}, {"$eq":[{"$month":"$timestamp"}, 1]}]}}},
      {"$addFields":{"SUBJECT_ID":{"$split":["$SUBJECT_ID",", "]},"SUBJECT":"$$subject"}},
      {"$unwind":"$SUBJECT"},
      {"$match":{"$expr":{"$in":["$SUBJECT","$SUBJECT_ID"]}}},
      {"$facet":{
        "UUID":[{"$group":{"_id":{"id":"$_id","UUID":"$UUID"}}},{"$count":"UUID_Count"}],
        "REST":[
          {"$group":{"_id":null,"subjects_list":{"$addToSet":"$SUBJECT"},"UUID_distinct_list":{"$addToSet":"$UUID"}}},
          {"$addFields":{"subject_count":{"$size":"$subjects_list"},"UUID_distinct_count":{"$size":"$UUID_distinct_list"}}},
          {"$project":{"_id":0}}
         ]
      }},
      {"$replaceRoot":{"newRoot":{"$mergeObjects":[{"$arrayElemAt":["$UUID",0]},{"$arrayElemAt":["$REST",0]}]}}}
    ],
    "as":"ref_data"
  }},
  {"$unwind":{"path":"$ref_data","preserveNullAndEmptyArrays":true}},
  {"$addFields":{"ref_data.Prof_Name":"$Prof_Name"}},
  {"$replaceRoot":{"newRoot":"$ref_data"}},
  {"$out":"data3"}
])
</code>```

The abov query works fine if the SUBJECT is a string as :

```<code>SUBJECT
"sub1, sub2, sub3"
"sub2, sub4, sub8"
</code>```

My question is : How do I change the query if  the SUBJECT column as an array of elements. Example as below :

```<code>subjects1
["sub1", "sub2", "sub3"]
["sub2", "sub4", "sub8"]
</code>```

If I try the same query i get an error something like , split on string  found an array.

答:
i think you want to use

```<code>> new Array("sub1, sub2, sub3")
</code>```

[ "sub1, sub2, sub3" ]

my console ss

Body:
In my mongodb, i have few collections, i want to create a new collection by comparing the collection 1 and collection 2 using pymongo.

Collection 1 :
Object id       timestamp                          Prof_Name   SUBJECT
abc67478898k  ISODate("2018-01-03T09:26:37.541Z")   ABDC      "sub1, sub2, sub3"
jjjjjjjjjj    ISODate("2018-01-03T09:26:37.541Z")   XYZ       "sub2, sub4, sub8"

Collection 2 :
Object id   timestamp               UUID   SUBJECT_ID            rating score
3333333    ISODate("2018-01-03TZ")  7897  "sub1,sub4, sub7"     7      10
444444     ISODate("2018-01-03TZ")  4532   "sub2"               4      6
777777     ISODate("2018-01-03TZ")  7876  "sub1,sub2,sub3"      8      8
1111111    ISODate("2018-01-03TZ")   654   "sub1,sub3"          7      8

Json is as below :

data1 :
{ "_id" : ObjectId("7a563a5a5560fd08da86dc44"), "Prof_Name" : "Jack", "timestamp" : ISODate("2018-01-10T16:08:26.613Z"), "SUBJECT" : ["Maths", "Chemistry", "Machinery1", "Ele1"] }
{ "_id" : ObjectId("7a563a5a5560fd08da86dc45"), "Prof_Name" : "Mac", "timestamp" : ISODate("2018-01-10T16:08:26.613Z"), "SUBJECT" : ["Chemistry", "CS", "German"] }
{ "_id" : ObjectId("7a563a5a5560fd08da86dc46"), "Prof_Name" : "Bill", "timestamp" : ISODate("2018-01-10T16:08:26.613Z"), "SUBJECT" : ["German"] }

data2 :
{ "_id" : ObjectId("7a563a5a5560fd08da86dc46"), "Rating" : 6, "UUID" : 8123, "timestamp" : ISODate("2018-01-10T16:08:26.613Z"), "SUBJECT_ID" : "Maths", "ID" : "OI-123" }
{ "_id" : ObjectId("7a563a5a5560fd08da86dc47"), "Rating" : 7, "UUID" : 8123, "timestamp" : ISODate("2018-01-10T16:08:26.613Z"), "SUBJECT_ID" : "Machinery1, Maths, French, German", "ID" : "OI-98" }

I'm trying to generate 3rd collection, where for each subject by Prof_name find matching subjects in collection2 and the UUID and UUID_count between a certain timestamp and my mongo query is as below:

db.data1.aggregate([
  {"$lookup":{
    "from":"data2",
    "let":{"subject":{"$split":["$SUBJECT",", "]}},
    "pipeline":[
      {"$match": {"expr":{"$and":[{"$eq":[{"$year":"$timestamp"}, 2016]}, {"$eq":[{"$month":"$timestamp"}, 1]}]}}},
      {"$addFields":{"SUBJECT_ID":{"$split":["$SUBJECT_ID",", "]},"SUBJECT":"$$subject"}},
      {"$unwind":"$SUBJECT"},
      {"$match":{"$expr":{"$in":["$SUBJECT","$SUBJECT_ID"]}}},
      {"$facet":{
        "UUID":[{"$group":{"_id":{"id":"$_id","UUID":"$UUID"}}},{"$count":"UUID_Count"}],
        "REST":[
          {"$group":{"_id":null,"subjects_list":{"$addToSet":"$SUBJECT"},"UUID_distinct_list":{"$addToSet":"$UUID"}}},
          {"$addFields":{"subject_count":{"$size":"$subjects_list"},"UUID_distinct_count":{"$size":"$UUID_distinct_list"}}},
          {"$project":{"_id":0}}
         ]
      }},
      {"$replaceRoot":{"newRoot":{"$mergeObjects":[{"$arrayElemAt":["$UUID",0]},{"$arrayElemAt":["$REST",0]}]}}}
    ],
    "as":"ref_data"
  }},
  {"$unwind":{"path":"$ref_data","preserveNullAndEmptyArrays":true}},
  {"$addFields":{"ref_data.Prof_Name":"$Prof_Name"}},
  {"$replaceRoot":{"newRoot":"$ref_data"}},
  {"$out":"data3"}
])

The abov query works fine if the SUBJECT is a string as :

SUBJECT
"sub1, sub2, sub3"
"sub2, sub4, sub8"

My question is : How do I change the query if  the SUBJECT column as an array of elements. Example as below :

subjects1
["sub1", "sub2", "sub3"]
["sub2", "sub4", "sub8"]

If I try the same query i get an error something like , split on string  found an array.

Body:
i think you want to use

> new Array("sub1, sub2, sub3")

[ "sub1, sub2, sub3" ]

my console ss


问:
Express server not allowing CORS even though I'm using Access-Control-Allow-Origin *
The browser error shows:

```<code>Access to XMLHttpRequest at <https://dev-api.mydomain.net/auth/login> from origin 'https://dev.mydomain.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

I also tried using my actual specific domain 'https://dev.mydomain.net'as the Access-Control-Allow-Origin value, and it didn't work, as well as trying the key 'origin' as well.

How can I get the server to accept requests from my domain?

```<code>import express from 'express'
import cors from 'cors'
import router from '../../routes'

const restServer = express()

restServer.use(cors({
  'Access-Control-Allow-Origin': '*'
}))

restServer.use('', router)

export default restServer
</code>```

答:
```<code>const morgan = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();

// * Logging middleware
app.use(morgan('dev'));

// * CORS headers setter
app.use(cors());
</code>```

Use it like this, No need to set Manually 'Access-Control-Allow-Origin' While using CORS Module!

Body:
The browser error shows:

Access to XMLHttpRequest at <https://dev-api.mydomain.net/auth/login> from origin 'https://dev.mydomain.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I also tried using my actual specific domain 'https://dev.mydomain.net'as the Access-Control-Allow-Origin value, and it didn't work, as well as trying the key 'origin' as well.

How can I get the server to accept requests from my domain?

import express from 'express'
import cors from 'cors'
import router from '../../routes'

const restServer = express()

restServer.use(cors({
  'Access-Control-Allow-Origin': '*'
}))

restServer.use('', router)

export default restServer

Body:
const morgan = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();

// * Logging middleware
app.use(morgan('dev'));

// * CORS headers setter
app.use(cors());

Use it like this, No need to set Manually 'Access-Control-Allow-Origin' While using CORS Module!


问:
Does a Silverlight memory profiler exist?
CLR profiler does not seem to work with the Silverlight CLR. Does another memory profiler exist?</p>

答: I use free XTE Profiler which also works with Silverlight Standard and Out of Browser applications. Shows live memory usage as well.</p>

OwnerDisplayName: Sander

ContentLicense: CC BY-SA 2.5


问:
Creating a heatmap from a list of nested dictionaries in python
I'm pretty new to python, and currently I'm stuck with writing a heatmap for comparing word vectors for different languages.

The data I have looks like this:

```<code>data = [{'de':  {'de': [[1]], 'es': [[0.9644323]], 'fr': [[0.9419257]], 'hu': [[0.9297902]]}},
        {'fr':   {'fr': [[1]], 'de': [[0.9419257]], 'es': [[0.9382719]], 'hu': [[0.91247433]]}},
        {'hu':  {'hu': [[1]], 'de': [[0.9419257]], 'es': [[0.9382719]], 'fr': [[0.91247433]]}}]

</code>```

The data shows similarity between the phrase in one language to its translations (e.g. in the first dictionary I have a German phrase that I compare to ES, HU and FR translations). I would like to have one heatmap for this list of nested dictionaries.  How do I visualise it in a heatmap? I tried looking at heatmaps in seaborn, but was confused by the fact my dictionary is nested.

答:
If solving quickly. You first transform your list with dictionaries to dataframe and then plot it with seaborn's heatmap. I am sure there could be more elegant solutions, however.</p>

```<code>import pandas as pd
import seaborn as sns
%matplotlib inline

frames = []

for d in data:
    frames.append(pd.DataFrame.from_dict(d, orient='index'))

res = pd.concat(frames)
res = res.applymap(lambda x: x[0][0])
sns.heatmap(res, annot=True)
</code>```

Body:
I'm pretty new to python, and currently I'm stuck with writing a heatmap for comparing word vectors for different languages.

The data I have looks like this:

data = [{'de':  {'de': [[1]], 'es': [[0.9644323]], 'fr': [[0.9419257]], 'hu': [[0.9297902]]}},
        {'fr':   {'fr': [[1]], 'de': [[0.9419257]], 'es': [[0.9382719]], 'hu': [[0.91247433]]}},
        {'hu':  {'hu': [[1]], 'de': [[0.9419257]], 'es': [[0.9382719]], 'fr': [[0.91247433]]}}]

The data shows similarity between the phrase in one language to its translations (e.g. in the first dictionary I have a German phrase that I compare to ES, HU and FR translations). I would like to have one heatmap for this list of nested dictionaries.  How do I visualise it in a heatmap? I tried looking at heatmaps in seaborn, but was confused by the fact my dictionary is nested.

Body:
If solving quickly. You first transform your list with dictionaries to dataframe and then plot it with seaborn's heatmap. I am sure there could be more elegant solutions, however.

import pandas as pd
import seaborn as sns
%matplotlib inline

frames = []

for d in data:
    frames.append(pd.DataFrame.from_dict(d, orient='index'))

res = pd.concat(frames)
res = res.applymap(lambda x: x[0][0])
sns.heatmap(res, annot=True)


问:
Why does VS Code not offer methods with autocompletion?
I noticed that VS Code doesn't know very many methods and doesn't offer them at autocompletion, for instance:

Did I break something? No one's ever had this problem?

答:
Javascript is not a statically typed language, so a IDE or Text editor cannot infer what is the type of your variables. In some cases, it does infer, when you use classes, for instance, but note that it is not a limitation of vscode, it is a limitation of dynamically typed languages, like Javascript.
 I suggest that you take a look at TypeScript, a language that can be transpiled to Javascript and that let you statically type you variables, providing the ability to have this kind of feature.

https://www.typescriptlang.org/


问:
h264 to FLV conversion, ambiguous FrameType definition: What differentiates a Key Frame vs an Inter Frame?
I'm trying to write out an Annex B formatted h264 bitstream in an FLV container over RTMP in an Android app. After reading this SO answer and several more, I understand my Annex B bitstream first has to be converted to AVCC before being wrapped in an FLV container.

That said, the FLV container spec is a bit unclear in the wrapping of its video tags. It requires a FrameType which can be:

keyframe (For AVC a seekable frame)

interframe (For AVC a non seekable frame)

Disposable interframe (h263 only)

Generated keyframe (serverside only)

Video info / command frame (The message string contains a byte, 0 or 1 meaning either start of client seeking video frame sequence, or end of client seeking frame sequence)

When writing IDR or non-IDR AVC frames, i.e VCL NAL units, it's clear that options 1 and 2 should be used respectively. However, my h264 bitstream also contains non-VCL NAL units, specifically SEI payload type 47 (Display Orientation). It's not clear whether this fits when going from AVC to FLV per the spec. Do I simply consider the SEI a non seekable frame? What is a "frame" from FLV's point of view?

答: According to "High Efficiency Video Coding: Coding Tools and Specification" by Mathias Wien, all SEI (Supplemental Enhancement Information) messages are defined as information not needed for decoding and reconstruction of the video. In general, not all video formats can represent such information. For this one specifically, a display orientation message does not represent any specific video frame, because it is a flag that persists until changed.</p>


问:
PHP: Loading content based on POST / GET user input
thank you for looking into my question. It's purely related to PHP POST / GET functions.

Here is my code :

index.php

```<code><html>
<body>
 <p>
<center>
<form action="story_get.php" method="post">
<label for="name">Name:</label> <input type="text" name="name">
<label for="age">Age:</label><input type="number" size=2 name="age"><p>
<label for="place">Place:</label> <input type="text" name="place"><p>

 <label for="storys">Choose a story:</label>
  <select name="story" id="story">
    <option value="sea">Sea side</option>
    <option value="mount">Mountain</option>
  </select>

<p>

<input type="submit" value="Enter">
<button type="reset" value="Reset">Reset</button>
</form>

</body>
</html>
</code>```

story_get.php

```<code><html>
<body>

<center>
<h1>Welcome <font color=red><i><?php echo $_POST["name"]; ?></i></font>, age of <font color=red><i><?php echo $_POST["age"]; ?></i></font><br>
to the wonderfull land of <br><font color=red><i><?php echo $_POST["place"]; ?></i></font>
<?php echo $_POST["story"]; ?>

 <p><a href=index.php>Edit</a>
</body>
</html>
</code>```

My code is working fine, but instead of <?php echo $_POST["story"]; ?> I want to print 200+ words story relating to what User has chosen. I hope You understand what I'm trying to achieve, and be able to suggest easy solutions. Thanks in advance

答:
...instead of <?php echo $_POST["story"]; ?> I want to print 200+ words story relating to what User has chosen.

Use a conditional if() or switch statement to see if your $_POST['story'] is set and equal to one of your options for story.

//--> ON story_get.php
//--> (Provided the $_POST variable in fact has the values assigned to the global array)
//--> use var_dump($_POST) on story_get.php to check if the global $_POST array has
//--> key/value pairs coming from your index.php page

// set variables that have your story information.
$seaside = //--> Your story about the sea side
$mountain = //--> Your story about the mountain
$output = null; //--> Empty variable to hold display info from conditional
//--> Now to see if the form element that selects story is set using isset
if(isset($_POST['story']){
  //--> Now that we know the input in the form that holds the value for story isset
  //--> Check to see if it is set and then declare a variable and assign it to that variable
  $story = $_POST['story'];
  if($story === 'sea'){
    $output = $seaside;
  }elseif($story === 'mount'){
    $output = $mountain;
  }else{
    $output = //--> Set a default setting that displays output here if neither story is selected.
  }
}

```

<p>Echo the variable <code>$output</code> where you wish to display your story content within the html doc</p>

<pre class="lang-html prettyprint-override"><code><div>
  <?=$output?>

  <!--// OR //-->

  <?php echo $output; ?>
</div>
</code>```

Body:
thank you for looking into my question. It's purely related to PHP POST / GET functions.

Here is my code :

index.php

<form action="story_get.php" method="post">
Name: <input type="text" name="name">
Age:<input type="number" size=2 name="age">

Place: <input type="text" name="place">

 Choose a story:
  <select name="story" id="story">
    <option value="sea">Sea side</option>
    <option value="mount">Mountain</option>
  </select>

<input type="submit" value="Enter">
<button type="reset" value="Reset">Reset</button>
</form>

story_get.php

Welcome <?php echo $_POST["name"]; ?>, age of <?php echo $_POST["age"]; ?>

to the wonderfull land of
<?php echo $_POST["place"]; ?>
<?php echo $_POST["story"]; ?>

Edit

My code is working fine, but instead of <?php echo $_POST["story"]; ?> I want to print 200+ words story relating to what User has chosen. I hope You understand what I'm trying to achieve, and be able to suggest easy solutions. Thanks in advance

Body:
...instead of <?php echo $_POST["story"]; ?> I want to print 200+ words story relating to what User has chosen.

Use a conditional if() or switch statement to see if your $_POST['story'] is set and equal to one of your options for story.

//--> ON story_get.php
//--> (Provided the $_POST variable in fact has the values assigned to the global array)
//--> use var_dump($_POST) on story_get.php to check if the global $_POST array has
//--> key/value pairs coming from your index.php page

// set variables that have your story information.
$seaside = //--> Your story about the sea side
$mountain = //--> Your story about the mountain
$output = null; //--> Empty variable to hold display info from conditional
//--> Now to see if the form element that selects story is set using isset
if(isset($_POST['story']){
  //--> Now that we know the input in the form that holds the value for story isset
  //--> Check to see if it is set and then declare a variable and assign it to that variable
  $story = $_POST['story'];
  if($story === 'sea'){
    $output = $seaside;
  }elseif($story === 'mount'){
    $output = $mountain;
  }else{
    $output = //--> Set a default setting that displays output here if neither story is selected.
  }
}

Echo the variable $output where you wish to display your story content within the html doc

<div>
  <?=$output?>

  <!--// OR //-->

  <?php echo $output; ?>
</div>


问:
Stored procedure output variable being stored as input/output type
I'm attempting to get the metadata for a stored procedure in Microsoft SQL Server using the Java SQL API.

This is the structure of the stored procedure:

```<code>CREATE PROCEDURE [dbo].[testproc]
    (@rolloverType AS integer,
     @retval nvarchar(50) output)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT @retval = [col1]
    FROM [dbo].[Table_1]
    WHERE col3 = @rolloverType;
END
GO
</code>```

However, the Java SQL API is saying that @retval is an INOUT type, and Microsoft SQL Server Management Studio also shows this parameter as an Input/Output type. How can I construct this stored procedure so that @retval is only of type Output?

答: If Management Studio sees @retval as OUTPUT, you will be able to read this value from outside. The fact that @retval is also marked as Input is irrelevant.

Body:
I'm attempting to get the metadata for a stored procedure in Microsoft SQL Server using the Java SQL API.

This is the structure of the stored procedure:

CREATE PROCEDURE [dbo].[testproc]
    (@rolloverType AS integer,
     @retval nvarchar(50) output)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT @retval = [col1]
    FROM [dbo].[Table_1]
    WHERE col3 = @rolloverType;
END
GO

However, the Java SQL API is saying that @retval is an INOUT type, and Microsoft SQL Server Management Studio also shows this parameter as an Input/Output type. How can I construct this stored procedure so that @retval is only of type Output?


问:
How to use 0/10 in cron in a yaml file?
I'm trying to use a cron job referenced in a yaml file part as part of my CircleCI CI system:

I would like a job to run every 10 mins using the 0/10 * * * * format but I get:

Config does not conform to schema

So how to use 0/10 in cron in a yaml file?`

Using a valid cron expression:

```<code>https://crontab.guru/#0/10_*_*_*_*
</code>```

I get

```<code>Config does not conform to schema:
{:workflows {:hourly {:triggers [{:schedule {:cron (not (:circleci.specs.cron/posix-expr \"0/10 * * * *\"))}}]}}}
</code>```

I tried various format such as

```<code>cron: "0/10 * * * *"
cron: 0/10 * * * *
cron: "0\/10 * * * *"
cron: 0\/10 * * * *
</code>```

but none were valid for allowing the slash.

Rest of section for context:

```<code>  hourly:
    triggers:
      - schedule:
          cron: "0/10 * * * *"
          filters:
            branches:
              only:
                - master
                - circleci-project-setup:
</code>```

答:
The docs say

cron key is defined using POSIX crontab syntax.

The linked manpage does not specify /. It is non-standard and apparently not supported. Wikipedia says that

POSIX does not define a use for slashes; its rationale (commenting on a BSD extension) notes that the definition is based on System V format but does not exclude the possibility of extensions

So you just can't use / here.

You can use the equivalent

```<code>"0,10,20,30,40,50 * * * *"
</code>```

Title: How to use 0/10 in cron in a yaml file?

Body:
I'm trying to use a cron job referenced in a yaml file part as part of my CircleCI CI system:

I would like a job to run every 10 mins using the 0/10 * * * * format but I get:

Config does not conform to schema

So how to use 0/10 in cron in a yaml file?`

Using a valid cron expression:

https://crontab.guru/#0/10_*_*_*_*

I get

Config does not conform to schema:
{:workflows {:hourly {:triggers [{:schedule {:cron (not (:circleci.specs.cron/posix-expr \"0/10 * * * *\"))}}]}}}

I tried various format such as

cron: "0/10 * * * *"
cron: 0/10 * * * *
cron: "0\/10 * * * *"
cron: 0\/10 * * * *

but none were valid for allowing the slash.

Rest of section for context:

  hourly:
    triggers:
      - schedule:
          cron: "0/10 * * * *"
          filters:
            branches:
              only:
                - master
                - circleci-project-setup:

Body:
The docs say

cron key is defined using POSIX crontab syntax.

The linked manpage does not specify /. It is non-standard and apparently not supported. Wikipedia says that

POSIX does not define a use for slashes; its rationale (commenting on a BSD extension) notes that the definition is based on System V format but does not exclude the possibility of extensions

So you just can't use / here.

You can use the equivalent

"0,10,20,30,40,50 * * * *"


问:
subprocess execution with different python version
I have a script which I execute within a python3 virtual environment and inside this script there is a subrocess.Popen command which starts an application that works only with python2. Is there a way to change the environment only for this process such that this subprocess finds python2 only?

So far I have tried the following which haven't work out.

```<code>os.environ["PATH"] = "/path/to/python2/bin:"+os.environ["PATH"]
</code>```

答:
Easiest solution I found:</p>

```<code>venv = os.environ.copy()
venv.update({"PATH": os.environ["PATH"].replace(venv['VIRTUAL_ENV'],
                     'other/python/version/path')}) # might have to tweak this a bit only

proc2 = subprocess.Popen(["cmd",
                         env=venv,
                         stdout=sys.stdout,
                         stderr=sys.stderr,
                             )
</code>```

Body:
I have a script which I execute within a python3 virtual environment and inside this script there is a subrocess.Popen command which starts an application that works only with python2. Is there a way to change the environment only for this process such that this subprocess finds python2 only?

So far I have tried the following which haven't work out.

os.environ["PATH"] = "/path/to/python2/bin:"+os.environ["PATH"]

Body:
Easiest solution I found:

venv = os.environ.copy()
venv.update({"PATH": os.environ["PATH"].replace(venv['VIRTUAL_ENV'],
                     'other/python/version/path')}) # might have to tweak this a bit only

proc2 = subprocess.Popen(["cmd",
                         env=venv,
                         stdout=sys.stdout,
                         stderr=sys.stderr,
                             )


问:
I am trying to make a prime number generator in Python3 and the input function is not working properly
There is probably a simple answer to this, but I'm new and have no idea what I'm doing as I am learning everything from google and reddit.

My code is:

```<code>def primefinder(z):
    primenumber_list=[]
    for y in range(2, z+1):
        if y not in primenumber_list:
            print(y)
            for x in range(y*y,z+1,y):
                primenumber_list.append(x)
q=input('Enter maximum:')
print(primefinder(q))
</code>```

The error is like this:

```<code>Traceback (most recent call last):
  File "primenumber.py", line 9, in <module>
    print(primefinder(q))
  File "primenumber.py", line 3, in primefinder
    for y in range(2, z+1):
TypeError: Can't convert 'int' object to str implicitly
</code>```

update: I learned how to properly format integers and strings etc. a very long time ago

答:
The input() function by default returns a string as output, you should explicitly covert it into a different type using int(),float() etc.

```<code>def primefinder(z):
    primenumber_list=[]
    for y in range(2, z+1):
        if y not in primenumber_list:
            print(y)
            for x in range(y*y,z+1,y):
                primenumber_list.append(x)
q=int(input('Enter maximum:'))
print(primefinder(q))
</code>```

Body:
There is probably a simple answer to this, but I'm new and have no idea what I'm doing as I am learning everything from google and reddit.

My code is:

def primefinder(z):
    primenumber_list=[]
    for y in range(2, z+1):
        if y not in primenumber_list:
            print(y)
            for x in range(y*y,z+1,y):
                primenumber_list.append(x)
q=input('Enter maximum:')
print(primefinder(q))

The error is like this:

Traceback (most recent call last):
  File "primenumber.py", line 9, in <module>
    print(primefinder(q))
  File "primenumber.py", line 3, in primefinder
    for y in range(2, z+1):
TypeError: Can't convert 'int' object to str implicitly

update: I learned how to properly format integers and strings etc. a very long time ago

Body:
The input() function by default returns a string as output, you should explicitly covert it into a different type using int(),float() etc.

def primefinder(z):
    primenumber_list=[]
    for y in range(2, z+1):
        if y not in primenumber_list:
            print(y)
            for x in range(y*y,z+1,y):
                primenumber_list.append(x)
q=int(input('Enter maximum:'))
print(primefinder(q))


问:
How to use the discord.js giveaway command
The code I have is:

```<code>C:\Users\xdswe\Desktop\Zero\src\commands\Testing\GIveaway.js:42
          if (m.reactions.cache.get("�").count <= 1) {
                                         ^
</code>```

That's the error message:

```<code>TypeError: Cannot read property 'count' of undefined
    at Timeout._onTimeout (C:\Users\xdswe\Desktop\Zero\src\commands\Testing\GIveaway.js:42:42)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7)
</code>```

How can I resolve the issue?

答:
Error clearly describes it, m.reactions.cache.get("�") is undefined, either way that isn't how you would get the amount of emojis, using <cache>.get("") just accesses the collection with the string given

Here's how:

const emoji = m.reactions.cache.find(f => f === "�");
const users = emoji && emoji.users;
const amount = users && users.size;
if(amount && amount <= 1) {
}
```

Body:
The code I have is:

C:\Users\xdswe\Desktop\Zero\src\commands\Testing\GIveaway.js:42
          if (m.reactions.cache.get("�").count <= 1) {
                                         ^

That's the error message:

TypeError: Cannot read property 'count' of undefined
    at Timeout._onTimeout (C:\Users\xdswe\Desktop\Zero\src\commands\Testing\GIveaway.js:42:42)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7)

How can I resolve the issue?


问:
How to limit product/variant quantity using Shopify Plus Script Editor app?
I'm looking for help to limit product/variant quantity using script editor app in Shopify Plus. The goal is to only allow one quantity to be able to add to cart per checkout for some specific variant ids in different products.

答:
There is no supported API for this, but you can update the line item object instance variables directly:</p>

```<code>line_item.instance_variable_set(:@quantity, max_quantity)
</code>```

Body:
There is no supported API for this, but you can update the line item object instance variables directly:

line_item.instance_variable_set(:@quantity, max_quantity)


问:
Type mismatch: number, date or string expected hibernate LocalDate
Task:

The field dates has type date in the database.

create table items
(
    id   serial primary key,
    dates date
);
```

<p><strong>Entity</strong>: // field "date" , type "LocalDate":</p>

<pre class="lang-java prettyprint-override"><code>@Entity
@Table(name = "items")
public class Item {
    private LocalDate date;

    @Column(name = "dates")
    public LocalDate getDate() {
        return date;
    }
}
</code>```

class UserStore:

class UserStore {
    private final SessionFactory factory = new Configuration()
            .configure().buildSessionFactory();

    public List<?> findByDate() {
        Session session = factory.openSession();
        session.beginTransaction();
        final String sql = "from Item i where i.date between ?1 and ?2";
        Query query = session.createQuery(sql, Item.class);
        query.setParameter(1, LocalDate.now());
        query.setParameter(2, LocalDate.now());
        List<?> result = query.getResultList();
        session.getTransaction().commit();
        session.close();
        return result;
    }
}
```

<p><strong>pom.xml</strong></p>

<pre class="lang-xml prettyprint-override"><code>        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.12.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-java8 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-java8</artifactId>
            <version>5.4.17.Final</version>
        </dependency>
</code>```

added:

```<code> <property name="dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>
</code>```

in the sql request: "from Item i where i.date between ?1 and ?2",
field i.date is highlighted in red, indicating a jpa error and requiring the use of the Date type:

If i use type Date instead LocalDate mistake escape. But I need LocalDate type.

How to fix it?

ps. The code compiles correctly.code implementation is not important. question one: How to remove the error without turning off the inspection.

答: Remove the hibernate-java8 artifact from your pom.xml. It is deprecated. The hibernate-core will be enough. I have tested your query and it works fine for me with LocalDate.

Body:
Task:

The field dates has type date in the database.

create table items
(
    id   serial primary key,
    dates date
);

Entity: // field "date" , type "LocalDate":

@Entity
@Table(name = "items")
public class Item {
    private LocalDate date;

    @Column(name = "dates")
    public LocalDate getDate() {
        return date;
    }
}

class UserStore:

class UserStore {
    private final SessionFactory factory = new Configuration()
            .configure().buildSessionFactory();

    public List<?> findByDate() {
        Session session = factory.openSession();
        session.beginTransaction();
        final String sql = "from Item i where i.date between ?1 and ?2";
        Query query = session.createQuery(sql, Item.class);
        query.setParameter(1, LocalDate.now());
        query.setParameter(2, LocalDate.now());
        List<?> result = query.getResultList();
        session.getTransaction().commit();
        session.close();
        return result;
    }
}

pom.xml

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.12.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-java8</artifactId>
            <version>5.4.17.Final</version>
        </dependency>

added:

 <property name="dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>

in the sql request: "from Item i where i.date between ?1 and ?2",
field i.date is highlighted in red, indicating a jpa error and requiring the use of the Date type:

If i use type Date instead LocalDate mistake escape. But I need LocalDate type.

How to fix it?

ps. The code compiles correctly.code implementation is not important. question one: How to remove the error without turning off the inspection.


问:
Entity Framework Core How To Solve ..Index 0-Error?
I am getting following error prompt from my Packet-Manager Console.

PM> Update-Database -Context SQLiteTestDbContext
Build started...
Build succeeded.
Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 3.1.4 initialized 'SQLiteTestDbContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite' with options: None
System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.
   at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue)
   at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2 parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms, Boolean firstKey)
   at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms, Boolean useOdbcRules)
   at System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value)
   at Microsoft.Data.Sqlite.SqliteConnectionStringBuilder..ctor(String connectionString)
   at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Format of the initialization string does not conform to specification starting at index 0.
```

<p>I don't know where the problem is. My connection string is stored in a <code>appsettings.json</code> in the project path.</p>

<p><code>appsettings.json</code>:</p>

```{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true",
    "SQLiteTestConnection": "Data Source=../DB-SQLite/Tests/TestDB.db"
  }
}
```

What is the problem there? The Add-Migration has worked for me but the next part with Update-Database won't work.

答:
Ok I found my problem.
My connection string was not correct. Also I tried with the ConfigurationManager to get the ConenctionString which was stored in an appsettings.json but this won't work (its only for .config I guess).

Body:
I am getting following error prompt from my Packet-Manager Console.

PM> Update-Database -Context SQLiteTestDbContext
Build started...
Build succeeded.
Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 3.1.4 initialized 'SQLiteTestDbContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite' with options: None
System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.
   at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue)
   at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2 parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms, Boolean firstKey)
   at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms, Boolean useOdbcRules)
   at System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value)
   at Microsoft.Data.Sqlite.SqliteConnectionStringBuilder..ctor(String connectionString)
   at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Format of the initialization string does not conform to specification starting at index 0.

I don't know where the problem is. My connection string is stored in a appsettings.json in the project path.

appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true",
    "SQLiteTestConnection": "Data Source=../DB-SQLite/Tests/TestDB.db"
  }
}

What is the problem there? The Add-Migration has worked for me but the next part with Update-Database won't work.


问:
Fixing error "Badly formed hexadecimal UUID string" after converting existing id to uuid in Django (Django 3.0)
I created a table with an initial IntegerField primary key and later changed the id to a UUIDField. Now this raises a "Badly formed hexadecimal UUID string", I guess because a number such as "1" isn't a valid UUID value. Does anyone know a concise way to fix this in code when updating the models.py file for the django app?

答:
Before everything, double check that you don't have any foreign key with Cascade uppon this model. Then, instead of changing the type of id = models.IntegerField() :

create a new field uuid = models.UUIDField(default=uuid.uuid4, primary=True) (default will set the field for existing rows)

make migrations

remove the id field

make migrations

rename the uuid field to id

make migrations

migrate

However, you should know that removing the id field, and / or naming the uuid is not mandatory, and it's often a good idea to keep both.


问:
Eloquent relationship not working in mail
I have an Order, Product and OrderProduct model. The Order has a belongsToMany relationship with Products as in

```<code>public function products(){
        return $this->belongsToMany('App\Product')->withPivot('group');
}
</code>```

So a user creates an order into the database:

```<code>$order = Order::create([
                    'order_id' => $payment->metadata->order_id,
                    'user_email' => $request ->email,
]);
</code>```

and we also save the products (note they have the same order_id as Order):

```<code>foreach (Cart::content() as $item){
                    OrderProduct::create([
                        'order_id' => $payment->metadata->order_id,
                        'product_id' =>$item->model->id,
                        'group' => $item->options->group,
                    ]);
                }
</code>```

So then I want to send an e-mail with the Order information and the Products information retrieved from the DB, this is in my webhook file and when the payment is paid, an email is sent:

```<code>      //Let's send an email.
      $order = Order::where('order_id', '=', $payment->metadata->order_id)->firstOrFail();
      Mail::send (new OrderPlaced ($order));
</code>```

The email shows all the order information like order_id and user_email in my view through the output {{$order->order_id}} and {{$order->user_email}} but I don't see the products when I try to loop through them with:

```<code>@foreach ($order->products as $product) {{$product->name}} @endforeach
</code>```

It just returns nothing, no error, nothing. A dd ($product) returns nothing. What am I overlooking here?

My thoughts:

 1. I am not using id as a primary key, so maybe I need to specify second and third arguments in the belongsToMany relationship?

 2. The $order variable defined prior to Mail, maybe I can't get the relationship through here?

答:
So I figured this out, maybe others will at some time face the same problem:
My foreign keys were not set right in the migration. So fixing the foreign keys and then doing a php artisan migrate refresh solved it.</p>

Body:
I have an Order, Product and OrderProduct model. The Order has a belongsToMany relationship with Products as in

public function products(){
        return $this->belongsToMany('App\Product')->withPivot('group');
}

So a user creates an order into the database:

$order = Order::create([
                    'order_id' => $payment->metadata->order_id,
                    'user_email' => $request ->email,
]);

and we also save the products (note they have the same order_id as Order):

foreach (Cart::content() as $item){
                    OrderProduct::create([
                        'order_id' => $payment->metadata->order_id,
                        'product_id' =>$item->model->id,
                        'group' => $item->options->group,
                    ]);
                }

So then I want to send an e-mail with the Order information and the Products information retrieved from the DB, this is in my webhook file and when the payment is paid, an email is sent:

      //Let's send an email.
      $order = Order::where('order_id', '=', $payment->metadata->order_id)->firstOrFail();
      Mail::send (new OrderPlaced ($order));

The email shows all the order information like order_id and user_email in my view through the output {{$order->order_id}} and {{$order->user_email}} but I don't see the products when I try to loop through them with:

@foreach ($order->products as $product) {{$product->name}} @endforeach

It just returns nothing, no error, nothing. A dd ($product) returns nothing. What am I overlooking here?

My thoughts:

 1. I am not using id as a primary key, so maybe I need to specify second and third arguments in the belongsToMany relationship?

 2. The $order variable defined prior to Mail, maybe I can't get the relationship through here?