问:
C++: Rotating a vector around a certain point
I am trying to rotate a vector around a certain point on the vector(in C++):

```<code>1 2 3
4 5 6
7 8 9
</code>```

rotated around the point (1,1) (which is the "5")  90 degrees would result in:

```<code>7 4 1
8 5 2
9 6 3
</code>```

Right now I am using:

```<code>x = (x * cos(90)) - (y * sin(90))
y = (y * cos(90)) + (x * sin(90))
</code>```

But I don't want it rotated around (0,0)

答: You will need to use a translation matrix to move rotate about a different point.</p>

OwnerDisplayName: Erik Ahlswede

Body:
I am trying to rotate a vector around a certain point on the vector(in C++):

1 2 3
4 5 6
7 8 9

rotated around the point (1,1) (which is the "5")  90 degrees would result in:

7 4 1
8 5 2
9 6 3

Right now I am using:

x = (x * cos(90)) - (y * sin(90))
y = (y * cos(90)) + (x * sin(90))

But I don't want it rotated around (0,0)

OwnerDisplayName: Ben S


来源: stackexchange

问:
g++ warning when using optional 'struct' keyword
If I write this program:

```<code>#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new struct foo::bar;
    delete a;
    return 0;
}
</code>```

and compile it with:

```<code>g++ main.cxx -Wall -Wextra
</code>```

It gives me this warning:

```<code>main.cxx: In function ‘int main()’:
main.cxx:10:39: warning: declaration ‘struct foo::bar’ does not declare anything [enabled by default]
</code>```

However, if I take out the struct keyword after the new keyword:

```<code>#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new foo::bar;
    delete a;
    return 0;
}
</code>```

and compile it the same way, g++ outputs no warnings.  Why does g++ output that warning if I use the struct keyword?

答:
Examining the error:

main.cxx:10:39: warning: declaration ‘struct foo::bar’ does not declare anything [enabled by default]

g++ thinks you're declaring a new struct with the name foo::bar instead of allocating memory of type struct foo::bar. My guess would be because g++ assumes any usage of struct that doesn't declare an lvalue is for the purpose of declaring a type.

ContentLicense: CC BY-SA 3.0

Body:
If I write this program:

#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new struct foo::bar;
    delete a;
    return 0;
}

and compile it with:

g++ main.cxx -Wall -Wextra

It gives me this warning:

main.cxx: In function ‘int main()’:
main.cxx:10:39: warning: declaration ‘struct foo::bar’ does not declare anything [enabled by default]

However, if I take out the struct keyword after the new keyword:

#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new foo::bar;
    delete a;
    return 0;
}

and compile it the same way, g++ outputs no warnings.  Why does g++ output that warning if I use the struct keyword?


问:
docker-compose doesnt launch more than approx. 50 service containers of 130 defined in file
I extended my service which should now launch 130 docker containers instead of 40 (before).
however, after about 50 containers, docker-compose just stops launching more but does not show an error message. (both 2.4 and 3.7 version)

I found a work around by splitting the docker-compose files with 50 each. But this is not very elegant.

Is there a setting or a way to solve this and launch 130 containers from just 1 docker-compose file?

Here is the compose file with 2/140 sample services.

```<code>docker-compose version 1.23.1, build b02f1306
</code>```

docker-compose.yml:

```<code>version: "2.4"

networks:
  proxy-tier:
    external:
      name: nginx-proxy

volumes:
  data:
    driver: local
    driver_opts:
      type: 'none'
      o: 'bind'
      device: '/home/geoFrontend2'
  logs:
    driver: local
    driver_opts:
      type: 'none'
      o: 'bind'
      device: '/home/logs_geoFrontend'
  ancestors:
    driver: local
    driver_opts:
      type: 'none'
      o: 'bind'
      device: '/home/ancestors'

services:
  myapp_4:
    extends:
      file: utils.yml
      service: shiny-server
    ports:
      - "3004:3838"
    environment:
      - "VIRTUAL_PORT=3004"
      - "VIRTUAL_HOST=myapp4.mydomain.com"
  myapp_5:
    extends:
      file: utils.yml
      service: shiny-server
    ports:
      - "3005:3838"
    environment:
      - "VIRTUAL_PORT=3005"
      - "VIRTUAL_HOST=myapp5.mydomain.com"
</code>```

utils.yml

```<code>version: "2.4"

networks:
  proxy-tier:
    external:
      name: nginx-proxy

services:
  shiny-server:
    image: shiny:latest
    environment:
      - "VIRTUAL_NETWORK=nginx-proxy"
    volumes:
      - data:/srv/shiny-server/
      - logs:/var/log/shiny-server/
      - ancestors:/srv/shiny-server/www/ancestors/
    networks:
      - proxy-tier
    restart: always
    mem_limit: 500m
    mem_reservation: 100m
</code>```

答:
The solution was</p>

```<code>export COMPOSE_HTTP_TIMEOUT=300000
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I extended my service which should now launch 130 docker containers instead of 40 (before).
however, after about 50 containers, docker-compose just stops launching more but does not show an error message. (both 2.4 and 3.7 version)

I found a work around by splitting the docker-compose files with 50 each. But this is not very elegant.

Is there a setting or a way to solve this and launch 130 containers from just 1 docker-compose file?

Here is the compose file with 2/140 sample services.

docker-compose version 1.23.1, build b02f1306

docker-compose.yml:

version: "2.4"

networks:
  proxy-tier:
    external:
      name: nginx-proxy

volumes:
  data:
    driver: local
    driver_opts:
      type: 'none'
      o: 'bind'
      device: '/home/geoFrontend2'
  logs:
    driver: local
    driver_opts:
      type: 'none'
      o: 'bind'
      device: '/home/logs_geoFrontend'
  ancestors:
    driver: local
    driver_opts:
      type: 'none'
      o: 'bind'
      device: '/home/ancestors'

services:
  myapp_4:
    extends:
      file: utils.yml
      service: shiny-server
    ports:
      - "3004:3838"
    environment:
      - "VIRTUAL_PORT=3004"
      - "VIRTUAL_HOST=myapp4.mydomain.com"
  myapp_5:
    extends:
      file: utils.yml
      service: shiny-server
    ports:
      - "3005:3838"
    environment:
      - "VIRTUAL_PORT=3005"
      - "VIRTUAL_HOST=myapp5.mydomain.com"

utils.yml

version: "2.4"

networks:
  proxy-tier:
    external:
      name: nginx-proxy

services:
  shiny-server:
    image: shiny:latest
    environment:
      - "VIRTUAL_NETWORK=nginx-proxy"
    volumes:
      - data:/srv/shiny-server/
      - logs:/var/log/shiny-server/
      - ancestors:/srv/shiny-server/www/ancestors/
    networks:
      - proxy-tier
    restart: always
    mem_limit: 500m
    mem_reservation: 100m

Body:
The solution was

export COMPOSE_HTTP_TIMEOUT=300000


问:
How can I configure Git or Gitlab so that only a branch's owner is allowed to push into it?
Definitions:

Who is the owner of a branch? The owner of a branch is the user who has created that branch.

Situation:

User A has created a branch from master called A-branch. Therefore, user A is the owner of A-branch.

User B, who is the colleague of user A, has created another branch from master called B-branch. Therefore, user B is the owner of B-branch.

Desired restriction:

User A must be the only user, who can push  changes into A-branch. (Because he is the owner of this branch)

User B must be the only user, who can push  changes into B-branch. (Because she is the owner of this branch)

Questions:

Can user A push to B-branch? No

Can user A pull
B-branch? Yes

Can user A merge B-branch into his own branch? yes

Can user A and B merge their branches into master ? Yes

Should this recruction apply automatically on branch creation? Yes

How can I achieve such behavior described above in Gitlab?

答:
As torek mentioned, Git doesn't record ownership of branches.  I'm not aware of any hosting platform for Git that allows branch restrictions on a per-user basis, especially automatically.

The typical assumption when one is sharing a repository with others is that those users are trusted to contribute to most branches in that repository, possibly with some particular restricted branches.

What you probably want to do in this case is allow the creation of forks for this repository and then have A and B push to their own forks.  They'll be able to fetch from each other's branches and open pull requests to merge their changes, but won't be able to push to each other's forks.


问:
Have a reloadData for a UITableView animate when changing
I have a UITableView that has two modes.  When we switch between the modes I have a different number of sections and cells per section.  Ideally, it would do some cool animation when the table grows or shrinks.

Here is the code I tried, but it doesn't do anything:

```<code>CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.5];

[self.tableView reloadData];
[UIView commitAnimations];
</code>```

Any thoughts on how I could do this?

答:
Native UITableView animations in Swift

Insert and delete rows all at once with tableView.performBatchUpdates so they occur simultaneously. Building on the answer from @iKenndac use methods such as:

tableView.insertSections

tableView.insertRows

tableView.deleteSections

tableView.deleteRows

Ex:

```<code> tableView.performBatchUpdates({
   tableView.insertSections([0], with: .top)
 })
</code>```

This inserts a section at the zero position with an animation that loads from the top. This will re-run the cellForRowAt method and check for a new cell at that position. You could reload the entire table view this way with specific animations.

Re: the OP question, a conditional flag would have been needed to show the cells for the alternate table view state.

OwnerDisplayName: Chris Butler

LastEditorDisplayName: Chris Hanson

Body:
I have a UITableView that has two modes.  When we switch between the modes I have a different number of sections and cells per section.  Ideally, it would do some cool animation when the table grows or shrinks.

Here is the code I tried, but it doesn't do anything:

CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.5];

[self.tableView reloadData];
[UIView commitAnimations];

Any thoughts on how I could do this?

Body:
Native UITableView animations in Swift

Insert and delete rows all at once with tableView.performBatchUpdates so they occur simultaneously. Building on the answer from @iKenndac use methods such as:

tableView.insertSections

tableView.insertRows

tableView.deleteSections

tableView.deleteRows

Ex:

 tableView.performBatchUpdates({
   tableView.insertSections([0], with: .top)
 })

This inserts a section at the zero position with an animation that loads from the top. This will re-run the cellForRowAt method and check for a new cell at that position. You could reload the entire table view this way with specific animations.

Re: the OP question, a conditional flag would have been needed to show the cells for the alternate table view state.


问:
Position ''top/bottom'' takes the image out of the div
This might be a bit more advance, but I cannot get the answer anywhere, and I am starting getting mad.

I manage to position my clouds as I want them in percentages values, so they are in proportion of the viewport/device screen. My div has relative position so the images inside (they all have absolute position) can move inside relative to the wrapping container (the div)

However, if I change or add top or bottom position percentages values to my image, somehow, the image moves out of the parent div (with position: relative), so, if I change the padding of my wrapping div (so it can cover more area of the screen), the images are not affected, they do not move along the alterations of the div's padding, as if they were not nested inside my div.

Does anyone know what exactly it is going on?

```<code><div class="top-container">
    <img class="top-cloud">
    <h1>I'm Marcos</h1>
    <h2>A Software Developer</h2>
    <img class="bot-cloud">
    <img class="mountain">
</div>
</code>```

This is my CSS

```<code>body {
    margin: 0;
    text-align: center;
}

h1 {
    margin-top: 0;
}

.top-container {
    background-color: #79bac1;
    position: relative;
    padding: 10% 0 0 0;
}

.top-cloud {
    position: absolute;
    width: 8%;
    left: 15%;
}

.mountain {
    width: 35%;
    display: block;
    margin: auto;
}

.bot-cloud {
    position: absolute;
    width: 8%;
    right: 15%;
    top: 10% /*If I delete this value, the image (.bot-cloud) moves in and it gets affected by the ".top-container" padding. But if I leave it, and modify the padding in the ".top-container", it gets moved out of the ".top-container" as if it's not wrapped by it.*/
}
</code>```

答:
You image has position: absolute; , which takes it out of the document flow, i.e. it will not occupy any space which wouldn't be there if you just erased it - it only covers space of other elements.

Its only reference in matter of position is the next highest parent element which has position: relative. If top is 0, its top will be directly at the top border of the parent. A padding of the parent will not change that at all (see snippet below).

If you use a negative top value, it will (vertically) move outside  the parent (= up), for example top: -10% will place it 10% (of the parent's height) above ( = outside) the top border of the parent. A positive value, like top: 10% will place it 10% (of the parent's height) below ( = inside) the top border of the parent. The reference for top is always the top border of the parent element. Same princicple for left, right and bottom values - their  reference will be the left, right and bottom border of the relative parent.

body {
  margin: 0;
  text-align: center;
}

h1 {
  margin-top: 0;
}

.top-container {
  background-color: #79bac1;
  position: relative;
  padding: 10% 0 0 0;
}

.top-cloud {
  position: absolute;
  width: 8%;
  left: 15%;
}

.mountain {
  width: 35%;
  display: block;
  margin: auto;
}

.bot-cloud {
  position: absolute;
  width: 8%;
  right: 15%;
  top: 0%;/*If I delete this value, the image (.bot-cloud) moves in and it gets affected by the ".top-container" padding. But if I leave it, and modify the padding in the ".top-container", it gets moved out of the ".top-container" as if it's not wrapped by it.*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="top-container">
  <img class="top-cloud">
  <h1>I'm Marcos</h1>
  <h2>A Software Developer</h2>
  <img src="https://placehold.it/200x150/d66" class="bot-cloud" >
  <img src="https://placehold.it/150x100/6a9" class="mountain">
</div></code>```

Body:
This might be a bit more advance, but I cannot get the answer anywhere, and I am starting getting mad.

I manage to position my clouds as I want them in percentages values, so they are in proportion of the viewport/device screen. My div has relative position so the images inside (they all have absolute position) can move inside relative to the wrapping container (the div)

However, if I change or add top or bottom position percentages values to my image, somehow, the image moves out of the parent div (with position: relative), so, if I change the padding of my wrapping div (so it can cover more area of the screen), the images are not affected, they do not move along the alterations of the div's padding, as if they were not nested inside my div.

Does anyone know what exactly it is going on?

I'm Marcos

A Software Developer

This is my CSS

body {
    margin: 0;
    text-align: center;
}

h1 {
    margin-top: 0;
}

.top-container {
    background-color: #79bac1;
    position: relative;
    padding: 10% 0 0 0;
}

.top-cloud {
    position: absolute;
    width: 8%;
    left: 15%;
}

.mountain {
    width: 35%;
    display: block;
    margin: auto;
}

.bot-cloud {
    position: absolute;
    width: 8%;
    right: 15%;
    top: 10% /*If I delete this value, the image (.bot-cloud) moves in and it gets affected by the ".top-container" padding. But if I leave it, and modify the padding in the ".top-container", it gets moved out of the ".top-container" as if it's not wrapped by it.*/
}

Body:
You image has position: absolute; , which takes it out of the document flow, i.e. it will not occupy any space which wouldn't be there if you just erased it - it only covers space of other elements.

Its only reference in matter of position is the next highest parent element which has position: relative. If top is 0, its top will be directly at the top border of the parent. A padding of the parent will not change that at all (see snippet below).

If you use a negative top value, it will (vertically) move outside  the parent (= up), for example top: -10% will place it 10% (of the parent's height) above ( = outside) the top border of the parent. A positive value, like top: 10% will place it 10% (of the parent's height) below ( = inside) the top border of the parent. The reference for top is always the top border of the parent element. Same princicple for left, right and bottom values - their  reference will be the left, right and bottom border of the relative parent.

body {
  margin: 0;
  text-align: center;
}

h1 {
  margin-top: 0;
}

.top-container {
  background-color: #79bac1;
  position: relative;
  padding: 10% 0 0 0;
}

.top-cloud {
  position: absolute;
  width: 8%;
  left: 15%;
}

.mountain {
  width: 35%;
  display: block;
  margin: auto;
}

.bot-cloud {
  position: absolute;
  width: 8%;
  right: 15%;
  top: 0%;/*If I delete this value, the image (.bot-cloud) moves in and it gets affected by the ".top-container" padding. But if I leave it, and modify the padding in the ".top-container", it gets moved out of the ".top-container" as if it's not wrapped by it.*/
}

<div class="top-container">
  <img class="top-cloud">
  <h1>I'm Marcos</h1>
  <h2>A Software Developer</h2>
  <img src="https://placehold.it/200x150/d66" class="bot-cloud" >
  <img src="https://placehold.it/150x100/6a9" class="mountain">
</div>


问:
How can I make the website sort by price from greatest to smallest
I'm working on a small grocery store website using javascript and I am having trouble sorting the items on the products category from least expensive down to most expensive.

The customer selects the "client" category and chooses their allergen specification, once the specification is selected they have to select the products tab where they will see the list of products, as shown in the screenshot.

As you can see, the products pricing is all mixed up, how can I make it so that the products go from cheapest product to the most expensive product at the bottom.

Code is below:

//groceries.js
// Array of products, each product is an object with different fieldset
// A set of ingredients should be added to products

var products = [
 {
  name: "brocoli $1.99",
  vegetarian: true,
  glutenFree: true,
  price: 1.99,
  organic:true
 },
 {
  name: "bread $2.35",
  vegetarian: true,
  glutenFree: false,
  price: 2.35,
  organic:false

 },
 {
  name: "salmon $10.00",
  vegetarian: false,
  glutenFree: true,
  price: 10.00,
  organic:true

 },

 {
  name: "chicken $8.99",
  vegetarian: false,
  glutenFree: true,
  price: 8.99,
  organic:true

 },

 {
  name: "macaroni $2.99",
  vegetarian: false,
  glutenFree: false,
  price: 2.99,
  organic:true

 },

 {
  name: "cake mix $3.99",
  vegetarian: false,
  glutenFree: false,
  price: 3.99,
  organic:true

 },

 {
  name: "Jam $4.99",
  vegetarian: true,
  glutenFree: true,
  price: 4.99,
  organic:true

 },

 {
  name: "banana $1.99",
  vegetarian: true,
  glutenFree: true,
  price: 1.99,
  organic:true

 },

 {
  name: "eggs $1.50",
  vegetarian: true,
  glutenFree: true,
  price: 1.50,
  organic:true

 },

 {
  name: "apples $2.49",
  vegetarian: true,
  glutenFree: true,
  price: 2.49,
  organic:true
 }

];

// given restrictions provided, make a reduced list of products
// prices should be included in this list, as well as a sort based on price

function restrictListProducts(prods, restriction) {
 let product_names = [];
 for (let i=0; i<prods.length; i+=1) {

  if ((restriction == "Vegetarian") && (prods[i].vegetarian == true)){
   product_names.push(prods[i].name);
  }
  else if ((restriction == "Gluten Free") && (prods[i].glutenFree == true)){
   product_names.push(prods[i].name);
  }

  else if((restriction == "GlutenFreeandVegetarian") && (prods[i].glutenFree == true) && (prods[i].vegetarian == true) ){
   product_names.push(prods[i].name);
  }

  else if((restriction == "Organic") && (prods[i].organic == true) ){
   product_names.push(prods[i].name);
  }

  else if((restriction == "GlutenFreeandOrganic") && (prods[i].organic == true) && (prods[i].glutenFree == true) ){
   product_names.push(prods[i].name);
  }

  else if((restriction == "GlutenFreeandVegetarian") && (prods[i].vegetarian == true) && (prods[i].glutenFree == true) ){
   product_names.push(prods[i].name);
  }

  else if((restriction == "GlutenFreeandVegetarianandOrganic") && (prods[i].organic == true) && (prods[i].vegetarian == true) && (prods[i].glutenFree == true) ){
   product_names.push(prods[i].name);
  }

  else if (restriction == "None"){
   product_names.push(prods[i].name);
  }

 }
 return product_names;
}

// Calculate the total price of items, with received parameter being a list of products
function getTotalPrice(chosenProducts) {
 totalPrice = 0;
 for (let i=0; i<products.length; i+=1) {
  if (chosenProducts.indexOf(products[i].name) > -1){
   totalPrice += products[i].price;
  }
 }
 return totalPrice;
}

// main.js

function openInfo(evt, tabName) {

 // Get all elements with class="tabcontent" and hide them
 tabcontent = document.getElementsByClassName("tabcontent");
 for (i = 0; i < tabcontent.length; i++) {
  tabcontent[i].style.display = "none";
 }

 // Get all elements with class="tablinks" and remove the class "active"
 tablinks = document.getElementsByClassName("tablinks");
 for (i = 0; i < tablinks.length; i++) {
  tablinks[i].className = tablinks[i].className.replace(" active", "");
 }

 // Show the current tab, and add an "active" class to the button that opened the tab
 document.getElementById(tabName).style.display = "block";
 evt.currentTarget.className += " active";

}

// generate a checkbox list from a list of products
// it makes each product name as the label for the checkbos

function populateListProductChoices(slct1, slct2) {
    var s1 = document.getElementById(slct1);
    var s2 = document.getElementById(slct2);

 // s2 represents the
 in the Products tab, which shows the product list, so we first set it empty
    s2.innerHTML = "";

 // obtain a reduced list of products based on restrictions
    var optionArray = restrictListProducts(products, s1.value);

 // for each item in the array, create a checkbox element, each containing information such as:
 // <input type="checkbox" name="product" value="Bread">
 // Bread/label>

 for (i = 0; i < optionArray.length; i++) {

  var productName = optionArray[i];
  // create the checkbox and add in HTML DOM
  var checkbox = document.createElement("input");
  checkbox.type = "checkbox";
  checkbox.name = "product";
  checkbox.value = productName;
  s2.appendChild(checkbox);

  // create a label for the checkbox, and also add in HTML DOM
  var label = document.createElement('label')
  label.htmlFor = productName;
  label.appendChild(document.createTextNode(productName));
  s2.appendChild(label);

  // create a breakline node and add in HTML DOM
  s2.appendChild(document.createElement("br"));
 }
}

// This function is called when the "Add selected items to cart" button in clicked
// The purpose is to build the HTML to be displayed (a Paragraph)
// We build a paragraph to contain the list of selected items, and the total price

function selectedItems(){

 var ele = document.getElementsByName("product");
 var chosenProducts = [];

 var c = document.getElementById('displayCart');
 c.innerHTML = "";

 // build list of selected item
 var para = document.createElement("P");
 para.innerHTML = "You selected : ";
 para.appendChild(document.createElement("br"));
 for (i = 0; i < ele.length; i++) {
  if (ele[i].checked) {
   para.appendChild(document.createTextNode(ele[i].value));
   para.appendChild(document.createElement("br"));
   chosenProducts.push(ele[i].value);
  }
 }

 // add paragraph and total price
 c.appendChild(para);
 c.appendChild(document.createTextNode("Total Price is " + getTotalPrice(chosenProducts)));

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* This style sheet is taken from  https://www.w3schools.com/howto/howto_js_tabs.asp> */

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons that are used to open the tab content */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}</code>```

<!DOCTYPE html>

 <! This style sheet is taken from  https://www.w3schools.com/howto/howto_js_tabs.asp>
 <link href="styles/style.css" rel="stylesheet" type="text/css">

Super Groceries

  <button class="tablinks" onclick="openInfo(event, 'Client')">Client</button>
  <button class="tablinks" onclick="openInfo(event, 'Products')">Products</button>
  <button class="tablinks" onclick="openInfo(event, 'Cart')">Cart</button>

Client Information

Tell us a bit about you.

 Choose a Category:
 <select id="dietSelect" name="dietSelect" onchange="populateListProductChoices(this.id, 'displayProduct')">
 <option value=""></option>
 <option value="Vegetarian">Vegetarian</option>
    <option value="Gluten Free">GlutenFree</option>
    <option value="Organic"> Organic</option>
    <option value="GlutenFreeandVegetarian"> GlutenFreeandVegetarian</option>
    <option value="GlutenFreeandOrganic"> GlutenFreeandOrganic</option>
    <option value="VegetarianandOrganic"> VegetarianandOrganic</option>
    <option value="GlutenFreeandVegetarianandOrganic"> GlutenFreeandVegetarianandOrganic</option>

    <option value="None">None</option>
  </select>

Your targeted products

We preselected products based on your restrictions.

  Choose items to buy:

  <button id="addCart" type="button" class="block" onclick="selectedItems()">
  Add selected items to cart.
 </button>

Cart

Here is your cart.

```

Thank you

答:
I made a new array of product prices (you can also solve without creating a new array , but I solved it so that the solution would be more understandable) and sorted it from the low to the high price:

```<code>var priceProducts = new Array(products.length);
for (let i = 0; i < priceProducts.length; i++) {
  priceProducts[i] = products[i].price;

}
priceProducts.sort(((x, y) => x - y));

for (let i = 0; i < priceProducts.length; i++) {
    console.log(priceProducts[i]);
}
</code>```

Output :

```<code>1.5
1.99
2.35
2.49
2.99
3.99
4.99
8.99
10
</code>```

Body:
I'm working on a small grocery store website using javascript and I am having trouble sorting the items on the products category from least expensive down to most expensive.

The customer selects the "client" category and chooses their allergen specification, once the specification is selected they have to select the products tab where they will see the list of products, as shown in the screenshot.

As you can see, the products pricing is all mixed up, how can I make it so that the products go from cheapest product to the most expensive product at the bottom.

Code is below:

//groceries.js
// Array of products, each product is an object with different fieldset
// A set of ingredients should be added to products

var products = [
 {
  name: "brocoli $1.99",
  vegetarian: true,
  glutenFree: true,
  price: 1.99,
  organic:true
 },
 {
  name: "bread $2.35",
  vegetarian: true,
  glutenFree: false,
  price: 2.35,
  organic:false

 },
 {
  name: "salmon $10.00",
  vegetarian: false,
  glutenFree: true,
  price: 10.00,
  organic:true

 },

 {
  name: "chicken $8.99",
  vegetarian: false,
  glutenFree: true,
  price: 8.99,
  organic:true

 },

 {
  name: "macaroni $2.99",
  vegetarian: false,
  glutenFree: false,
  price: 2.99,
  organic:true

 },

 {
  name: "cake mix $3.99",
  vegetarian: false,
  glutenFree: false,
  price: 3.99,
  organic:true

 },

 {
  name: "Jam $4.99",
  vegetarian: true,
  glutenFree: true,
  price: 4.99,
  organic:true

 },

 {
  name: "banana $1.99",
  vegetarian: true,
  glutenFree: true,
  price: 1.99,
  organic:true

 },

 {
  name: "eggs $1.50",
  vegetarian: true,
  glutenFree: true,
  price: 1.50,
  organic:true

 },

 {
  name: "apples $2.49",
  vegetarian: true,
  glutenFree: true,
  price: 2.49,
  organic:true
 }

];

// given restrictions provided, make a reduced list of products
// prices should be included in this list, as well as a sort based on price

function restrictListProducts(prods, restriction) {
 let product_names = [];
 for (let i=0; i<prods.length; i+=1) {

  if ((restriction == "Vegetarian") && (prods[i].vegetarian == true)){
   product_names.push(prods[i].name);
  }
  else if ((restriction == "Gluten Free") && (prods[i].glutenFree == true)){
   product_names.push(prods[i].name);
  }

  else if((restriction == "GlutenFreeandVegetarian") && (prods[i].glutenFree == true) && (prods[i].vegetarian == true) ){
   product_names.push(prods[i].name);
  }

  else if((restriction == "Organic") && (prods[i].organic == true) ){
   product_names.push(prods[i].name);
  }

  else if((restriction == "GlutenFreeandOrganic") && (prods[i].organic == true) && (prods[i].glutenFree == true) ){
   product_names.push(prods[i].name);
  }

  else if((restriction == "GlutenFreeandVegetarian") && (prods[i].vegetarian == true) && (prods[i].glutenFree == true) ){
   product_names.push(prods[i].name);
  }

  else if((restriction == "GlutenFreeandVegetarianandOrganic") && (prods[i].organic == true) && (prods[i].vegetarian == true) && (prods[i].glutenFree == true) ){
   product_names.push(prods[i].name);
  }

  else if (restriction == "None"){
   product_names.push(prods[i].name);
  }

 }
 return product_names;
}

// Calculate the total price of items, with received parameter being a list of products
function getTotalPrice(chosenProducts) {
 totalPrice = 0;
 for (let i=0; i<products.length; i+=1) {
  if (chosenProducts.indexOf(products[i].name) > -1){
   totalPrice += products[i].price;
  }
 }
 return totalPrice;
}

// main.js

function openInfo(evt, tabName) {

 // Get all elements with class="tabcontent" and hide them
 tabcontent = document.getElementsByClassName("tabcontent");
 for (i = 0; i < tabcontent.length; i++) {
  tabcontent[i].style.display = "none";
 }

 // Get all elements with class="tablinks" and remove the class "active"
 tablinks = document.getElementsByClassName("tablinks");
 for (i = 0; i < tablinks.length; i++) {
  tablinks[i].className = tablinks[i].className.replace(" active", "");
 }

 // Show the current tab, and add an "active" class to the button that opened the tab
 document.getElementById(tabName).style.display = "block";
 evt.currentTarget.className += " active";

}

// generate a checkbox list from a list of products
// it makes each product name as the label for the checkbos

function populateListProductChoices(slct1, slct2) {
    var s1 = document.getElementById(slct1);
    var s2 = document.getElementById(slct2);

 // s2 represents the
 in the Products tab, which shows the product list, so we first set it empty
    s2.innerHTML = "";

 // obtain a reduced list of products based on restrictions
    var optionArray = restrictListProducts(products, s1.value);

 // for each item in the array, create a checkbox element, each containing information such as:
 // <input type="checkbox" name="product" value="Bread">
 // Bread/label>

 for (i = 0; i < optionArray.length; i++) {

  var productName = optionArray[i];
  // create the checkbox and add in HTML DOM
  var checkbox = document.createElement("input");
  checkbox.type = "checkbox";
  checkbox.name = "product";
  checkbox.value = productName;
  s2.appendChild(checkbox);

  // create a label for the checkbox, and also add in HTML DOM
  var label = document.createElement('label')
  label.htmlFor = productName;
  label.appendChild(document.createTextNode(productName));
  s2.appendChild(label);

  // create a breakline node and add in HTML DOM
  s2.appendChild(document.createElement("br"));
 }
}

// This function is called when the "Add selected items to cart" button in clicked
// The purpose is to build the HTML to be displayed (a Paragraph)
// We build a paragraph to contain the list of selected items, and the total price

function selectedItems(){

 var ele = document.getElementsByName("product");
 var chosenProducts = [];

 var c = document.getElementById('displayCart');
 c.innerHTML = "";

 // build list of selected item
 var para = document.createElement("P");
 para.innerHTML = "You selected : ";
 para.appendChild(document.createElement("br"));
 for (i = 0; i < ele.length; i++) {
  if (ele[i].checked) {
   para.appendChild(document.createTextNode(ele[i].value));
   para.appendChild(document.createElement("br"));
   chosenProducts.push(ele[i].value);
  }
 }

 // add paragraph and total price
 c.appendChild(para);
 c.appendChild(document.createTextNode("Total Price is " + getTotalPrice(chosenProducts)));

}

/* This style sheet is taken from  https://www.w3schools.com/howto/howto_js_tabs.asp> */

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons that are used to open the tab content */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}

<!DOCTYPE html>

 <! This style sheet is taken from  https://www.w3schools.com/howto/howto_js_tabs.asp>
 <link href="styles/style.css" rel="stylesheet" type="text/css">

Super Groceries

  <button class="tablinks" onclick="openInfo(event, 'Client')">Client</button>
  <button class="tablinks" onclick="openInfo(event, 'Products')">Products</button>
  <button class="tablinks" onclick="openInfo(event, 'Cart')">Cart</button>

Client Information

Tell us a bit about you.

 Choose a Category:
 <select id="dietSelect" name="dietSelect" onchange="populateListProductChoices(this.id, 'displayProduct')">
 <option value=""></option>
 <option value="Vegetarian">Vegetarian</option>
    <option value="Gluten Free">GlutenFree</option>
    <option value="Organic"> Organic</option>
    <option value="GlutenFreeandVegetarian"> GlutenFreeandVegetarian</option>
    <option value="GlutenFreeandOrganic"> GlutenFreeandOrganic</option>
    <option value="VegetarianandOrganic"> VegetarianandOrganic</option>
    <option value="GlutenFreeandVegetarianandOrganic"> GlutenFreeandVegetarianandOrganic</option>

    <option value="None">None</option>
  </select>

Your targeted products

We preselected products based on your restrictions.

  Choose items to buy:

  <button id="addCart" type="button" class="block" onclick="selectedItems()">
  Add selected items to cart.
 </button>

Cart

Here is your cart.

Thank you

Body:
I made a new array of product prices (you can also solve without creating a new array , but I solved it so that the solution would be more understandable) and sorted it from the low to the high price:

var priceProducts = new Array(products.length);
for (let i = 0; i < priceProducts.length; i++) {
  priceProducts[i] = products[i].price;

}
priceProducts.sort(((x, y) => x - y));

for (let i = 0; i < priceProducts.length; i++) {
    console.log(priceProducts[i]);
}

Output :

1.5
1.99
2.35
2.49
2.99
3.99
4.99
8.99
10


答:
You can use sort() method to solve that.
For example:

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);```

For more info use this link

Title: How can I make the website sort by price from greatest to smallest

Body:
You can use sort() method to solve that.
For example:

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);

For more info use this link


问:
Grouping object entries into object arrays
How can I create arrays to group members depending on their tag?

Tags can be anything, these are just examples.

Example Input

[
  { tag: 'Red', member: 'Red-Steve' },
  { tag: 'Red', member: 'Red-Adam' },
  { tag: 'Blue', member: 'Blue-John' },
  { tag: 'Blue', member: 'Blue-James' },
  { tag: 'Blue', member: 'Blue-Igor' }
]
```

<p>Example Output</p>

<pre class="lang-js prettyprint-override"><code>{
  Red: ['Red-Steve', 'Red-Adam']
  Blue: ['Blue-John', 'Blue-James', 'Blue-Igor']
}
</code>```

Edit: I just made a test case on jsperf to compare the efficiency of the different answers and also the answer from the suggested duplicate question
https://jsperf.com/group-objects-reduce-vs-for-loop

The answer by @Majed Badawi was the most efficient

答:
The following code will do what you ask. It uses the object[variableKey] syntax to get what you are looking for.</p>

```<code>const members=[
  { tag: 'Red', member: 'Red-Steve' },
  { tag: 'Red', member: 'Red-Adam' },
  { tag: 'Blue', member: 'Blue-John' },
  { tag: 'Blue', member: 'Blue-James' },
  { tag: 'Blue', member: 'Blue-Igor' }
]

//this will be the output object
const newObj={};

for(memberObj of members){
    const newKey = memberObj.tag;

    //if the key already existed, just add the new item to the existing array
    if(newObj[newKey]){newObj[newKey].push(memberObj.member);}
    //if the key didn't exist, create an array value for it with the new object
    else{newObj[newKey]=[memberObj.member];}
}

console.log(newObj);
</code>```

Body:
How can I create arrays to group members depending on their tag?

Tags can be anything, these are just examples.

Example Input

[
  { tag: 'Red', member: 'Red-Steve' },
  { tag: 'Red', member: 'Red-Adam' },
  { tag: 'Blue', member: 'Blue-John' },
  { tag: 'Blue', member: 'Blue-James' },
  { tag: 'Blue', member: 'Blue-Igor' }
]

Example Output

{
  Red: ['Red-Steve', 'Red-Adam']
  Blue: ['Blue-John', 'Blue-James', 'Blue-Igor']
}

Edit: I just made a test case on jsperf to compare the efficiency of the different answers and also the answer from the suggested duplicate question
https://jsperf.com/group-objects-reduce-vs-for-loop

The answer by @Majed Badawi was the most efficient

Body:
The following code will do what you ask. It uses the object[variableKey] syntax to get what you are looking for.

const members=[
  { tag: 'Red', member: 'Red-Steve' },
  { tag: 'Red', member: 'Red-Adam' },
  { tag: 'Blue', member: 'Blue-John' },
  { tag: 'Blue', member: 'Blue-James' },
  { tag: 'Blue', member: 'Blue-Igor' }
]

//this will be the output object
const newObj={};

for(memberObj of members){
    const newKey = memberObj.tag;

    //if the key already existed, just add the new item to the existing array
    if(newObj[newKey]){newObj[newKey].push(memberObj.member);}
    //if the key didn't exist, create an array value for it with the new object
    else{newObj[newKey]=[memberObj.member];}
}

console.log(newObj);


问:
Node.js parse terminal input
So I have a ssh2 server, and I want to be able to parse the commands that are entered, I am currently using the readline module, but even it outputs special characters when backspace is used, I don't want every keypress, I just want the entire visible line when Enter is pressed, if I type in testing and press enter, as expected, my log outputs Line: "testing" 7 long, but if I type testing with backspaces then press backspace 5 times, and type oops, mistake, it outputs Line: "testing with backspaces⌂⌂⌂⌂⌂oops, mistake" 41 long.

How do I "parse" these codes to get Line: "testing with backsoops, mistake" 31 long out?

```<code>const rl = readline.createInterface(shell, shell);
rl.on('line', (line) => console.log(`Line: "${line}" ${line.length} long`));
</code>```

答:
Solved, shell.isTTY was either false or undefined, fixed by changing to

```<code>const rl = readline.createInterface({
  input: shell,
  output: shell,
  terminal: true,
});
</code>```

Title: Node.js parse terminal input

Body:
So I have a ssh2 server, and I want to be able to parse the commands that are entered, I am currently using the readline module, but even it outputs special characters when backspace is used, I don't want every keypress, I just want the entire visible line when Enter is pressed, if I type in testing and press enter, as expected, my log outputs Line: "testing" 7 long, but if I type testing with backspaces then press backspace 5 times, and type oops, mistake, it outputs Line: "testing with backspaces⌂⌂⌂⌂⌂oops, mistake" 41 long.

How do I "parse" these codes to get Line: "testing with backsoops, mistake" 31 long out?

const rl = readline.createInterface(shell, shell);
rl.on('line', (line) => console.log(`Line: "${line}" ${line.length} long`));

Body:
Solved, shell.isTTY was either false or undefined, fixed by changing to

const rl = readline.createInterface({
  input: shell,
  output: shell,
  terminal: true,
});


问:
How to check content of a Noobaa bucket
I am able to check status of Nooba bucket using noobaa bucket status <bucket> command.

```<code>$ noobaa bucket status XYZ
INFO[0005] ✅ Exists: NooBaa "noobaa"
INFO[0005] ✅ Exists: Service "noobaa-mgmt"
INFO[0006] ✅ Exists: Secret "noobaa-operator"
INFO[0006] ✅ Exists: Secret "noobaa-admin"
INFO[0008] ✈  RPC: bucket.read_bucket() Request: {Name:XYZ}
INFO[0010] ✅ RPC: bucket.read_bucket() Response OK: took 14.3ms

Bucket status:
  Bucket                 : XYZ
  OBC Namespace          : xyz-namespace
  OBC BucketClass        : default-bucket-class
  Type                   : REGULAR
  Mode                   : OPTIMAL
  ResiliencyStatus       : OPTIMAL
  QuotaStatus            : QUOTA_NOT_SET
  Num Objects            : 1
  Data Size              : 3.000 B
  Data Size Reduced      : 5.000 B
  Data Space Avail       : 1.000 PB

</code>```

But I am not able to check content present inside Noobaa bucket.

How can we check content of a Noobaa bucket? using Noobaa CLI or any other way?

答:
Your question made me realize that noobaa CLI should have noobaa object list command so I opened a new issue for this enhancement on the operator github repo. Thanks :)

Until this is added, there are several ways we use to list objects:

run noobaa ui - notice that it opens the browser quickly, but on the terminal it prints the credentials for you to use for login. You can probably find the buckets and the drill down to the objects in the UI on your own, and you can also check out some recorded videos that navigate the UI - for example this video.

Take the admin S3 credentials and endpoint from noobaa status and then use your favorite s3 client - I currently use aws-cli or rclone:

```<code>alias s3='AWS_ACCESS_KEY_ID=$NOOBAA_ACCESS_KEY AWS_SECRET_ACCESS_KEY=$NOOBAA_SECRET_KEY aws --endpoint $NOOBAA_S3_ENDPOINT --no-verify-ssl s3'
</code>```

and then:

```<code>s3 ls XYZ
</code>```

Not many noticed but the NooBaa system CR contains a useful Readme text in its status, with commands to "Test S3 client" - ready to copy-paste to set up your aws-cli, including kubectl port-forward to support secure networks and reading the credentials from secrets. Check it out with kubectl describe noobaa. This 40 seconds youtube video shows this briefly. BTW, the readme text is generated for the system but its text does not contain actual secrets, only kubectl commands to read those secrets if permitted to.

```<code>$ kubectl describe noobaa
...

Phase:                Ready
Readme:

Welcome to NooBaa!
-----------------
NooBaa Core Version:     5.3.0-9f579d9
NooBaa Operator Version: 2.1.0

Lets get started:

1. Connect to Management console:

    Read your mgmt console login information (email & password) from secret: "noobaa-admin".

    kubectl get secret noobaa-admin -n backup-service -o json | jq '.data|map_values(@base64d)'

    Open the management console service - take External IP/DNS or Node Port or use port forwarding:

    kubectl port-forward -n backup-service service/noobaa-mgmt 11443:443 &
    open https://localhost:11443

2. Test S3 client:

    kubectl port-forward -n backup-service service/s3 10443:443 &
    NOOBAA_ACCESS_KEY=$(kubectl get secret noobaa-admin -n backup-service -o json | jq -r '.data.AWS_ACCESS_KEY_ID|@base64d')
    NOOBAA_SECRET_KEY=$(kubectl get secret noobaa-admin -n backup-service -o json | jq -r '.data.AWS_SECRET_ACCESS_KEY|@base64d')
    alias s3='AWS_ACCESS_KEY_ID=$NOOBAA_ACCESS_KEY AWS_SECRET_ACCESS_KEY=$NOOBAA_SECRET_KEY aws --endpoint https://localhost:10443 --no-verify-ssl s3'
    s3 ls

...
</code>```

Last option, which should have been mentioned first, but unfortunately I just saw it is broken in the current version v2.1.0 (opened new issue), is to use the generic noobaa api command in order to call the object_api list_objects method like so:

```<code>noobaa api object list_objects '{ "bucket": "first.bucket" }'
</code>```

I hope that helps, feel free to open github issues with suggestions/issues.

Thanks!

(NooBaa CTO)

Title: How to check content of a Noobaa bucket

Body:
I am able to check status of Nooba bucket using noobaa bucket status <bucket> command.

$ noobaa bucket status XYZ
INFO[0005] ✅ Exists: NooBaa "noobaa"
INFO[0005] ✅ Exists: Service "noobaa-mgmt"
INFO[0006] ✅ Exists: Secret "noobaa-operator"
INFO[0006] ✅ Exists: Secret "noobaa-admin"
INFO[0008] ✈  RPC: bucket.read_bucket() Request: {Name:XYZ}
INFO[0010] ✅ RPC: bucket.read_bucket() Response OK: took 14.3ms

Bucket status:
  Bucket                 : XYZ
  OBC Namespace          : xyz-namespace
  OBC BucketClass        : default-bucket-class
  Type                   : REGULAR
  Mode                   : OPTIMAL
  ResiliencyStatus       : OPTIMAL
  QuotaStatus            : QUOTA_NOT_SET
  Num Objects            : 1
  Data Size              : 3.000 B
  Data Size Reduced      : 5.000 B
  Data Space Avail       : 1.000 PB

But I am not able to check content present inside Noobaa bucket.

How can we check content of a Noobaa bucket? using Noobaa CLI or any other way?

Body:
Your question made me realize that noobaa CLI should have noobaa object list command so I opened a new issue for this enhancement on the operator github repo. Thanks :)

Until this is added, there are several ways we use to list objects:

run noobaa ui - notice that it opens the browser quickly, but on the terminal it prints the credentials for you to use for login. You can probably find the buckets and the drill down to the objects in the UI on your own, and you can also check out some recorded videos that navigate the UI - for example this video.

Take the admin S3 credentials and endpoint from noobaa status and then use your favorite s3 client - I currently use aws-cli or rclone:

alias s3='AWS_ACCESS_KEY_ID=$NOOBAA_ACCESS_KEY AWS_SECRET_ACCESS_KEY=$NOOBAA_SECRET_KEY aws --endpoint $NOOBAA_S3_ENDPOINT --no-verify-ssl s3'

and then:

s3 ls XYZ

Not many noticed but the NooBaa system CR contains a useful Readme text in its status, with commands to "Test S3 client" - ready to copy-paste to set up your aws-cli, including kubectl port-forward to support secure networks and reading the credentials from secrets. Check it out with kubectl describe noobaa. This 40 seconds youtube video shows this briefly. BTW, the readme text is generated for the system but its text does not contain actual secrets, only kubectl commands to read those secrets if permitted to.

$ kubectl describe noobaa
...

Phase:                Ready
Readme:

Welcome to NooBaa!
-----------------
NooBaa Core Version:     5.3.0-9f579d9
NooBaa Operator Version: 2.1.0

Lets get started:

1. Connect to Management console:

    Read your mgmt console login information (email & password) from secret: "noobaa-admin".

    kubectl get secret noobaa-admin -n backup-service -o json | jq '.data|map_values(@base64d)'

    Open the management console service - take External IP/DNS or Node Port or use port forwarding:

    kubectl port-forward -n backup-service service/noobaa-mgmt 11443:443 &
    open https://localhost:11443

2. Test S3 client:

    kubectl port-forward -n backup-service service/s3 10443:443 &
    NOOBAA_ACCESS_KEY=$(kubectl get secret noobaa-admin -n backup-service -o json | jq -r '.data.AWS_ACCESS_KEY_ID|@base64d')
    NOOBAA_SECRET_KEY=$(kubectl get secret noobaa-admin -n backup-service -o json | jq -r '.data.AWS_SECRET_ACCESS_KEY|@base64d')
    alias s3='AWS_ACCESS_KEY_ID=$NOOBAA_ACCESS_KEY AWS_SECRET_ACCESS_KEY=$NOOBAA_SECRET_KEY aws --endpoint https://localhost:10443 --no-verify-ssl s3'
    s3 ls

...

Last option, which should have been mentioned first, but unfortunately I just saw it is broken in the current version v2.1.0 (opened new issue), is to use the generic noobaa api command in order to call the object_api list_objects method like so:

noobaa api object list_objects '{ "bucket": "first.bucket" }'

I hope that helps, feel free to open github issues with suggestions/issues.

Thanks!

(NooBaa CTO)


问:
How can the error 'Client found response content type of 'text/html'.. be interpreted
I'm using C# and connecting to a WebService via an auto-generated C# proxy object. The method I'm calling can be long running, and sometimes times out. I get different errors back, sometimes I get a System.Net.WebException or a System.Web.Services.Protocols.SoapException. These exceptions have properties I can interrogate to find the specific type of error from which I can display a human-friendly version of to the user.

But sometimes I just get an InvalidOperationException, and it has the following Message. Is there any way I can interpret what this is without digging through the string for things I recognize, that feels very dirty, and isn't internationalization agnostic, the error message might come back in a different language.

```<code>Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'.
The request failed with the error message:
--
<html>
    <head>
    <title>Request timed out.</title>
                        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Lucida Console";font-size: .9em}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold;     color:navy;         cursor:hand; }
        </style>
    </head>

    <body bgcolor="white">

            <span><H1>Server Error in '/PerformanceManager' Application.<hr     width=100% size=1 color=silver></H1>

            <h2> <i>Request timed out.</i> </h2></span>

            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

            <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

            <br><br>

            <b> Exception Details: </b>System.Web.HttpException: Request timed out.<br><br>

            <b>Source Error:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code>

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>

                  </td>
               </tr>
            </table>

            <br>

            <b>Stack Trace:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
                   <tr>
                  <td>
                      <code>```

[HttpException (0x80004005): Request timed out.]
```</code>

                  </td>
               </tr>
            </table>

            <br>

            <hr width=100% size=1 color=silver>

            <b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.312; ASP.NET Version:2.0.50727.833

            </font>

    </body>
</html>
<!--
[HttpException]: Request timed out.
-->
--.
</code>```

Edit:
I have a try-catch around the method on the web-server. I have debugged it, and the web-server method returns (after a minute or so) without any exception. I also added an unhandled exception handler in the web service and a breakpoint there wasn't hit. As soon as the web-service returns, I get this error in the client instead of the result I expected.

答:
If you are using .NET version 4.0. the validateRequestion is turned on by default for all the pages. in previous versions 1.1 and 2.0 it was only for aspx page. You can turn the default validation off. In that case you have to do the due diligence and make sure that the data is clean. Use HtmlEncode. Do the following to turn the validation off

In the web.config
add the following lines for system.web

```<code> <httpRuntime requestValidationMode="2.0" />
</code>```

and

```<code> <pages validateRequest="false" />
</code>```

You can read more about this http://www.asp.net/learn/whitepapers/aspnet4/breaking-changes
also http://msdn.microsoft.com/en-us/library/ff649310.aspx

Hope this helps.

OwnerDisplayName: Scott Langham

Body:
I'm using C# and connecting to a WebService via an auto-generated C# proxy object. The method I'm calling can be long running, and sometimes times out. I get different errors back, sometimes I get a System.Net.WebException or a System.Web.Services.Protocols.SoapException. These exceptions have properties I can interrogate to find the specific type of error from which I can display a human-friendly version of to the user.

But sometimes I just get an InvalidOperationException, and it has the following Message. Is there any way I can interpret what this is without digging through the string for things I recognize, that feels very dirty, and isn't internationalization agnostic, the error message might come back in a different language.

Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'.
The request failed with the error message:
--

    <title>Request timed out.</title>

Server Error in '/PerformanceManager' Application.

 Request timed out.

             Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

             Exception Details: System.Web.HttpException: Request timed out.

            Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

            Stack Trace:

[HttpException (0x80004005): Request timed out.]

            Version Information: Microsoft .NET Framework Version:2.0.50727.312; ASP.NET Version:2.0.50727.833

--.

Edit:
I have a try-catch around the method on the web-server. I have debugged it, and the web-server method returns (after a minute or so) without any exception. I also added an unhandled exception handler in the web service and a breakpoint there wasn't hit. As soon as the web-service returns, I get this error in the client instead of the result I expected.

LastEditorDisplayName: Scott Langham

Body:
If you are using .NET version 4.0. the validateRequestion is turned on by default for all the pages. in previous versions 1.1 and 2.0 it was only for aspx page. You can turn the default validation off. In that case you have to do the due diligence and make sure that the data is clean. Use HtmlEncode. Do the following to turn the validation off

In the web.config
add the following lines for system.web

 <httpRuntime requestValidationMode="2.0" />

and

 <pages validateRequest="false" />

You can read more about this http://www.asp.net/learn/whitepapers/aspnet4/breaking-changes
also http://msdn.microsoft.com/en-us/library/ff649310.aspx

Hope this helps.


问:
How to use selenium module?
This is what I have so far. I want to open the instagram using selenium</p>

```<code>#code should be inside three backticks
from selenium import webdriver

class InstaBot:
    def __init__(self):
        self.driver = webdriver.chrome()
        self.driver.get("https://instagram.com")

InstaBot()
</code>```

答:
```<code>    from selenium.webdriver import Chrome

    with Chrome() as driver:
        driver.get('https://instagram.com')
        ... #  Add logic here...
</code>```

Title: How to use selenium module?

Body:
This is what I have so far. I want to open the instagram using selenium

#code should be inside three backticks
from selenium import webdriver

class InstaBot:
    def __init__(self):
        self.driver = webdriver.chrome()
        self.driver.get("https://instagram.com")

InstaBot()


问:
Unable to drag and drop external events into FullCalendar dayGridView
I am going crazy with a very strange problem that I am facin using PrimeNG FullCalendar component, this one: https://primefaces.org/primeng/showcase/#/fullcalendar

That is based on the Angular FullCalendar component, this one: https://fullcalendar.io/

In particular I am trying to implement a behavior like the last link where draggable event are mooved into the calendar.

Differently from the link example my draggable events have a start and an end time.
For example I want drag an evet into a specific day of my calendar specifying that it start at 07:00 and that end at 15:00 (this because my calendar represents a worki shift calendar where put person working in a specific time range).

Here you can find my entire code: https://bitbucket.org/dgs_poste_team/soc_calendar/src/master/

Ok as you can see in the app-component view I have:

      <app-header></app-header>

DRAGGABLE

        <app-people-list></app-people-list>

        <app-fullcalendar></app-fullcalendar>

```

<p>On the left there is the <code><app-people-list></code> component showing the list of event\people that I can drag into my calendar for a specific work shift.</p>

<p>On the right side I have the <code><app-fullcalendar></code> component rendering my calendar.</p>

<p>Into the <code>PeopleListComponent</code> class (the controller of the <code>app-people-list</code> component) I have this <code>ngAfterViewInit</code> method:</p>

<pre class="lang-js prettyprint-override"><code>ngAfterViewInit() {
  console.log("PEOPLE LIST ngAfterViewInit() START !!!")
  var self = this

  new Draggable(this.draggablePeopleExternalElement.nativeElement, {
    itemSelector: '.fc-event',
    eventData: function(eventEl) {
      console.log("DRAG !!!");
      console.log("SELECTED SHIFT: " + self.selectedShift.value);

      //var returnedEvent = self.createEventObject(self.selectedShift.value, eventEl.innerText);

      //return returnedEvent;

      var returnedEvent = {
        title: eventEl.innerText,
        startTime: "18:00",
        duration: {
          hours: 8
        }
      };

      return returnedEvent;
    }
  });

}
</code>```

As you can see it is creating a Draggable object used to drag an event\person of my list into the calendar. At the moment it is returning an object like this:

var returnedEvent = {
  title: eventEl.innerText,
  startTime: "18:00",
  duration: { hours: 8 }
};
```

<p>where I put the title of the person\event (it works fine). Then I put (at the moment it is static, then I will make it dynamic) the <code>startTime</code> that is starting time of the event (for example: I drag the person\event into a specific day, it means that this event have to start at the 18:00 of the day in which the event was dragged) and the <code>duration</code> meaning that the event end 8 hours after the starting time.</p>

<p>Ok, in this case it seems to works "fine", in fact when I drag a person\event into a specific day it appears in the calendar, here is a Screenshot:</p>

<p><img src="https://i.stack.imgur.com/QX71R.png" alt="enter image description here"></p>

<p>For example in the previous screenshot I dragged the <strong>PERSONA 2</strong> event into the day having date <strong>22 Februrary 2017</strong> and it is here (the other events came from a static array of events defined into my code)</p>

<p>First strange thing noticed: I expected that thus event starts with something that indicates the starting time (as for the events set for the 9 February that starts with <strong>4p</strong> indicating that this event starts at 16:00 o'clock of this specific day).</p>

<p>Ok then the very strange thing: if I change the <strong>startTime</strong> property of my <strong>returnedEvent</strong> object with a value that is less than <strong>16:00</strong> it doesn't work anymore !!!</p>

<p>For example, using:</p>

<pre class="lang-js prettyprint-override"><code>var returnedEvent = {
  title: eventEl.innerText,
  startTime: "16:00",
  duration: {hours: 8}
};
</code>```

that means: the event start at 4pm of the selected day in the calendar and end at 00:00 of the same day. When I drag this event into the calendar the event doesn't appear on the calendar. It is not rendered !!! It happens for all the startTime previous 17:00, and I can't understand why. Into the JavaScript console I am obtaining no error message.

For completeness, into the FullcalendarComponent class (the class that controll the full calendar component) I have:

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

  events: any[];
  options: any;
  header: any;

  //people: any[];

  @ViewChild('fullcalendar') fullcalendar: FullCalendar;

  constructor(private eventService: EventService) {}

  ngOnInit() {
    this.eventService.getEvents().then(events => {
      this.events = events;
    });

    this.options = {
      plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin, listPlugin],
      defaultDate: '2017-02-01',
      header: {
        left: 'prev,next',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,timeGridDay'
      },
      editable: true,

      dateClick: (dateClickEvent) => { // <-- add the callback here as one of the properties of `options`
        console.log("DATE CLICKED !!!");
      },

      eventClick: (eventClickEvent) => {
        console.log("EVENT CLICKED !!!");
      },

      eventDragStop: (eventDragStopEvent) => {
        console.log("EVENT DRAG STOP !!!");
      },

      eventReceive: (eventReceiveEvent) => {
        //console.log("EXTERNAL EVENT LAND ON THE CALENDAR. Title: " + eventReceiveEvent.event.title + " Selected shift: " + eventReceiveEvent.selectedShift);
        //console.log("EXTERNAL EVENT LAND ON THE CALENDAR. Title: " + eventReceiveEvent.event.title + " Selected start: " + eventReceiveEvent.event.start);

        console.log(eventReceiveEvent);
        this.eventService.addEvent(eventReceiveEvent);
      }
    };

  }

}
```

<p>As you can see it contains this method:</p>

<pre class="lang-js prettyprint-override"><code>eventReceive: (eventReceiveEvent) => {
  //console.log("EXTERNAL EVENT LAND ON THE CALENDAR. Title: " + eventReceiveEvent.event.title + " Selected shift: " + eventReceiveEvent.selectedShift);
  //console.log("EXTERNAL EVENT LAND ON THE CALENDAR. Title: " + eventReceiveEvent.event.title + " Selected start: " + eventReceiveEvent.event.start);

  console.log(eventReceiveEvent);
  this.eventService.addEvent(eventReceiveEvent);
}
</code>```

that receive the previous event emitted by the people list component and put this event into an array (calling a service), it works fine.

I am really not understanding what could be wrong with my code and why using a startTime value < "17:00" it is not working.

What is wrong? What am I missing? How can I change my code to solve this issue?

答:
When dragging an event into a dayGridMonth view, FullCalendar doesn't respect allDay value set in original event definition and always sets allDay: true. That means, by default, events dragged into a dayGridMonth view are considered/supposed to be all-day events.

However, when you create a timed event with startTime and duration set, that event is not an all-day event any more. And when you drag such an event into a dayGridMonth view FullCalendar doesn't allow to drop that event into the view.

What you describe as strangest thing is that, when you create following event;

var returnedEvent = {
  title: eventEl.innerText,
  startTime: "16:00",
  duration: {hours: 8}
};
```

<p>this events end time is after today and FullCalendar considers this as an all-day event. And since this is an all-day event it is allowed to drop it into an <em>all-day slot</em>.</p>

<p>However, when you create following event;</p>

<pre class="lang-js prettyprint-override"><code>var returnedEvent = {
  title: eventEl.innerText,
  startTime: "15:00",
  duration: {hours: 8}
};
</code>```

this events end time is today and FullCalendar considers this not as an all-day event but a timed event. And since this is not an all-day event it is not allowed to drop it into an all-day slot.

You can observe same behavior by switching to week or day views and try dropping events into the all-day row at the top. It doesn't allow to drop timed-events into that row while it allows to drop timed-events into any other row.

As a result; you need a way to workaround for FullCalendar to allow timed events to be dropped into an all-day slot. Simple as said :) it is enough to convert all-day events into timed-events after events are parsed by FullCalendar. This can be done in eventReceive callback.

eventReceive: receivedEvent => {
  receivedEvent.event.setAllDay(false, {maintainDuration: true})
}
```

<p>Long story short, in your <code>FullcalendarComponent</code>;</p>

<pre class="lang-js prettyprint-override"><code>eventReceive: (eventReceiveEvent) => {
  //console.log("EXTERNAL EVENT LAND ON THE CALENDAR. Title: " + eventReceiveEvent.event.title + " Selected shift: " + eventReceiveEvent.selectedShift);
  //console.log("EXTERNAL EVENT LAND ON THE CALENDAR. Title: " + eventReceiveEvent.event.title + " Selected start: " + eventReceiveEvent.event.start);

  //console.log(eventReceiveEvent);
  eventReceiveEvent.event.setAllDay(false, {maintainDuration: true})
  this.eventService.addEvent(eventReceiveEvent);
}
</code>```

But beware that this will affect all dragged events. So, you might want to set all-day to false based on a condition that can be determined by some flag defined during initial event creation. This very much depends on your use case.

Related docs:

https://fullcalendar.io/docs/eventReceive

https://fullcalendar.io/docs/external-dragging

https://fullcalendar.io/docs/event-parsing

https://fullcalendar.io/docs/Event-setAllDay

https://fullcalendar.io/docs/allDayMaintainDuration

I hope it helps, good luck.

Body:
I am going crazy with a very strange problem that I am facin using PrimeNG FullCalendar component, this one: https://primefaces.org/primeng/showcase/#/fullcalendar

That is based on the Angular FullCalendar component, this one: https://fullcalendar.io/

In particular I am trying to implement a behavior like the last link where draggable event are mooved into the calendar.

Differently from the link example my draggable events have a start and an end time.
For example I want drag an evet into a specific day of my calendar specifying that it start at 07:00 and that end at 15:00 (this because my calendar represents a worki shift calendar where put person working in a specific time range).

Here you can find my entire code: https://bitbucket.org/dgs_poste_team/soc_calendar/src/master/

Ok as you can see in the app-component view I have:

      <app-header></app-header>

DRAGGABLE

        <app-people-list></app-people-list>

        <app-fullcalendar></app-fullcalendar>

On the left there is the <app-people-list> component showing the list of event\people that I can drag into my calendar for a specific work shift.

On the right side I have the <app-fullcalendar> component rendering my calendar.

Into the PeopleListComponent class (the controller of the app-people-list component) I have this ngAfterViewInit method:

ngAfterViewInit() {
  console.log("PEOPLE LIST ngAfterViewInit() START !!!")
  var self = this

  new Draggable(this.draggablePeopleExternalElement.nativeElement, {
    itemSelector: '.fc-event',
    eventData: function(eventEl) {
      console.log("DRAG !!!");
      console.log("SELECTED SHIFT: " + self.selectedShift.value);

      //var returnedEvent = self.createEventObject(self.selectedShift.value, eventEl.innerText);

      //return returnedEvent;

      var returnedEvent = {
        title: eventEl.innerText,
        startTime: "18:00",
        duration: {
          hours: 8
        }
      };

      return returnedEvent;
    }
  });

}

As you can see it is creating a Draggable object used to drag an event\person of my list into the calendar. At the moment it is returning an object like this:

var returnedEvent = {
  title: eventEl.innerText,
  startTime: "18:00",
  duration: { hours: 8 }
};

where I put the title of the person\event (it works fine). Then I put (at the moment it is static, then I will make it dynamic) the startTime that is starting time of the event (for example: I drag the person\event into a specific day, it means that this event have to start at the 18:00 of the day in which the event was dragged) and the duration meaning that the event end 8 hours after the starting time.

Ok, in this case it seems to works "fine", in fact when I drag a person\event into a specific day it appears in the calendar, here is a Screenshot:

For example in the previous screenshot I dragged the PERSONA 2 event into the day having date 22 Februrary 2017 and it is here (the other events came from a static array of events defined into my code)

First strange thing noticed: I expected that thus event starts with something that indicates the starting time (as for the events set for the 9 February that starts with 4p indicating that this event starts at 16:00 o'clock of this specific day).

Ok then the very strange thing: if I change the startTime property of my returnedEvent object with a value that is less than 16:00 it doesn't work anymore !!!

For example, using:

var returnedEvent = {
  title: eventEl.innerText,
  startTime: "16:00",
  duration: {hours: 8}
};

that means: the event start at 4pm of the selected day in the calendar and end at 00:00 of the same day. When I drag this event into the calendar the event doesn't appear on the calendar. It is not rendered !!! It happens for all the startTime previous 17:00, and I can't understand why. Into the JavaScript console I am obtaining no error message.

For completeness, into the FullcalendarComponent class (the class that controll the full calendar component) I have:

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

  events: any[];
  options: any;
  header: any;

  //people: any[];

  @ViewChild('fullcalendar') fullcalendar: FullCalendar;

  constructor(private eventService: EventService) {}

  ngOnInit() {
    this.eventService.getEvents().then(events => {
      this.events = events;
    });

    this.options = {
      plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin, listPlugin],
      defaultDate: '2017-02-01',
      header: {
        left: 'prev,next',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,timeGridDay'
      },
      editable: true,

      dateClick: (dateClickEvent) => { // <-- add the callback here as one of the properties of `options`
        console.log("DATE CLICKED !!!");
      },

      eventClick: (eventClickEvent) => {
        console.log("EVENT CLICKED !!!");
      },

      eventDragStop: (eventDragStopEvent) => {
        console.log("EVENT DRAG STOP !!!");
      },

      eventReceive: (eventReceiveEvent) => {
        //console.log("EXTERNAL EVENT LAND ON THE CALENDAR. Title: " + eventReceiveEvent.event.title + " Selected shift: " + eventReceiveEvent.selectedShift);
        //console.log("EXTERNAL EVENT LAND ON THE CALENDAR. Title: " + eventReceiveEvent.event.title + " Selected start: " + eventReceiveEvent.event.start);

        console.log(eventReceiveEvent);
        this.eventService.addEvent(eventReceiveEvent);
      }
    };

  }

}

As you can see it contains this method:

eventReceive: (eventReceiveEvent) => {
  //console.log("EXTERNAL EVENT LAND ON THE CALENDAR. Title: " + eventReceiveEvent.event.title + " Selected shift: " + eventReceiveEvent.selectedShift);
  //console.log("EXTERNAL EVENT LAND ON THE CALENDAR. Title: " + eventReceiveEvent.event.title + " Selected start: " + eventReceiveEvent.event.start);

  console.log(eventReceiveEvent);
  this.eventService.addEvent(eventReceiveEvent);
}

that receive the previous event emitted by the people list component and put this event into an array (calling a service), it works fine.

I am really not understanding what could be wrong with my code and why using a startTime value < "17:00" it is not working.

What is wrong? What am I missing? How can I change my code to solve this issue?

Body:
When dragging an event into a dayGridMonth view, FullCalendar doesn't respect allDay value set in original event definition and always sets allDay: true. That means, by default, events dragged into a dayGridMonth view are considered/supposed to be all-day events.

However, when you create a timed event with startTime and duration set, that event is not an all-day event any more. And when you drag such an event into a dayGridMonth view FullCalendar doesn't allow to drop that event into the view.

What you describe as strangest thing is that, when you create following event;

var returnedEvent = {
  title: eventEl.innerText,
  startTime: "16:00",
  duration: {hours: 8}
};

this events end time is after today and FullCalendar considers this as an all-day event. And since this is an all-day event it is allowed to drop it into an all-day slot.

However, when you create following event;

var returnedEvent = {
  title: eventEl.innerText,
  startTime: "15:00",
  duration: {hours: 8}
};

this events end time is today and FullCalendar considers this not as an all-day event but a timed event. And since this is not an all-day event it is not allowed to drop it into an all-day slot.

You can observe same behavior by switching to week or day views and try dropping events into the all-day row at the top. It doesn't allow to drop timed-events into that row while it allows to drop timed-events into any other row.

As a result; you need a way to workaround for FullCalendar to allow timed events to be dropped into an all-day slot. Simple as said :) it is enough to convert all-day events into timed-events after events are parsed by FullCalendar. This can be done in eventReceive callback.

eventReceive: receivedEvent => {
  receivedEvent.event.setAllDay(false, {maintainDuration: true})
}

Long story short, in your FullcalendarComponent;

eventReceive: (eventReceiveEvent) => {
  //console.log("EXTERNAL EVENT LAND ON THE CALENDAR. Title: " + eventReceiveEvent.event.title + " Selected shift: " + eventReceiveEvent.selectedShift);
  //console.log("EXTERNAL EVENT LAND ON THE CALENDAR. Title: " + eventReceiveEvent.event.title + " Selected start: " + eventReceiveEvent.event.start);

  //console.log(eventReceiveEvent);
  eventReceiveEvent.event.setAllDay(false, {maintainDuration: true})
  this.eventService.addEvent(eventReceiveEvent);
}

But beware that this will affect all dragged events. So, you might want to set all-day to false based on a condition that can be determined by some flag defined during initial event creation. This very much depends on your use case.

Related docs:

https://fullcalendar.io/docs/eventReceive

https://fullcalendar.io/docs/external-dragging

https://fullcalendar.io/docs/event-parsing

https://fullcalendar.io/docs/Event-setAllDay

https://fullcalendar.io/docs/allDayMaintainDuration

I hope it helps, good luck.


问:
Python/NumPy: find the first index of zero, then replace all elements with zero after that for each row
I have an numpy array like this:

```<code>a = np.array([[1, 0, 1, 1, 1],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 1, 1],
              [1, 0, 1, 0, 1]])
</code>```

Question 1:
As shown in the title, I want to replace all elements with zero after the first zero appeared. The result should be like this :

```<code>a = np.array([[1, 0, 0, 0, 0],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 0, 0],
              [1, 0, 0, 0, 0]])
</code>```

Question 2: how to slice different columns for each row like this example?
As I am dealing with an array with large size. If any one could find an efficient way to solve this please. Thank you very much.

答:
Question 1:
You could iterate over the array like so:

```<code>for i in range(a.shape[0]):
    j = 0
    row = a[i]
    while row[j]>0:
        j += 1
    row[j+1:] = 0
</code>```

This will change the array in-place. If you are interested in very high performance, the answers to this question could be of use to find the first zero faster. np.where scans the entire array for this and therefore is not optimal for the task.
Actually, the fastest solution will depend a bit on the distribution of your array entries: If there are many floats in there and rarely is there ever a zero, the while loops in the code above will interrupt late on average, requiring to write only "a few" zeros. If however there are only two possible entries like in your sample array and these occur with a similar probability (i.e. ~50%), there would be a lot of zeros to be written to a, and the following will be faster:

```<code>b = np.zeros(a.shape)
for i in range(a.shape[0]):
    j = 0
    a_row = a[i]
    b_row = b[i]
    while a_row[j]>0:
        b_row[j] = a_row[j]
        j += 1
</code>```

Question 2:
If you mean to slice each row individually on a similar criterion dealing with a first occurence of some kind, you could simply adapt this iteration pattern. If the criterion is more global (like finding the maximum of the row, for example) built-in methods like np.where exist that will be more efficient, but it probably would depend a bit on the criterion itself which choice is best.

Body:
I have an numpy array like this:

a = np.array([[1, 0, 1, 1, 1],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 1, 1],
              [1, 0, 1, 0, 1]])

Question 1:
As shown in the title, I want to replace all elements with zero after the first zero appeared. The result should be like this :

a = np.array([[1, 0, 0, 0, 0],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 0, 0],
              [1, 0, 0, 0, 0]])

Question 2: how to slice different columns for each row like this example?
As I am dealing with an array with large size. If any one could find an efficient way to solve this please. Thank you very much.

Body:
Question 1:
You could iterate over the array like so:

for i in range(a.shape[0]):
    j = 0
    row = a[i]
    while row[j]>0:
        j += 1
    row[j+1:] = 0

This will change the array in-place. If you are interested in very high performance, the answers to this question could be of use to find the first zero faster. np.where scans the entire array for this and therefore is not optimal for the task.
Actually, the fastest solution will depend a bit on the distribution of your array entries: If there are many floats in there and rarely is there ever a zero, the while loops in the code above will interrupt late on average, requiring to write only "a few" zeros. If however there are only two possible entries like in your sample array and these occur with a similar probability (i.e. ~50%), there would be a lot of zeros to be written to a, and the following will be faster:

b = np.zeros(a.shape)
for i in range(a.shape[0]):
    j = 0
    a_row = a[i]
    b_row = b[i]
    while a_row[j]>0:
        b_row[j] = a_row[j]
        j += 1

Question 2:
If you mean to slice each row individually on a similar criterion dealing with a first occurence of some kind, you could simply adapt this iteration pattern. If the criterion is more global (like finding the maximum of the row, for example) built-in methods like np.where exist that will be more efficient, but it probably would depend a bit on the criterion itself which choice is best.


问:
Are props.render and props.children equal?
I can't find a distinction between props.render and props.children, so I'm starting to believe that they achieve the same thing BUT in different ways.

Is this a correct assumption? If not; how are they different (beside how they are implemented), and when should I use one over the other?

答:
render-props can address your questions.

children is part of the Top-level API, meaning, it is intrinsic to a react component. The children prop can be just about anything react can render, typically an element or array of elements, but can be a function similar to a "render prop".

The "render" prop, however, is not intrinsic, it can be anything really... so long as it is a function.

Using props other then render

It’s important to remember that just because the pattern is called
  “render props” you don’t have to use a prop named render to use this
  pattern. In fact, any prop that is a function that a component uses to
  know what to render is technically a “render prop”.


问:
Discord.py @bot.event
So I have a script that uses both @bot.event and @bot.command(). The problem is that when I have a @bot.event waiting the @bot.command() will not run.

Here is my code:

```<code>@bot.event
async def on_ready():
    print("Bot Is Ready And Online!")

async def react(message):
    if message.content == "Meeting":
        await message.add_reaction("")

@bot.command()
async def info(ctx):
    await ctx.send("Hello, thanks for testing out our bot. ~ techNOlogics")

@bot.command(pass_context=True)
async def meet(ctx,time):
    if ctx.message.author.name == "techNOlogics":
        await ctx.channel.purge(limit=1)
        await ctx.send("**Meeting at " + time + " today!** React if you read.")

@bot.event ##THIS ONE HOLDS UP THE WHOLE SCRIPT
async def on_message(message):
    await react(message)
</code>```

答:
When using a mixture of the on_message event with commands, you'll want to add await bot.process_commands(message), like so:

@bot.event
async def on_message(message):
    await bot.process_commands(message)
    # rest of code
```

As said in the docs:

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

If you choose to override the on_message() event, you then you should invoke this coroutine as well.

References:

Bot.process_commands()

on_message()

Title: Discord.py @bot.event

Body:
So I have a script that uses both @bot.event and @bot.command(). The problem is that when I have a @bot.event waiting the @bot.command() will not run.

Here is my code:

@bot.event
async def on_ready():
    print("Bot Is Ready And Online!")

async def react(message):
    if message.content == "Meeting":
        await message.add_reaction("")

@bot.command()
async def info(ctx):
    await ctx.send("Hello, thanks for testing out our bot. ~ techNOlogics")

@bot.command(pass_context=True)
async def meet(ctx,time):
    if ctx.message.author.name == "techNOlogics":
        await ctx.channel.purge(limit=1)
        await ctx.send("**Meeting at " + time + " today!** React if you read.")

@bot.event ##THIS ONE HOLDS UP THE WHOLE SCRIPT
async def on_message(message):
    await react(message)

Body:
When using a mixture of the on_message event with commands, you'll want to add await bot.process_commands(message), like so:

@bot.event
async def on_message(message):
    await bot.process_commands(message)
    # rest of code

As said in the docs:

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

If you choose to override the on_message() event, you then you should invoke this coroutine as well.

References:

Bot.process_commands()

on_message()


问:
Graphql-ruby how to define a hash as type
Is there a possibility to define a Hash as Type field in graphql-ruby schema?
In my data structure there is a multi language String type, which consist out of the language code as key and a corresponding text. At the Moment there are 2 languages provided like:

```<code>{
  "en" : "hello",
  "de" : "hallo"
}
</code>```

So it is enough to  build a type like that:

 class Types::LanguageStringType < GraphQL::Schema::Object
   field :de, String, null:true
   field :en, String, null:true
 end
```
<p>How does a type looks like which provides a Map of String to String? The corresponding typescript interface looks like this for example:</p>
```title: {
  [language: string]: string;
}
```
<p>To make a step further, like a recursive node:</p>
```export interface NodeDescription {
  name: string
  children?: {
      [childrenCategory: string]: NodeDescription[];
  }
}
```

Is there a way to use this in a field as a Types::NodeDescriptionType in graphql-ruby schema?

答:
There is no such thing as a generic object type. And there is no built-in String -> String Hash type. Your GraphQL API is built on a specific object graph which you have to define in advance. If all you want is a String -> String Hash, then you may be able to define your own scalar, or if its sufficient you could use the built-in JSON scalar that comes with graphql-ruby:

Source: https://graphql-ruby.org/type_definitions/scalars.html

Body:
Is there a possibility to define a Hash as Type field in graphql-ruby schema?
In my data structure there is a multi language String type, which consist out of the language code as key and a corresponding text. At the Moment there are 2 languages provided like:

{
  "en" : "hello",
  "de" : "hallo"
}

So it is enough to  build a type like that:

 class Types::LanguageStringType < GraphQL::Schema::Object
   field :de, String, null:true
   field :en, String, null:true
 end

How does a type looks like which provides a Map of String to String? The corresponding typescript interface looks like this for example:

title: {
  [language: string]: string;
}

To make a step further, like a recursive node:

export interface NodeDescription {
  name: string
  children?: {
      [childrenCategory: string]: NodeDescription[];
  }
}

Is there a way to use this in a field as a Types::NodeDescriptionType in graphql-ruby schema?


问:
MongoDB FilterDefinition & IQueryable in C#
I have the following spatial FilterDefinition:

```<code>var filter = Builders<MyDocument>
                .Filter
                .Near(x => x.Point, point, 1000);
</code>```

Is there any way to include this into an IQueryable expression?

For example, I might have the following LINQ statement. How can I include the above condition?  From what I can see, there is no LINQ support for spatial querying.

```<code>return Database
    .GetCollection<Places>("Places")
    .AsQueryable()
    .Where(x => x.StartDate.Date <= date)
    .Where(x => x.EndDate.Date >= date)
    .Where(x => keys.Contains(selectedKeys))
    .ToList();
</code>```

I am using the new 2.2.2 libraries.

答:
As of 2.4, you can use Inject() to accomplish this.

See: https://mongodb.github.io/mongo-csharp-driver/2.4/apidocs/html/M_MongoDB_Driver_Linq_LinqExtensions_Inject__1.htm

With the example code provided (corrected slightly) this would be:

```<code>var filter = Builders<Places>
                .Filter
                .Near(x => x.Point, point, 1000);

return Database
    .GetCollection<Places>("Places")
    .AsQueryable()
    .Where(x => x.StartDate.Date <= date)
    .Where(x => x.EndDate.Date >= date)
    .Where(x => keys.Contains(selectedKeys))
    .Where(x => filter.Inject())
    .ToList();
</code>```

Body:
I have the following spatial FilterDefinition:

var filter = Builders<MyDocument>
                .Filter
                .Near(x => x.Point, point, 1000);

Is there any way to include this into an IQueryable expression?

For example, I might have the following LINQ statement. How can I include the above condition?  From what I can see, there is no LINQ support for spatial querying.

return Database
    .GetCollection<Places>("Places")
    .AsQueryable()
    .Where(x => x.StartDate.Date <= date)
    .Where(x => x.EndDate.Date >= date)
    .Where(x => keys.Contains(selectedKeys))
    .ToList();

I am using the new 2.2.2 libraries.

Body:
As of 2.4, you can use Inject() to accomplish this.

See: https://mongodb.github.io/mongo-csharp-driver/2.4/apidocs/html/M_MongoDB_Driver_Linq_LinqExtensions_Inject__1.htm

With the example code provided (corrected slightly) this would be:

var filter = Builders<Places>
                .Filter
                .Near(x => x.Point, point, 1000);

return Database
    .GetCollection<Places>("Places")
    .AsQueryable()
    .Where(x => x.StartDate.Date <= date)
    .Where(x => x.EndDate.Date >= date)
    .Where(x => keys.Contains(selectedKeys))
    .Where(x => filter.Inject())
    .ToList();


问:
Storing a user's Facebook access token
I have a database that stores a user's access token (along with some other data). My list of permissions include offline_access when I authorize the user.

So will the user's access token (client side) always be the same as that user's access token in the database? Or can the user's access token change when they log out, change their password, etc?

答:
No, the access token will not always be the same, even with offline_access.  You will need to get a new access token when 1) the user changes their password or 2) deactivates your app.  Otherwise, it should remain the same.

The users Facebook id will never change though.  This can be parsed from the access token or obtained by calling the /me graph api.

Facebook has a blog post that goes on in detail about this.

Update: Facebook added a blog post specifically for handling revoked authorization.

Title: Storing a user's Facebook access token


问:
TypeScript function overloading with passing a variable
I'm trying to use TypeScript function overloading:

```<code>function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations): T;
function useEntityTranslation<T extends Translation>(entity: null): {};

function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations | null): T | {} {
  // do smth and return T or {}
}
</code>```

It works if I call it these ways:

```<code>useEntityTranslation<ProductTranslation>(product); // EntityWithTranslations type
useEntityTranslation<ProductTranslation>(null);
</code>```

But if product is of type EntityWithTranslations | null (it's in React component: null until an entity is retrieved from api)

```<code>useEntityTranslation<ProductTranslation>(product); // EntityWithTranslations | null
</code>```

TypeScript throws an error No overload matches this call.

It's because the type EntityWithTranslations | null is not assignable to any of the two overloads.

But how can I make it understandable for TypeScript?

UPDATE:

The problem also is I can't use a received value as a known type

```<code>const translation = useEntityTranslation<ProductTranslation>(product);
translation.name // name doesn't exist in {}
</code>```

My workaround is to add one more overload:

```<code>function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations | null): { [name: string]: any }
</code>```

I use translation if product isn't null, so I'm sure translation is of type ProductTranslation.

Not awesome (translation.name -> any) but at least works

答:
maybe this is that you want</p>

```<code>function useEntityTranslation<T extends Translation>(entity?:EntityWithTranslations): T | {}
</code>```

Body:
I'm trying to use TypeScript function overloading:

function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations): T;
function useEntityTranslation<T extends Translation>(entity: null): {};

function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations | null): T | {} {
  // do smth and return T or {}
}

It works if I call it these ways:

useEntityTranslation<ProductTranslation>(product); // EntityWithTranslations type
useEntityTranslation<ProductTranslation>(null);

But if product is of type EntityWithTranslations | null (it's in React component: null until an entity is retrieved from api)

useEntityTranslation<ProductTranslation>(product); // EntityWithTranslations | null

TypeScript throws an error No overload matches this call.

It's because the type EntityWithTranslations | null is not assignable to any of the two overloads.

But how can I make it understandable for TypeScript?

UPDATE:

The problem also is I can't use a received value as a known type

const translation = useEntityTranslation<ProductTranslation>(product);
translation.name // name doesn't exist in {}

My workaround is to add one more overload:

function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations | null): { [name: string]: any }

I use translation if product isn't null, so I'm sure translation is of type ProductTranslation.

Not awesome (translation.name -> any) but at least works

Body:
maybe this is that you want

function useEntityTranslation<T extends Translation>(entity?:EntityWithTranslations): T | {}