问:
Returning a SUBSET of a multidimensional array that satisfies a particular condition?
Basically taking a multidimensional array and checking to see whether the 3rd column of the array is the hypotenuse of the first and second columns. This is the code I have so far. I've added some stuff in the comments to sort of facilitate a better understanding of what's going on.

```<code>import numpy
import random

def triple(mm):
    mm=np.asanyarray(mm) # I think this is how we specify that the paremeter should be an array, however,
    # it's possible the parameter isn't just mm, it could be 'j', 'qw', 'mm1', whatever. I'm not sure
    # how to work that while specifying the parameter must be array.
assert mm.ndim == 2 # we want mm or w/e the name of the parameter to be a 1 multidimensional array
assert mm.shape[1] == 3 # we want 3 columns, with any number of rows
    x = mm[:,0]
    y = mm[:,1]
    z = mm[:,2] # 3rd column is to be checked to see if its's the hypotenuse of 1st & 2nd columns
    zz = np.hypot(x,y)
    condition = np.any(z) == np.any(zz)
    return np.array([condition, mm]) # I'm not sure how to specify it here, that we want the function to return a subset
        # of the original multi-dim array, where the 3rd column is in fact the hypotenuse of the first and
        # second columns. And we want to exclude the rows that don't satisfy this condition.
</code>```

And I'd want to check   :

```<code>mm = np.array([[5,5,5],[5,12,13],[3,4,5],[5,11,21],[8,15,17]])
triple(mm)
</code>```

But the error I'm getting is :

```<code>ValueError: setting an array element with a sequence.
</code>```

I'm not sure if that 'condition' I set is even the right way to go about this, so can someone help steer me in the right direction?
Feel free to ask for more clarifications.

答:
A vectored way to do that is :

This compute x²+y²-z² on each line (axis=1)

```<code>In [1]: goods=(mm*mm*[1,1,-1]).sum(axis=1)==0

In [2]: goods
Out[2]: array([False,  True,  True, False,  True], dtype=bool)
</code>```

And with boolean indexing :

```<code>In [3]: mm[goods]
Out[3]:
array([[ 5, 12, 13],
       [ 3,  4,  5],
       [ 8, 15, 17]])
</code>```

Your condition is not good : np.any(z) == np.any(zz) is true if zz and z are not the null vector.

np.array([condition, mm]) is here np.array ([ True, [[5....]] ]) , which trig the error message.

Body:
Basically taking a multidimensional array and checking to see whether the 3rd column of the array is the hypotenuse of the first and second columns. This is the code I have so far. I've added some stuff in the comments to sort of facilitate a better understanding of what's going on.

import numpy
import random

def triple(mm):
    mm=np.asanyarray(mm) # I think this is how we specify that the paremeter should be an array, however,
    # it's possible the parameter isn't just mm, it could be 'j', 'qw', 'mm1', whatever. I'm not sure
    # how to work that while specifying the parameter must be array.
assert mm.ndim == 2 # we want mm or w/e the name of the parameter to be a 1 multidimensional array
assert mm.shape[1] == 3 # we want 3 columns, with any number of rows
    x = mm[:,0]
    y = mm[:,1]
    z = mm[:,2] # 3rd column is to be checked to see if its's the hypotenuse of 1st & 2nd columns
    zz = np.hypot(x,y)
    condition = np.any(z) == np.any(zz)
    return np.array([condition, mm]) # I'm not sure how to specify it here, that we want the function to return a subset
        # of the original multi-dim array, where the 3rd column is in fact the hypotenuse of the first and
        # second columns. And we want to exclude the rows that don't satisfy this condition.

And I'd want to check   :

mm = np.array([[5,5,5],[5,12,13],[3,4,5],[5,11,21],[8,15,17]])
triple(mm)

But the error I'm getting is :

ValueError: setting an array element with a sequence.

I'm not sure if that 'condition' I set is even the right way to go about this, so can someone help steer me in the right direction?
Feel free to ask for more clarifications.

Body:
A vectored way to do that is :

This compute x²+y²-z² on each line (axis=1)

In [1]: goods=(mm*mm*[1,1,-1]).sum(axis=1)==0

In [2]: goods
Out[2]: array([False,  True,  True, False,  True], dtype=bool)

And with boolean indexing :

In [3]: mm[goods]
Out[3]:
array([[ 5, 12, 13],
       [ 3,  4,  5],
       [ 8, 15, 17]])

Your condition is not good : np.any(z) == np.any(zz) is true if zz and z are not the null vector.

np.array([condition, mm]) is here np.array ([ True, [[5....]] ]) , which trig the error message.


来源: stackexchange

问:
React - bubble up state to change className on children
I have a hierarchy of data broken down into 6 columns for each tier of the hierarchy. As the user clicks through their selection, their selected location is highlighted via a dynamic css className and the corresponding list of data shows. I figured out how to make the highlight move for each selection. However, if the user starts back at the beginning of the hierarchy, it holds the last highlight in state.

For example, If I have a hierarchy of country, state, city and I selected USA, California, LA. If I select a different country, and then click back to USA, California will still be highlighted. How do I change the className across all columns?

I realize there are several similar posts about bubbling up state. I have not been able to figure out how to apply them to my scenario as I need to go up one more child than the usual examples.

Code structure:
App.js, LocationList.js, Location.js

LocationList.js

```<code>class LocationList extends Component {
    constructor(props){
        super(props);
        this.state = {
            title: props.title,
            clicked: false,
         };
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(selectedItem) {
       this.props.onListClick(selectedItem)
       this.setState({clicked: selectedItem})
    }

    isSelected(location){ //current selected item is highlighted
        if(location.LocationId === this.state.clicked.LocationId){
            return 'highlight'
        }
        else {return 'no_highlight'}
    }

    return( ..//other info..
                 <Location
                    location={location}
                    key={location.LocationId+location.LocationName}
                    tier={this.props.level}
                    handler={this.handleClick}
                    highlightClass={this.isSelected(location)}
                  />
</code>```

Location.js

```<code>class Location extends Component {
    constructor(props) {
        super(props);
        this.state={
            locationsList: props.locationList
        }
        this.onClick = this.onClick.bind(this);
    }

    onClick(selectedItem) {
        this.props.handler(this.props.location);
     };

  render() {
        let location = this.props.location;
        console.log(this.props)

        return(
            <div
                id="item"
                style={locationStyle}
                key={location.LocationId}
                value={location.Name}
                level={location.Level}
                onClick={this.onClick}
                className={this.props.highlightClass}
            >
                {location.LocationName}
            </div>
        );
    }
  }
</code>```

App.js - this is where I'm stuck

```<code>handleClick(selectedItem) {
// See value user clicked
console.log('Selected location: ', selectedItem)
}

render() {
      return(
          <div className="row">
          <LocationList key="1" level="1" title="Country" lis={this.state.column Tier1} onListClick={this.handleClick}/>
          <LocationList key="2" level="2" title="State" lis={this.state.column Tier2} onListClick={this.handleClick}/>
          <LocationList key="3" level="3" title="City" lis={this.state.column Tier3} onListClick={this.handleClick}/>
  </div>
 );
</code>```

}

App.css

```<code>.no_highlight {
  background-color: transparent
}
.highlight {
  background-color: #007dc34d
}
</code>```

答:
Store the whole selection in the App state, then pass down the appropriate selection to the corresponding LocationList. Finally, implement different handlers for LocationList clicks to reset the state

```<code>class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ...
      selection: {
        country: null,
        state: null,
        city: null
      }
    };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(getSelection) {
    return location => {
      const selection = getSelection(location);
      this.setState({
        selection: Object.assign({}, this.state.selection, selection)
      };
    };
  }

  render() {
    return (
      <div>
        ...
        <LocationList title="Country"
                      selection={this.state.selection.country}
                      onClick={this.handleClick(country => ({ country, state: null, city: null }))}
                      // other props
        />
        <LocationList title="State"
                      selection={this.state.selection.state}
                      onClick={this.handleClick(state => ({ state, city: null }))}
                      // other props
        />
        <LocationList title="City"
                      selection={this.state.selection.city}
                      onClick={this.handleClick(city => ({ city }))}
        />
      </div>
    );
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a hierarchy of data broken down into 6 columns for each tier of the hierarchy. As the user clicks through their selection, their selected location is highlighted via a dynamic css className and the corresponding list of data shows. I figured out how to make the highlight move for each selection. However, if the user starts back at the beginning of the hierarchy, it holds the last highlight in state.

For example, If I have a hierarchy of country, state, city and I selected USA, California, LA. If I select a different country, and then click back to USA, California will still be highlighted. How do I change the className across all columns?

I realize there are several similar posts about bubbling up state. I have not been able to figure out how to apply them to my scenario as I need to go up one more child than the usual examples.

Code structure:
App.js, LocationList.js, Location.js

LocationList.js

class LocationList extends Component {
    constructor(props){
        super(props);
        this.state = {
            title: props.title,
            clicked: false,
         };
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(selectedItem) {
       this.props.onListClick(selectedItem)
       this.setState({clicked: selectedItem})
    }

    isSelected(location){ //current selected item is highlighted
        if(location.LocationId === this.state.clicked.LocationId){
            return 'highlight'
        }
        else {return 'no_highlight'}
    }

    return( ..//other info..
                 <Location
                    location={location}
                    key={location.LocationId+location.LocationName}
                    tier={this.props.level}
                    handler={this.handleClick}
                    highlightClass={this.isSelected(location)}
                  />

Location.js

class Location extends Component {
    constructor(props) {
        super(props);
        this.state={
            locationsList: props.locationList
        }
        this.onClick = this.onClick.bind(this);
    }

    onClick(selectedItem) {
        this.props.handler(this.props.location);
     };

  render() {
        let location = this.props.location;
        console.log(this.props)

        return(

                {location.LocationName}

        );
    }
  }

App.js - this is where I'm stuck

handleClick(selectedItem) {
// See value user clicked
console.log('Selected location: ', selectedItem)
}

render() {
      return(

          <LocationList key="1" level="1" title="Country" lis={this.state.column Tier1} onListClick={this.handleClick}/>
          <LocationList key="2" level="2" title="State" lis={this.state.column Tier2} onListClick={this.handleClick}/>
          <LocationList key="3" level="3" title="City" lis={this.state.column Tier3} onListClick={this.handleClick}/>

 );

}

App.css

.no_highlight {
  background-color: transparent
}
.highlight {
  background-color: #007dc34d
}

Body:
Store the whole selection in the App state, then pass down the appropriate selection to the corresponding LocationList. Finally, implement different handlers for LocationList clicks to reset the state

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ...
      selection: {
        country: null,
        state: null,
        city: null
      }
    };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(getSelection) {
    return location => {
      const selection = getSelection(location);
      this.setState({
        selection: Object.assign({}, this.state.selection, selection)
      };
    };
  }

  render() {
    return (
      <div>
        ...
        <LocationList title="Country"
                      selection={this.state.selection.country}
                      onClick={this.handleClick(country => ({ country, state: null, city: null }))}
                      // other props
        />
        <LocationList title="State"
                      selection={this.state.selection.state}
                      onClick={this.handleClick(state => ({ state, city: null }))}
                      // other props
        />
        <LocationList title="City"
                      selection={this.state.selection.city}
                      onClick={this.handleClick(city => ({ city }))}
        />
      </div>
    );
  }
}


问:
How to match against an iterator's item?
What is the most idiomatic way to match against an iterator's item? For example, if we take command line arguments, what is the best way to use pattern matching on one of the items? This is what I'm doing and I'm not 100% sure why as_ref() is required and why &args[0] wouldn't work:

```<code>let args: Vec<String> = env::args().skip(1).collect();
match args[0].as_ref() {...}
</code>```

答:
Since env::args() returns an iterator (Args), you can work with it like with any other iterator. If you want to match against a given item once, the simplest way to do it would be:

```<code>use std::env;

fn main() {
    let mut args = env::args().skip(1);

    match args.next() {
        Some(x) => {
            if &x == "herp derp" { ... }
        },
        None => ()
    }
}
</code>```

Body:
What is the most idiomatic way to match against an iterator's item? For example, if we take command line arguments, what is the best way to use pattern matching on one of the items? This is what I'm doing and I'm not 100% sure why as_ref() is required and why &args[0] wouldn't work:

let args: Vec<String> = env::args().skip(1).collect();
match args[0].as_ref() {...}

Body:
Since env::args() returns an iterator (Args), you can work with it like with any other iterator. If you want to match against a given item once, the simplest way to do it would be:

use std::env;

fn main() {
    let mut args = env::args().skip(1);

    match args.next() {
        Some(x) => {
            if &x == "herp derp" { ... }
        },
        None => ()
    }
}


问:
Reverse DNS-style string
In a script running in a Debian environment, what is a good way to reverse a DNS-style string?

For example, if my script has:

```<code>example.org
</code>```

What would be a good way to reverse it, so that the string would read:

```<code>org.example
</code>```

A longer example:

```<code>www.example.org
</code>```

should reverse to:

```<code>org.example.www
</code>```

Title: Reverse DNS-style string

Body:
In a script running in a Debian environment, what is a good way to reverse a DNS-style string?

For example, if my script has:

example.org

What would be a good way to reverse it, so that the string would read:

org.example

A longer example:

www.example.org

should reverse to:

org.example.www

Body:
You can try

sed -E 's/\./\n/g;s/$/\n/;:A;s/([^\n]*)\n(.*)(\n)(.*)/\2\3.\1\4/;tA;s/\n//'


问:
PHP - json_decode from url to variables
i had this url

```<code> https://poloniex.com/public?command=returnTicker
</code>```

thats the json output of the first 2 (for example)

```<code> {"BTC_BCN":{"id":7,"last":"0.00000018","lowestAsk":"0.00000018","highestBid":"0.00000017","percentChange":"0.00000000","baseVolume":"58.73610647","quoteVolume":"328275043.97652394","isFrozen":"0","high24hr":"0.00000019","low24hr":"0.00000017"},"BTC_BELA":{"id":8,"last":"0.00001191","lowestAsk":"0.00001191","highestBid":"0.00001174","percentChange":"0.13536701","baseVolume":"6.33896473","quoteVolume":"572949.02508918","isFrozen":"0","high24hr":"0.00001200","low24hr":"0.00001033"},
</code>```

now i want to get all datas to varialbles. Like... $curreny = xxx; $last = xxx,..

i have tried it with that..

```<code>$url = "https://poloniex.com/public?command=returnTicker";
$response = file_get_contents($url);
$obj = json_decode($response,true);
$keys = array_keys((array)$obj);

foreach($keys as $result) {
$marketname = $result; }
</code>```

that works for the first level .
then i get a list of all currencies. But.. how can i get all other data to the currency?

a second foreach? like..

```<code> foreach($result[$marketname] as $result2) { }
</code>```

doesn't make sense, i think!?

i would like to have it in that form

$currency = BTC_BCN;
$last = 0.00003223;
and so on..

Any idea?

答:
You don't need to use array_keys.

You can use foreach to keep track of the key.

```<code>//$json = file_get_contents($url);
$json = '{"BTC_BCN":{"id":7,"last":"0.00000018","lowestAsk":"0.00000018","highestBid":"0.00000017","percentChange":"0.00000000","baseVolume":"58.73610647","quoteVolume":"328275043.97652394","isFrozen":"0","high24hr":"0.00000019","low24hr":"0.00000017"},"BTC_BELA":{"id":8,"last":"0.00001191","lowestAsk":"0.00001191","highestBid":"0.00001174","percentChange":"0.13536701","baseVolume":"6.33896473","quoteVolume":"572949.02508918","isFrozen":"0","high24hr":"0.00001200","low24hr":"0.00001033"}}';

$arr = json_decode($json, true);

Foreach($arr as $key => $val){
    Echo "in ".$key . " last is ". $val['last'] ."\n";
}
</code>```

Output is:

```<code>in BTC_BCN last is 0.00000018
in BTC_BELA last is 0.00001191
</code>```

https://3v4l.org/UpkOm

If you want to use the items from the array as variables you can extract the variables.

I do not use this method myself as the values are in the array anyways.

I add this method because your question kind of implies that it's what you want.

On each iteration the variables will be overwritten, that is why this method is not recommended.

If one of the items do not have "last" all other variables will be overwritten with new data on the iteration except "last".

That means you have both new and old data in your variables at the same time.

My advice is to use the array and not to extract the variables.

```<code>$json = '{"BTC_BCN":{"id":7,"last":"0.00000018","lowestAsk":"0.00000018","highestBid":"0.00000017","percentChange":"0.00000000","baseVolume":"58.73610647","quoteVolume":"328275043.97652394","isFrozen":"0","high24hr":"0.00000019","low24hr":"0.00000017"},"BTC_BELA":{"id":8,"last":"0.00001191","lowestAsk":"0.00001191","highestBid":"0.00001174","percentChange":"0.13536701","baseVolume":"6.33896473","quoteVolume":"572949.02508918","isFrozen":"0","high24hr":"0.00001200","low24hr":"0.00001033"}}';

$arr = json_decode($json, true);

Foreach($arr as $key => $val){
    Extract($val);
    Echo $key ."\n";
    Echo $last ."\n";
    Echo $baseVolume ."\n\n";
}
</code>```

https://3v4l.org/aZv1s

Title: PHP - json_decode from url to variables

Body:
i had this url

 https://poloniex.com/public?command=returnTicker

thats the json output of the first 2 (for example)

 {"BTC_BCN":{"id":7,"last":"0.00000018","lowestAsk":"0.00000018","highestBid":"0.00000017","percentChange":"0.00000000","baseVolume":"58.73610647","quoteVolume":"328275043.97652394","isFrozen":"0","high24hr":"0.00000019","low24hr":"0.00000017"},"BTC_BELA":{"id":8,"last":"0.00001191","lowestAsk":"0.00001191","highestBid":"0.00001174","percentChange":"0.13536701","baseVolume":"6.33896473","quoteVolume":"572949.02508918","isFrozen":"0","high24hr":"0.00001200","low24hr":"0.00001033"},

now i want to get all datas to varialbles. Like... $curreny = xxx; $last = xxx,..

i have tried it with that..

$url = "https://poloniex.com/public?command=returnTicker";
$response = file_get_contents($url);
$obj = json_decode($response,true);
$keys = array_keys((array)$obj);

foreach($keys as $result) {
$marketname = $result; }

that works for the first level .
then i get a list of all currencies. But.. how can i get all other data to the currency?

a second foreach? like..

 foreach($result[$marketname] as $result2) { }

doesn't make sense, i think!?

i would like to have it in that form

$currency = BTC_BCN;
$last = 0.00003223;
and so on..

Any idea?

Body:
You don't need to use array_keys.

You can use foreach to keep track of the key.

//$json = file_get_contents($url);
$json = '{"BTC_BCN":{"id":7,"last":"0.00000018","lowestAsk":"0.00000018","highestBid":"0.00000017","percentChange":"0.00000000","baseVolume":"58.73610647","quoteVolume":"328275043.97652394","isFrozen":"0","high24hr":"0.00000019","low24hr":"0.00000017"},"BTC_BELA":{"id":8,"last":"0.00001191","lowestAsk":"0.00001191","highestBid":"0.00001174","percentChange":"0.13536701","baseVolume":"6.33896473","quoteVolume":"572949.02508918","isFrozen":"0","high24hr":"0.00001200","low24hr":"0.00001033"}}';

$arr = json_decode($json, true);

Foreach($arr as $key => $val){
    Echo "in ".$key . " last is ". $val['last'] ."\n";
}

Output is:

in BTC_BCN last is 0.00000018
in BTC_BELA last is 0.00001191

https://3v4l.org/UpkOm

If you want to use the items from the array as variables you can extract the variables.

I do not use this method myself as the values are in the array anyways.

I add this method because your question kind of implies that it's what you want.

On each iteration the variables will be overwritten, that is why this method is not recommended.

If one of the items do not have "last" all other variables will be overwritten with new data on the iteration except "last".

That means you have both new and old data in your variables at the same time.

My advice is to use the array and not to extract the variables.

$json = '{"BTC_BCN":{"id":7,"last":"0.00000018","lowestAsk":"0.00000018","highestBid":"0.00000017","percentChange":"0.00000000","baseVolume":"58.73610647","quoteVolume":"328275043.97652394","isFrozen":"0","high24hr":"0.00000019","low24hr":"0.00000017"},"BTC_BELA":{"id":8,"last":"0.00001191","lowestAsk":"0.00001191","highestBid":"0.00001174","percentChange":"0.13536701","baseVolume":"6.33896473","quoteVolume":"572949.02508918","isFrozen":"0","high24hr":"0.00001200","low24hr":"0.00001033"}}';

$arr = json_decode($json, true);

Foreach($arr as $key => $val){
    Extract($val);
    Echo $key ."\n";
    Echo $last ."\n";
    Echo $baseVolume ."\n\n";
}

https://3v4l.org/aZv1s


问:
Why would the debugger not be stopping at a breakpoint in my ASP.NET application?
I'm trying to debug a large ASP.NET application.

I set a breakpoint on the first line in Page_Load in Default.aspx.cs.

When I start the application, my breakpoint briefly turns into a red round outline with an exclamation in it, then turns back into a regular breakpoint, then the application starts without ever stopping at my breakpoint.

MSDN tells me that this symbol means "the breakpoint location has not been loaded". So how can I get the breakpoint location to load? It was working a couple weeks ago. What kinds of things could cause a breakpoint to "not be loaded"?

What can I do so that the debugger stops at my breakpoints again?

Addendum:

I still can't get debugging to work by pressing F5, but I can start the website, then do debug/attach-process to get into debugging mode. If anyone knows why this would work but when I press F5 it would not work (the debugging buttons don't even show up on F5), any ideas would be welcome.

答:
In my case, the issue ending up being related to both using full IIS (not Express) and having a debug build where it included full debug symbols but also had project properties, Build, Optimize code checked.

Under Express, this works fine, but under full IIS this doesn't work.  Visual Studio attaches to the w3wp process correctly, but it does not load symbols for the optimized dll.  In Visual Studio you can go to Debug, Windows, Modules then scroll for the specific dll and see if under the Symbol Status column it shows Skipped Loading Symbols..  Right-click on it and select Load Symbols to make it work.

One additional setting that can affect this is if Visual Studio is set to only debug user code under Debug, Options and Settings, Debugging, General, Enable Just My Code.  When optimized, the dlls will be marked as not user code when running under full IIS, so when Just My Code is enabled any breakpoints in them will be skipped.  You can either set VS to debug non-user code or set the build to not optimize to allow breakpoints to be hit.

ContentLicense: CC BY-SA 2.5


问:
Headings in an ol, indent left or negative text-indent
I'm trying to have the heading to the left of the list item.

I don't want to nest an ordered list inside of an unordered because I need the list items to be continuous between headings.

This is what I have been using, but I don't like that the heading is indented right, despite not being included in the list item.

Tried using "text-indent:-2em" on the heading but that didn't work.
I even tried creating a separate div and putting the negative text indent there, but that didn't work either.

year

item

item

year

item

```

Tried a few websites:
https://www.htmlgoodies.com/tutorials/getting_started/article.php/3479461

答:
So, I think you are on the right path with the -2em to reverse the indent, but it needs to be placed on "margin-left" instead of "text-indent", and either create a class to call it each time you want to use it:

in CSS:

```<code>.unindent{
    margin-left: -2em;
}
</code>```

HTML:

```<code><ol reversed>
    <h3 class="unindent">year</h3>
    <li >item 1</li>
    <li>item 2</li>
    <h3 class="unindent">year</h3>
    <li>item 3</li>
</ol>
</code>```

or individually add it to the lines you want "un-indented":

```<code>    <ol reversed>
        <h3 style="margin-left: -2em" >year</h3>
        <li >item 1</li>
        <li>item 2</li>
        <h3 style="margin-left: -2em" >year</h3>
        <li>item 3</li>
    </ol>
</code>```

There may be other ways, but that's the simplest way I could think of. Good luck!

Body:
I'm trying to have the heading to the left of the list item.

I don't want to nest an ordered list inside of an unordered because I need the list items to be continuous between headings.

This is what I have been using, but I don't like that the heading is indented right, despite not being included in the list item.

Tried using "text-indent:-2em" on the heading but that didn't work.
I even tried creating a separate div and putting the negative text indent there, but that didn't work either.

year

item

item

year

item

Tried a few websites:
https://www.htmlgoodies.com/tutorials/getting_started/article.php/3479461

Body:
So, I think you are on the right path with the -2em to reverse the indent, but it needs to be placed on "margin-left" instead of "text-indent", and either create a class to call it each time you want to use it:

in CSS:

.unindent{
    margin-left: -2em;
}

HTML:

<ol reversed>
    <h3 class="unindent">year</h3>
    <li >item 1</li>
    <li>item 2</li>
    <h3 class="unindent">year</h3>
    <li>item 3</li>
</ol>

or individually add it to the lines you want "un-indented":

    <ol reversed>
        <h3 style="margin-left: -2em" >year</h3>
        <li >item 1</li>
        <li>item 2</li>
        <h3 style="margin-left: -2em" >year</h3>
        <li>item 3</li>
    </ol>

There may be other ways, but that's the simplest way I could think of. Good luck!


问:
Find a range address #2
So because I wasn't specific with my previous question I need your help again.

Basically, I asked if there's a way to find a range between some value/cells, because I was sure that when i will get that range this below will work (so I can select lets say "headers" of the columns with all the data below:

totalRange(Selection, Selection.End(xlDown)).Select

So one of you came up with help and provide code below, which is working just fine, but i'm not sure if I can use it in my case. Because as I said, what im trying to do is to first find a range between  two cells in firstrow and then select all the data below with it. Something like on screenshot below.
I want to find Col7 and Col12 and then select the whole range below.
The problem is this Col7/Col12 range might start from different column in each file.

https://ibb.co/gtuvEb

```<code>Sub RangeBetween()

Dim totalRange As Range
Dim c1 As Long, c2 As Long
Dim r1 As Long, r2 As Long

r1 = 0
r2 = 0

c1 = 1
c2 = 1
With Worksheets("Sheet1") 'Change to your worksheet

    c1 = 1
    Do Until Name = "A"
        Name = Cells(1, c1)
        c1 = c1 + 1
    Loop
    c1 = c1 - 1

    c2 = 1
    Do Until Name = "B"
        Name = Cells(1, c2)
        c2 = c2 + 1
    Loop
    c2 = c2 - 1

    On Error Resume Next
        r1 = Application.WorksheetFunction.Match("A", .Columns(c1), 0)
        r2 = Application.WorksheetFunction.Match("B", .Columns(c2), 0)
    On Error GoTo 0

    If r1 > 0 And r2 > 0 Then
        Set totalRange = .Range(.Cells(r1, c1), .Cells(r2, c2))
        totalRange.Select
    Else
        MsgBox "One or both items not found in range"
    End If
End With

End Sub
</code>```

Thanks for any suggestions.

答:
It seems that you try to look up certain values in the headers and select the ones between those columns. If I understood correctly, your question this can help you.</p>

```<code>Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("your sheet")

Dim header1 As Range, header2 As Range

On Error Resume Next
Set header1 = ws.Rows(1).Find(what:="your header value 1", LookIn:=xlValues,
lookat:=xlWhole)
Set header2 = ws.Rows(1).Find(what:="your header value 2", LookIn:=xlValues,
lookat:=xlWhole)
On Error GoTo 0

If Not header1 Is Nothing And Not header2 Is Nothing Then
    Range(header1,
    header2).EntireColumn.SpecialCells(xlCellTypeConstants).Select
Else:
    MsgBox "Header not fount"
End If
</code>```

Title: Find a range address #2

Body:
So because I wasn't specific with my previous question I need your help again.

Basically, I asked if there's a way to find a range between some value/cells, because I was sure that when i will get that range this below will work (so I can select lets say "headers" of the columns with all the data below:

totalRange(Selection, Selection.End(xlDown)).Select

So one of you came up with help and provide code below, which is working just fine, but i'm not sure if I can use it in my case. Because as I said, what im trying to do is to first find a range between  two cells in firstrow and then select all the data below with it. Something like on screenshot below.
I want to find Col7 and Col12 and then select the whole range below.
The problem is this Col7/Col12 range might start from different column in each file.

https://ibb.co/gtuvEb

Sub RangeBetween()

Dim totalRange As Range
Dim c1 As Long, c2 As Long
Dim r1 As Long, r2 As Long

r1 = 0
r2 = 0

c1 = 1
c2 = 1
With Worksheets("Sheet1") 'Change to your worksheet

    c1 = 1
    Do Until Name = "A"
        Name = Cells(1, c1)
        c1 = c1 + 1
    Loop
    c1 = c1 - 1

    c2 = 1
    Do Until Name = "B"
        Name = Cells(1, c2)
        c2 = c2 + 1
    Loop
    c2 = c2 - 1

    On Error Resume Next
        r1 = Application.WorksheetFunction.Match("A", .Columns(c1), 0)
        r2 = Application.WorksheetFunction.Match("B", .Columns(c2), 0)
    On Error GoTo 0

    If r1 > 0 And r2 > 0 Then
        Set totalRange = .Range(.Cells(r1, c1), .Cells(r2, c2))
        totalRange.Select
    Else
        MsgBox "One or both items not found in range"
    End If
End With

End Sub

Thanks for any suggestions.

Body:
It seems that you try to look up certain values in the headers and select the ones between those columns. If I understood correctly, your question this can help you.

Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("your sheet")

Dim header1 As Range, header2 As Range

On Error Resume Next
Set header1 = ws.Rows(1).Find(what:="your header value 1", LookIn:=xlValues,
lookat:=xlWhole)
Set header2 = ws.Rows(1).Find(what:="your header value 2", LookIn:=xlValues,
lookat:=xlWhole)
On Error GoTo 0

If Not header1 Is Nothing And Not header2 Is Nothing Then
    Range(header1,
    header2).EntireColumn.SpecialCells(xlCellTypeConstants).Select
Else:
    MsgBox "Header not fount"
End If


问:
Object Oriented: 'NoneType' object is not iterable. Why?
This is a recurrent topic, about function that are not iterable because python3 TypeError: 'function' object is not iterable

I do not know when I execute the code, it says

```<code>w,c= PRank.Prank(c,w,X[i,:],Y[i])
</code>```

TypeError: 'NoneType' object is not iterable: Here is the code.

```<code>    import numpy as np

class PRank:

  def predict(X,w,c):
    rank = min(np.where(np.dot(X,w)-c<0)[0])
    return(rank)

  def Prank (c,w,x_t,y):

    l_t=np.zeros(len(c)-1)
    a_t=np.zeros(len(c)-1)
    y_t =min(np.where((np.dot(w,x_t)-c) < 0)[0])

    if y_t != y:
        for r in range(len(c)-1):
            if (y <= r):
                    l_t[r] = -1
            else:
                    l_t[r] = 1
        for r in range(len(c)-1):
            if (((np.dot(w,x_t)-c[r])*l_t[r]) <= 0):
                a_t[r] = l_t[r]
            else:
                a_t[r] = 0

            w = w + sum(a_t)*x_t
            c_ = np.delete(c,len(c)-1)
            c_ = c_ - a_t
            c = np.append(c_,np.inf)

        else:
            w = w
            c = c

   def modelPRank(X,Y,maxrank=5,epsilon=0.02):

      N=np.shape(X)[0]
      feat=np.shape(X)[1]
      c=np.sort(np.random.uniform(size=(maxrank+1,1)),axis=0)
      c[0]=-np.inf
      c[-1]=np.inf
      w=np.zeros(feat)
      ypred=np.zeros(N)
      MSE=1
      j=0
      while MSE > epsilon:
            for i in range(np.shape(X)[0]):
                   w,c= PRank.Prank(c,w,X[i,:],Y[i])
            for i in range(np.shape(X)[0]):
               ypred[i]=min(np.where(np. dot(X[i,:],w)-c<0)[0])
            MSE=np.nanmean((ypred-Y)**2)
            print(MSE)
            j=j+1
      return[MSE,w,ypred,c]
X=np.random.uniform(1,5,(5000,2))

Wini=[0.35,0.65]
Y=np.round(np.dot(X,Wini))
PRank.modelPRank(X,Y)
</code>```

If I do not use class, then the code works well. I do not know why it says that Prank is not iterable and how I can I fix it.

答:
You are telling Python to unpack the return value of the .Prank(...) call into two variables, w and c:

```<code>w,c= PRank.Prank(c,w,X[i,:],Y[i])
</code>```

For Python to do that, whatever is produced on the right-hand side must be an iterable (like a list or a tuple or a string), and each element from that iterable is then used to assign values to your two names.

Your function call returns None, which is not an iterable; it can't be used to assign separate values to two different names.

Add a return statement at the end of the function to return two values in a tuple:

```<code>return w, c
</code>```

This has nothing to do with using classes. You are not using your class correctly, you didn't create an instance, for example. All you did was move a function into a class object.

Body:
This is a recurrent topic, about function that are not iterable because python3 TypeError: 'function' object is not iterable

I do not know when I execute the code, it says

w,c= PRank.Prank(c,w,X[i,:],Y[i])

TypeError: 'NoneType' object is not iterable: Here is the code.

    import numpy as np

class PRank:

  def predict(X,w,c):
    rank = min(np.where(np.dot(X,w)-c<0)[0])
    return(rank)

  def Prank (c,w,x_t,y):

    l_t=np.zeros(len(c)-1)
    a_t=np.zeros(len(c)-1)
    y_t =min(np.where((np.dot(w,x_t)-c) < 0)[0])

    if y_t != y:
        for r in range(len(c)-1):
            if (y <= r):
                    l_t[r] = -1
            else:
                    l_t[r] = 1
        for r in range(len(c)-1):
            if (((np.dot(w,x_t)-c[r])*l_t[r]) <= 0):
                a_t[r] = l_t[r]
            else:
                a_t[r] = 0

            w = w + sum(a_t)*x_t
            c_ = np.delete(c,len(c)-1)
            c_ = c_ - a_t
            c = np.append(c_,np.inf)

        else:
            w = w
            c = c

   def modelPRank(X,Y,maxrank=5,epsilon=0.02):

      N=np.shape(X)[0]
      feat=np.shape(X)[1]
      c=np.sort(np.random.uniform(size=(maxrank+1,1)),axis=0)
      c[0]=-np.inf
      c[-1]=np.inf
      w=np.zeros(feat)
      ypred=np.zeros(N)
      MSE=1
      j=0
      while MSE > epsilon:
            for i in range(np.shape(X)[0]):
                   w,c= PRank.Prank(c,w,X[i,:],Y[i])
            for i in range(np.shape(X)[0]):
               ypred[i]=min(np.where(np. dot(X[i,:],w)-c<0)[0])
            MSE=np.nanmean((ypred-Y)**2)
            print(MSE)
            j=j+1
      return[MSE,w,ypred,c]
X=np.random.uniform(1,5,(5000,2))

Wini=[0.35,0.65]
Y=np.round(np.dot(X,Wini))
PRank.modelPRank(X,Y)

If I do not use class, then the code works well. I do not know why it says that Prank is not iterable and how I can I fix it.

Body:
You are telling Python to unpack the return value of the .Prank(...) call into two variables, w and c:

w,c= PRank.Prank(c,w,X[i,:],Y[i])

For Python to do that, whatever is produced on the right-hand side must be an iterable (like a list or a tuple or a string), and each element from that iterable is then used to assign values to your two names.

Your function call returns None, which is not an iterable; it can't be used to assign separate values to two different names.

Add a return statement at the end of the function to return two values in a tuple:

return w, c

This has nothing to do with using classes. You are not using your class correctly, you didn't create an instance, for example. All you did was move a function into a class object.


问:
Turning a continuous variable into categorical in Spark
I am trying to turn some continuous variables into categorical variables in order to apply some ML algorithms to them and I want to make categories like from 6:00  to 12:00 --> "Morning" or dates in a format like ddMM to "Summer" or whatever.
These variables are already casted to integers. Like the recode function in R, I think.

```<code>+----------+
|CRSDepTime|
+----------+
|       745|
|      1053|
|      1915|
|      1755|
|       832|
|       630|
|       820|
|       945|
|      1245|
|      1645|
|       620|
|      1125|
|      2045|
|      1340|
|      1540|
|       730|
|      1145|
|       525|
|       630|
|      1520|
+----------+
</code>```

I solved this issue with this sentence!!

```<code>df = df.withColumn("Season", when(df("Month") >= 12 and df("Month") <=3, "Fall")
  .when(df("Month") >= 4 and df("Month") <= 6, "Spring")
  .when(df("Month") >= 7 and df("Month") <= 9, "Summer").otherwise("Autumm"))
</code>```

Body:
I am trying to turn some continuous variables into categorical variables in order to apply some ML algorithms to them and I want to make categories like from 6:00  to 12:00 --> "Morning" or dates in a format like ddMM to "Summer" or whatever.
These variables are already casted to integers. Like the recode function in R, I think.

+----------+
|CRSDepTime|
+----------+
|       745|
|      1053|
|      1915|
|      1755|
|       832|
|       630|
|       820|
|       945|
|      1245|
|      1645|
|       620|
|      1125|
|      2045|
|      1340|
|      1540|
|       730|
|      1145|
|       525|
|       630|
|      1520|
+----------+

I solved this issue with this sentence!!

df = df.withColumn("Season", when(df("Month") >= 12 and df("Month") <=3, "Fall")
  .when(df("Month") >= 4 and df("Month") <= 6, "Spring")
  .when(df("Month") >= 7 and df("Month") <= 9, "Summer").otherwise("Autumm"))

Body:
There are two Transformers which can be used to convert continuous variables to categorical ones:

Bucketizer

QuantileDiscretizer

Bucketizer takes splits so it can be used here:

import org.apache.spark.ml.feature._

val df = Seq(
  745, 1053, 1915, 1755, 832, 630, 820, 945,
  1245, 1645, 620, 1125, 2045, 1340, 1540, 730,
  1145, 525, 630, 1520
).toDF("CRSDepTime")

val bucketizer = new Bucketizer()
  .setInputCol("CRSDepTime")
  .setOutputCol("bucketedFeatures")
  .setSplits(Array(0, 600, 1200, 1800, 2400))

// +----------+----------------+
// |CRSDepTime|bucketedFeatures|
// +----------+----------------+
// |       745|             1.0|
// |      1053|             1.0|
// |      1915|             3.0|
// |      1755|             2.0|
// |       832|             1.0|
// |       630|             1.0|
// |       820|             1.0|
// |       945|             1.0|
// |      1245|             2.0|
// |      1645|             2.0|
// +----------+----------------+
// only showing top 10 rows

Typically it will be coupled with OneHotEncoder:

import org.apache.spark.ml.Pipeline

val encoder = new OneHotEncoder()
  .setInputCol(bucketizer.getOutputCol)
  .setOutputCol("CRSDepTimeencoded")

val pipeline = new Pipeline().setStages(Array(bucketizer, encoder))

pipeline.fit(df).transform(df).show(10)

// +----------+----------------+-----------------+
// |CRSDepTime|bucketedFeatures|CRSDepTimeencoded|
// +----------+----------------+-----------------+
// |       745|             1.0|    (3,[1],[1.0])|
// |      1053|             1.0|    (3,[1],[1.0])|
// |      1915|             3.0|        (3,[],[])|
// |      1755|             2.0|    (3,[2],[1.0])|
// |       832|             1.0|    (3,[1],[1.0])|
// |       630|             1.0|    (3,[1],[1.0])|
// |       820|             1.0|    (3,[1],[1.0])|
// |       945|             1.0|    (3,[1],[1.0])|
// |      1245|             2.0|    (3,[2],[1.0])|
// |      1645|             2.0|    (3,[2],[1.0])|
// +----------+----------------+-----------------+
// only showing top 10 rows


问:
Export mysql query to amazon s3 bucket
Based on the accepted answer here, I am able to export the results of mysql query to a csv file on my Amazon EC2 instance using the following:

```<code>mysql -user -pass -e "SELECT * FROM table" > /data.csv
</code>```

However, as the file exported is large, I want to export an Amazon s3-bucket (s3:\\mybucket) which is accessible from my EC2 instance

I tried:

```<code>mysql -user -pass -e "SELECT * FROM table" > s3:\\mybucket\data.csv
</code>```

But it doesn't export the file.

答:
If you want to use the mysql command line program, then you have two choices:

Increase the size of your instance's storage so that the file can be created. Then copy the file to S3

Create a separate program or script that reads from Standard Input and writes to S3.

Another solution would be to create a simple program that processes your SELECT and directly writes to S3. There are lots of examples of this on the Internet in Python, Java, etc.

Title: Export mysql query to amazon s3 bucket

Body:
Based on the accepted answer here, I am able to export the results of mysql query to a csv file on my Amazon EC2 instance using the following:

mysql -user -pass -e "SELECT * FROM table" > /data.csv

However, as the file exported is large, I want to export an Amazon s3-bucket (s3:\\mybucket) which is accessible from my EC2 instance

I tried:

mysql -user -pass -e "SELECT * FROM table" > s3:\\mybucket\data.csv

But it doesn't export the file.


问:
Install4j - animation during installation
Is there any way, how to show some animation (video or animated gif) on installation screen during downloading (in case od downloadable components) and during installing files in Install4j?</p>

答: The "Installation" screen is a form screen, so you can add a form component that shows an animation. As of 7.0, install4j does not have a form component that shows videos, but the "Label" form component can show an animated GIF.</p>


问:
db:seed laravel 5.5.x not increment sequence id of postgres
I am using laravel 5.5.20 and PostgreSQL 9.5.10. When I run php artisan db:seed then data inserted into the table but not increase the sequence id or number. Then when I try to insert the data into the table from my application then it creates an error. Autoincrement primary id have already existed.

How I can increment the sequence when inserting data by running php artisan db:seed.

答:
Just ran into this also.  Go into your seeds and check and see if you have assigned a value to the incrementing column.  If so, remove it.

Seems like when you explicitly assign a value to the incrementing column that it does not register this in the next sequence.  By leaving it out, everything works properly.


问:
Issue with Java JRE and Eclipse when Installing Talend Data Integration Studio
I am trying to install Talend data integration software, and it fails. It writes the following issue to the log (and about 500 KB more just like it):

Update: I also posted [the full error log] (https://pastebin.com/g06Guuk9) to Pastebin.

```<code>!SESSION 2017-10-19 06:41:34.981 -----------------------------------------------
eclipse.buildId=unknown
java.version=9.0.1
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US
Command-line arguments:  -os win32 -ws win32 -arch x86_64

!ENTRY org.eclipse.jdt.launching.macosx 4 0 2017-10-19 06:42:04.725
!MESSAGE FrameworkEvent ERROR
!STACK 0
org.osgi.framework.BundleException: Could not resolve module: org.eclipse.jdt.launching.macosx [326]
  Unresolved requirement: Require-Capability: eclipse.platform; filter:="(osgi.os=macosx)"

    at org.eclipse.osgi.container.Module.start(Module.java:434)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1582)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1561)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1533)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1476)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)
</code>```

I am on a 64-bit machine, and have the 64-bit JRE installed I believe. Environment variable JRE_HOME and PATH have the correct paths to the JRE.

```<code>JRE_HOME = C:\Program Files\Java\jre-9.0.1
</code>```

I know that log has MacOS X stuff in it ... but I am clicking the correct .exe:

I can’t figure out what to try next based on the log. Any ideas?

答:
The problem is you are using Java 9 but the current version of Talend Studio only supports Java 8.
See here for details: https://help.talend.com/reader/TCzKRnmOy7N82kok2_ix6A/QiBwsPB_OFS64lEACkDWEQ</p>

Body:
I am trying to install Talend data integration software, and it fails. It writes the following issue to the log (and about 500 KB more just like it):

Update: I also posted [the full error log] (https://pastebin.com/g06Guuk9) to Pastebin.

!SESSION 2017-10-19 06:41:34.981 -----------------------------------------------
eclipse.buildId=unknown
java.version=9.0.1
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US
Command-line arguments:  -os win32 -ws win32 -arch x86_64

!ENTRY org.eclipse.jdt.launching.macosx 4 0 2017-10-19 06:42:04.725
!MESSAGE FrameworkEvent ERROR
!STACK 0
org.osgi.framework.BundleException: Could not resolve module: org.eclipse.jdt.launching.macosx [326]
  Unresolved requirement: Require-Capability: eclipse.platform; filter:="(osgi.os=macosx)"

    at org.eclipse.osgi.container.Module.start(Module.java:434)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1582)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1561)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1533)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1476)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)

I am on a 64-bit machine, and have the 64-bit JRE installed I believe. Environment variable JRE_HOME and PATH have the correct paths to the JRE.

JRE_HOME = C:\Program Files\Java\jre-9.0.1

I know that log has MacOS X stuff in it ... but I am clicking the correct .exe:

I can’t figure out what to try next based on the log. Any ideas?


问:
MongoDB: Query elements of an array of objects nested in a collection property
I have a Mongo DB database set up with the following collection, Races:

```<code>[
    {
        "_id": "5a24b47f8b8498252a0a0ef9",
        "year": 2017,
        "runners": [
            {
                "Place": "1",
                "Div/Tot": "1/126",
                "FName": "XXXX",
                "LName": "XXXX",
                "Num": "XXXX",
                "S": "M",
                "Ag": "25",
                "City": "XXXX",
                "St": "XX",
                "Gun-Time": "32:15.2",
                "Net-Time": "32:14.91",
                "Pace": "5:13"
            },
            {
                "Place": "2",
                "Div/Tot": "1/138",
                "FName": "XXXX",
                "LName": "XXXX",
                "Num": "XXXX",
                "S": "M",
                "Ag": "34",
                "City": "XXXX",
                "St": "XXXX",
                "Gun-Time": "MD",
                "Net-Time": "32:19.0",
                "Pace": "32:18.78"
            },
        ....
</code>```

I am trying to query by year to bring up the right element of the collection, and then query within the element's "runners" array based on input criteria.  So far I have not been able to direct the query into this array.  The goal is to derive members of an array of objects held within an element of a collection.

I looked at the syntax for mongo DB's $in and $all operators but I have not been able to construct a query that matches against the properties of the objects in the array.

I am using Node and this is the end-point I have tried to adapt;

```<code>router.route( '/race/:year' )
  .get( ( req, res ) => {
      console.log( 'query', req.query, ' params ', req.params );
      Race.find( { year: req.params.year }, {runners: {$elemMatch: req.query } } )
      .then( race => {
          return res.json( race );
      } )
      .catch( () => res.status( 500 ).send( 'endpoint error..........' ) );
});
</code>```

The problem with this query is that it only returns the first array element that matches req.query, not all of the values that do.

Is there a concise way to construct a query into the objects of the array that returns all of the matches?  Thank you for your time.

答:
Thank you Alex for the suggestion to try aggregation or the filters.  I could not get the filter to work, based on what I read from the docs but I was able to get it working with this:

```<code>router.route( '/race/:year' )
  .get( ( req, res ) => {
      console.log( 'query', req.query, ' params ', req.params );

      Race.find( { year: req.params.year } )
     .then( race => {
        let results = [];
        const runners = race[ 0 ].runners;
        const searchObj = req.query;
        const searchKeys = Object.keys( searchObj );

        for ( let i = 0; i < runners.length; i++ ){
            searchKeys.forEach( function( searchTerm ){
                if ( runners[ i ][ `${ searchTerm }` ] === searchObj[ `${ searchTerm }` ] ){
                    results.push( runners[ i ] );
                }
            }
        ) }
        return res.json( results );
      })
      .catch( () => res.status( 500 ).send( 'endpoint error..........' ) );
});
</code>```

This works for a single search term, but if the requirement were runners who had more than one characteristic this would return runners with any of the characteristics, not the set of runners that has all of them. It seems that MongoDB should have something to make this less painful...

If anyone has any suggestions I would appreciate the help in refactoring.  Thank you.

Body:
I have a Mongo DB database set up with the following collection, Races:

[
    {
        "_id": "5a24b47f8b8498252a0a0ef9",
        "year": 2017,
        "runners": [
            {
                "Place": "1",
                "Div/Tot": "1/126",
                "FName": "XXXX",
                "LName": "XXXX",
                "Num": "XXXX",
                "S": "M",
                "Ag": "25",
                "City": "XXXX",
                "St": "XX",
                "Gun-Time": "32:15.2",
                "Net-Time": "32:14.91",
                "Pace": "5:13"
            },
            {
                "Place": "2",
                "Div/Tot": "1/138",
                "FName": "XXXX",
                "LName": "XXXX",
                "Num": "XXXX",
                "S": "M",
                "Ag": "34",
                "City": "XXXX",
                "St": "XXXX",
                "Gun-Time": "MD",
                "Net-Time": "32:19.0",
                "Pace": "32:18.78"
            },
        ....

I am trying to query by year to bring up the right element of the collection, and then query within the element's "runners" array based on input criteria.  So far I have not been able to direct the query into this array.  The goal is to derive members of an array of objects held within an element of a collection.

I looked at the syntax for mongo DB's $in and $all operators but I have not been able to construct a query that matches against the properties of the objects in the array.

I am using Node and this is the end-point I have tried to adapt;

router.route( '/race/:year' )
  .get( ( req, res ) => {
      console.log( 'query', req.query, ' params ', req.params );
      Race.find( { year: req.params.year }, {runners: {$elemMatch: req.query } } )
      .then( race => {
          return res.json( race );
      } )
      .catch( () => res.status( 500 ).send( 'endpoint error..........' ) );
});

The problem with this query is that it only returns the first array element that matches req.query, not all of the values that do.

Is there a concise way to construct a query into the objects of the array that returns all of the matches?  Thank you for your time.

Body:
Thank you Alex for the suggestion to try aggregation or the filters.  I could not get the filter to work, based on what I read from the docs but I was able to get it working with this:

router.route( '/race/:year' )
  .get( ( req, res ) => {
      console.log( 'query', req.query, ' params ', req.params );

      Race.find( { year: req.params.year } )
     .then( race => {
        let results = [];
        const runners = race[ 0 ].runners;
        const searchObj = req.query;
        const searchKeys = Object.keys( searchObj );

        for ( let i = 0; i < runners.length; i++ ){
            searchKeys.forEach( function( searchTerm ){
                if ( runners[ i ][ `${ searchTerm }` ] === searchObj[ `${ searchTerm }` ] ){
                    results.push( runners[ i ] );
                }
            }
        ) }
        return res.json( results );
      })
      .catch( () => res.status( 500 ).send( 'endpoint error..........' ) );
});

This works for a single search term, but if the requirement were runners who had more than one characteristic this would return runners with any of the characteristics, not the set of runners that has all of them. It seems that MongoDB should have something to make this less painful...

If anyone has any suggestions I would appreciate the help in refactoring.  Thank you.


问:
Python Script Read TXT and create new
I have this script for creating 'acl' to add all IP's of server to squid config

```<code>file = open("ip.txt", "r")
ip_list = [line for line in file]

for acl, tcp in zip(ip_list[::2], ip_list[1::2]):
    print "acl ip" + str(ip_list.index(acl) + 1) + " myip " + acl.strip()
    print  "tcp_outgoing_address " + tcp.strip() + " ip" + str(ip_list.index(acl) + 1)
</code>```

My problem is that when script read IP from ip.txt I need to enter 2 times the same IP cause I need the same IP 2 times in my final paste.

My friend told me to create double loop but I have no idea how to do it.

ip.txt looks like this

```<code>1.1.1.1
2.2.2.2
3.3.3.3
</code>```

Final paste should looked like this

```<code>acl ip1 myip 1.1.1.1
tcp_outgoing_address 1.1.1.1 ip1
acl ip2 myip 2.2.2.2
tcp_outgoing_address 2.2.2.2 ip2
acl ip3 myip 3.3.3.3
tcp_outgoing_address 3.3.3.3 ip3
acl ip4 myip 4.4.4.4
tcp_outgoing_address 4.4.4.4 ip4
</code>```

答:
There is a simpler way to do that, without the overhead of zip() and index():

```<code>file = open("ip.txt", "r")

for index, line in enumerate(file):
    print("acl ip" + str(index + 1) + " myip " + line.strip())
    print("tcp_outgoing_address " + line.strip() + " ip" + str(index + 1))
</code>```

even nicer (i think):

```<code>file = open("ip.txt", "r")

tpl = """acl ip{index} myip {ip}
tcp_outgoing_address {ip} ip {index}"""

for index, line in enumerate(file):
    print(tpl.format(index=index, ip=line.strip()))
</code>```

and the output will be the same that you request:

acl ip1 myip 1.1.1.1

  tcp_outgoing_address 1.1.1.1 ip1

  acl ip2 myip 2.2.2.2

  tcp_outgoing_address 2.2.2.2 ip2

  acl ip3 myip 3.3.3.3

  tcp_outgoing_address 3.3.3.3 ip3

Title: Python Script Read TXT and create new

Body:
I have this script for creating 'acl' to add all IP's of server to squid config

file = open("ip.txt", "r")
ip_list = [line for line in file]

for acl, tcp in zip(ip_list[::2], ip_list[1::2]):
    print "acl ip" + str(ip_list.index(acl) + 1) + " myip " + acl.strip()
    print  "tcp_outgoing_address " + tcp.strip() + " ip" + str(ip_list.index(acl) + 1)

My problem is that when script read IP from ip.txt I need to enter 2 times the same IP cause I need the same IP 2 times in my final paste.

My friend told me to create double loop but I have no idea how to do it.

ip.txt looks like this

1.1.1.1
2.2.2.2
3.3.3.3

Final paste should looked like this

acl ip1 myip 1.1.1.1
tcp_outgoing_address 1.1.1.1 ip1
acl ip2 myip 2.2.2.2
tcp_outgoing_address 2.2.2.2 ip2
acl ip3 myip 3.3.3.3
tcp_outgoing_address 3.3.3.3 ip3
acl ip4 myip 4.4.4.4
tcp_outgoing_address 4.4.4.4 ip4

Body:
There is a simpler way to do that, without the overhead of zip() and index():

file = open("ip.txt", "r")

for index, line in enumerate(file):
    print("acl ip" + str(index + 1) + " myip " + line.strip())
    print("tcp_outgoing_address " + line.strip() + " ip" + str(index + 1))

even nicer (i think):

file = open("ip.txt", "r")

tpl = """acl ip{index} myip {ip}
tcp_outgoing_address {ip} ip {index}"""

for index, line in enumerate(file):
    print(tpl.format(index=index, ip=line.strip()))

and the output will be the same that you request:

acl ip1 myip 1.1.1.1

  tcp_outgoing_address 1.1.1.1 ip1

  acl ip2 myip 2.2.2.2

  tcp_outgoing_address 2.2.2.2 ip2

  acl ip3 myip 3.3.3.3

  tcp_outgoing_address 3.3.3.3 ip3


问:
GWT client request not getting posted to server
I have a small GWT application that gets the contents for a FlexTable from a database based on some string parameters. It is triggered by the click of a button on the GUI.

Everything works as expected when the app is initially started. But, upon multiple clicks (requests), the app stops working and my requests from the client no longer reaches the sever code. I am running on hosted mode and have breakpoints in my code. I can trace the code on client side; but after it submits the request to server using my service instance, it never reaches the server; nor the onSuccess() gets called.

Can someone please help me debug this? Where should i start to see traces of what is happening?

答:
Turns out that it wasnt anything about GWT RPC. The request was indeed getting submitted to server but because of a db resource contention, Eclipse wasn't showing me any trace of the code on server side. I switched on debug loggings in the code and everything because real clear.

Thanks!
pjames


问:
'System.Data.SqlClient.SqlException' in System.Data.dll ("Incorrect syntax near ')'.")?
Hey this is my code and this is the error I get:

Exception thrown: 'System.Data.SqlClient.SqlException' in
  System.Data.dll ("Incorrect syntax near ')'.")

```<code>void addMember()
{
    try
    {
       //con.Open();
        String EmpID = txtEmpID.Text.ToString().Trim();
        String EmployeeName = txtEmpID.Text.ToString().Trim();
        String UserName = txtUsername.Text.ToString().Trim();
        String UserType = cmbUserType.GetItemText(cmbUserType.SelectedItem);
        String PassWord = txtPassword.Text.ToString().Trim();
        SqlCommand addUser = new SqlCommand("insert into  userDetails(@empID ,@employeeName ,@userName , @userType, @password)", con);
        addUser.Parameters.Add(new SqlParameter("@empID", EmpID));
        addUser.Parameters.Add(new SqlParameter("@employeeName", EmployeeName));
        addUser.Parameters.Add(new SqlParameter("@userName", UserName));
        addUser.Parameters.Add(new SqlParameter("@userType", UserType));
        addUser.Parameters.Add(new SqlParameter("@password", PassWord));

        int x = addUser.ExecuteNonQuery();

        if (x > 0)
        {

            MessageBox.Show("Data Inserted", "User Form", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        //con.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show("" + ex);
    }
</code>```

答:
You have missed the Values keyword:

```<code>SqlCommand addUser = new SqlCommand("insert into userDetails Values(@empID ," +
                                                              ^^^^
                                    "@employeeName ,@userName , @userType, @password)", con);
</code>```

Body:
Hey this is my code and this is the error I get:

Exception thrown: 'System.Data.SqlClient.SqlException' in
  System.Data.dll ("Incorrect syntax near ')'.")

void addMember()
{
    try
    {
       //con.Open();
        String EmpID = txtEmpID.Text.ToString().Trim();
        String EmployeeName = txtEmpID.Text.ToString().Trim();
        String UserName = txtUsername.Text.ToString().Trim();
        String UserType = cmbUserType.GetItemText(cmbUserType.SelectedItem);
        String PassWord = txtPassword.Text.ToString().Trim();
        SqlCommand addUser = new SqlCommand("insert into  userDetails(@empID ,@employeeName ,@userName , @userType, @password)", con);
        addUser.Parameters.Add(new SqlParameter("@empID", EmpID));
        addUser.Parameters.Add(new SqlParameter("@employeeName", EmployeeName));
        addUser.Parameters.Add(new SqlParameter("@userName", UserName));
        addUser.Parameters.Add(new SqlParameter("@userType", UserType));
        addUser.Parameters.Add(new SqlParameter("@password", PassWord));

        int x = addUser.ExecuteNonQuery();

        if (x > 0)
        {

            MessageBox.Show("Data Inserted", "User Form", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        //con.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show("" + ex);
    }

Body:
You have missed the Values keyword:

SqlCommand addUser = new SqlCommand("insert into userDetails Values(@empID ," +
                                                              ^^^^
                                    "@employeeName ,@userName , @userType, @password)", con);


问:
Bitbucket private repository limits for free plan
I'm a university professor teaching a programming class. There will be a group assignment for this class and I'd like to monitor each group's progress, therefore I thought of using GitHub or Bitbucket to host the assignments. Each group will be composed of at most 4 students, and of course I will need to be able to see the repository as well.

Thus there will be a repository containing myself and students A, B, C and D, a second repository containing myself and students E, F, G and H, a third repository containing myself and students I, J, K and L, and so on.

Due to the particulars of this assignment, the repositories must necessarily be private.

I understand GitHub doesn't offer free private repositories, so I've crossed out that option. As for Bitbucket, am I correct in assuming that this doesn't exceed the limits for the free plan? If it does, are there other Git hosting services where I could host these assignments for free?

答:
Bitbucket has an academic plan that should suit your needs. From https://bitbucket.org/product/pricing?tab=host-in-the-cloud :

Do you offer free community or academic subscriptions?

Yes! Community or academic subscriptions include unlimited private repositories for unlimited contributors which also includes 5 GB file storage for LFS and 500 build minutes for Pipelines to help you get started. You share build minutes and storage with all users on your team or personal account. Fees will apply for additional build minutes and file storage.

How can I sign up for a free academic subscription?

When you sign up with your academic email address, we will automatically convert your account to an unlimited academic plan. If your account doesn't automatically get converted, you can apply to have your institution added.


问:
Orbeon forms - validation trigger on keyup
We are using Orbeon forms version 2017.1.1, and we are trying to trigger validation of the current field in the form on each keyup JS event. We have tried using ev:event="xxforms-value-changed" but it only fires after the field has "blurred". Is there a way to trigger the validation on keyup event using XML?</p>

答: You can get the value to be updated as users type, without waiting for users to press enter, or for the field to loose the focus, by adding the incremental="true" attribute on your <xf:input>. This isn't the default as it creates more chatter between the browser and the server, as well as more load on the server, and often isn't necessary.


问:
Elm updating model with http
I am trying to update my bitcoin price field in my List Token Model in my update function. This is my code I cannot seem to get it to only update the price field. Do I need to access the list elements seeing as my model is list? Is this possible to do using record syntax in elm?

```<code>import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Bass exposing (style, center, h1)
import Http
import Json.Decode as Decode

main =
  Html.program
    { init = init
    , view = view
    , update = update
    , subscriptions = subscriptions
    }

------------- MODEL

type alias Model =
  { tokens : List Token
  }

init : (Model, Cmd Msg)
init =
  (initialModel , Cmd.none)

initialModel : Model
initialModel =
  { tokens = [Token "Bitcoin" "150" "11000.00"]
  }

type alias Token =
  { name : String
  , holdings : String
  , price : String
}

------------- UPDATE

type Msg
  = FetchDatabasePrice | FetchLivePrice (Result Http.Error String)

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case msg of
    FetchDatabasePrice ->
      (model, getPrice )
    FetchLivePrice (Ok newPrice) ->
      ( { model | price = newPrice }, Cmd.none )
    FetchLivePrice (Err _) ->
      (model,Cmd.none)

getPrice : Cmd Msg
getPrice  =
  let
    url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/"
    request = Http.get url decodedUrl
  in
    Http.send FetchLivePrice request

decodedUrl : Decode.Decoder String
decodedUrl = Decode.at ["price_usd"] Decode.string
------------- SUBSCRIPTIONS

subscriptions : Model -> Sub Msg
subscriptions model =
  Sub.none

------------- VIEW

view : Model -> Html Msg
view model =
  div []
    [nav
    , div [] [list model.tokens]
    , div [] [ button [onClick (FetchDatabasePrice) ] [text "Fetch Price"] ]
    ]

------BROKEN INTO PIECES---------

nav : Html Msg
nav = div [Bass.style
            [center
            , Bass.h1
            , [("background-color", "black")
            , ("color", "white")
              ]
            ]
           ]
           [ div [] [text "Crypto Nutshell"]]

list : List Token -> Html Msg
list tokens =
  div [Bass.style
        [Bass.left_align
        ]
      ]
    [div [ class "p1"]
       [ table []
          [ thead []
             [ tr []
                [ th [] [text "Name"]
                , th [] [text "Holdings"]
                , th [] [text "Price"]
                , th [] [text "Actions"]
                ]
             ]
             , tbody [] (List.map tokenRow tokens)
          ]
        ]
      ]

tokenRow : Token -> Html Msg
tokenRow token =
  tr []
      [ td [] [ text token.name ]
      , td [] [ text token.holdings ]
      , td [] [ text token.price ]
      ]
</code>```

This is my error:

```<code>-- TYPE MISMATCH ------------------------------------------------------ test.elm

The definition of `update` does not match its type annotation.

50| update : Msg -> Model -> (Model, Cmd Msg)
51| update msg model =
52|>  case msg of
53|>    FetchDatabasePrice ->
54|>      (model, getPrice )
55|>    FetchLivePrice (Ok newPrice) ->
56|>      ( { model | price = newPrice }, Cmd.none )
57|>    FetchLivePrice (Err _) ->
58|>      (model,Cmd.none)

The type annotation for `update` says it always returns:

    ( Model, Cmd Msg )

But the returned value (shown above) is a:

    ( { b | price : String }, Cmd Msg )

Hint: The record fields do not match up. One has tokens. The other has price.

-- TYPE MISMATCH ------------------------------------------------------ test.elm

`model` is being used in an unexpected way.

56|       ( { model | price = newPrice }, Cmd.none )
              ^^^^^
Based on its definition, `model` has this type:

    Model

But you are trying to use it as:

    { b | price : a }

Hint: The record fields do not match up. One has tokens. The other has price.
</code>```

答:
The type errors are fundamentally telling you your issue - you are trying to work on a Token, but you don't have one - you have a Model.

How do we get from one to the other? Well. We start with a model, and we can do model.tokens to get a List Token. We then want to modify that list to contain the new tokens, updated. The normal way to do this is with List.map. This operates on each Token and gives us the updated list. Following these steps:

```<code>FetchLivePrice (Ok newPrice) ->
  let
    updatePrice = (\token -> { token | price = newPrice })
    updated = List.map updatePrice model.tokens
  in
    ({ model | tokens = updated }, Cmd.none )
</code>```

Now, the solution I've given is a simple one that will fall apart when you have multiple different tokens (they will all get changed at the same time). As you only have one right now, the same thing could be achieved just by simplifying the model to take only a single token, not a list.

You will need to start identifying which token you are getting the price for so you can update the right one, if you want to be able to use the ability to have multiple tokens.

In reality, you probably want this to end up looking something like:

```<code>FetchLivePrice tokenId (Ok newPrice) ->
    ({ model | tokens = tokenUpdatePrice tokenId newPrice model.tokens, Cmd.none)
</code>```

Where tokenUpdatePrice is a function that manipulates your list (or other data structure - a dictionary might be appropriate, although you might need to store a separate order for presentation) to update the appropriate records. tokenId will be something used to identify the token.

Title: Elm updating model with http

Body:
I am trying to update my bitcoin price field in my List Token Model in my update function. This is my code I cannot seem to get it to only update the price field. Do I need to access the list elements seeing as my model is list? Is this possible to do using record syntax in elm?

import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Bass exposing (style, center, h1)
import Http
import Json.Decode as Decode

main =
  Html.program
    { init = init
    , view = view
    , update = update
    , subscriptions = subscriptions
    }

------------- MODEL

type alias Model =
  { tokens : List Token
  }

init : (Model, Cmd Msg)
init =
  (initialModel , Cmd.none)

initialModel : Model
initialModel =
  { tokens = [Token "Bitcoin" "150" "11000.00"]
  }

type alias Token =
  { name : String
  , holdings : String
  , price : String
}

------------- UPDATE

type Msg
  = FetchDatabasePrice | FetchLivePrice (Result Http.Error String)

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case msg of
    FetchDatabasePrice ->
      (model, getPrice )
    FetchLivePrice (Ok newPrice) ->
      ( { model | price = newPrice }, Cmd.none )
    FetchLivePrice (Err _) ->
      (model,Cmd.none)

getPrice : Cmd Msg
getPrice  =
  let
    url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/"
    request = Http.get url decodedUrl
  in
    Http.send FetchLivePrice request

decodedUrl : Decode.Decoder String
decodedUrl = Decode.at ["price_usd"] Decode.string
------------- SUBSCRIPTIONS

subscriptions : Model -> Sub Msg
subscriptions model =
  Sub.none

------------- VIEW

view : Model -> Html Msg
view model =
  div []
    [nav
    , div [] [list model.tokens]
    , div [] [ button [onClick (FetchDatabasePrice) ] [text "Fetch Price"] ]
    ]

------BROKEN INTO PIECES---------

nav : Html Msg
nav = div [Bass.style
            [center
            , Bass.h1
            , [("background-color", "black")
            , ("color", "white")
              ]
            ]
           ]
           [ div [] [text "Crypto Nutshell"]]

list : List Token -> Html Msg
list tokens =
  div [Bass.style
        [Bass.left_align
        ]
      ]
    [div [ class "p1"]
       [ table []
          [ thead []
             [ tr []
                [ th [] [text "Name"]
                , th [] [text "Holdings"]
                , th [] [text "Price"]
                , th [] [text "Actions"]
                ]
             ]
             , tbody [] (List.map tokenRow tokens)
          ]
        ]
      ]

tokenRow : Token -> Html Msg
tokenRow token =
  tr []
      [ td [] [ text token.name ]
      , td [] [ text token.holdings ]
      , td [] [ text token.price ]
      ]

This is my error:

-- TYPE MISMATCH ------------------------------------------------------ test.elm

The definition of `update` does not match its type annotation.

50| update : Msg -> Model -> (Model, Cmd Msg)
51| update msg model =
52|>  case msg of
53|>    FetchDatabasePrice ->
54|>      (model, getPrice )
55|>    FetchLivePrice (Ok newPrice) ->
56|>      ( { model | price = newPrice }, Cmd.none )
57|>    FetchLivePrice (Err _) ->
58|>      (model,Cmd.none)

The type annotation for `update` says it always returns:

    ( Model, Cmd Msg )

But the returned value (shown above) is a:

    ( { b | price : String }, Cmd Msg )

Hint: The record fields do not match up. One has tokens. The other has price.

-- TYPE MISMATCH ------------------------------------------------------ test.elm

`model` is being used in an unexpected way.

56|       ( { model | price = newPrice }, Cmd.none )
              ^^^^^
Based on its definition, `model` has this type:

    Model

But you are trying to use it as:

    { b | price : a }

Hint: The record fields do not match up. One has tokens. The other has price.

Body:
The type errors are fundamentally telling you your issue - you are trying to work on a Token, but you don't have one - you have a Model.

How do we get from one to the other? Well. We start with a model, and we can do model.tokens to get a List Token. We then want to modify that list to contain the new tokens, updated. The normal way to do this is with List.map. This operates on each Token and gives us the updated list. Following these steps:

FetchLivePrice (Ok newPrice) ->
  let
    updatePrice = (\token -> { token | price = newPrice })
    updated = List.map updatePrice model.tokens
  in
    ({ model | tokens = updated }, Cmd.none )

Now, the solution I've given is a simple one that will fall apart when you have multiple different tokens (they will all get changed at the same time). As you only have one right now, the same thing could be achieved just by simplifying the model to take only a single token, not a list.

You will need to start identifying which token you are getting the price for so you can update the right one, if you want to be able to use the ability to have multiple tokens.

In reality, you probably want this to end up looking something like:

FetchLivePrice tokenId (Ok newPrice) ->
    ({ model | tokens = tokenUpdatePrice tokenId newPrice model.tokens, Cmd.none)

Where tokenUpdatePrice is a function that manipulates your list (or other data structure - a dictionary might be appropriate, although you might need to store a separate order for presentation) to update the appropriate records. tokenId will be something used to identify the token.


问:
What is &'a in Rust Language
I read here that

A shared reference type is written &type, or &'a type when you need to specify an explicit lifetime.

Understood & is for shared reference but did not understand what is the difference between type and 'a in Rust language

In another location I read this code:

```<code>#[derive(Debug)]
struct Person<'a> {
    name: &'a str,
    age: u8
}

fn main() {
    let name = "Peter";
    let age = 27;
    let peter = Person { name, age };

    // Pretty print
    println!("{:#?}", peter);
}
</code>```

What does 'a in the struct Person<'a> { } means?
and can I build the same struct using struct Person<'type> { } or struct Person<T> { }?

And what is the meaning of name: &'a str?

And how can I re-code it, if want to avoid using the <'a>

答:
I found this and this and this and this that explains my question.

The 'a reads ‘the lifetime a’. Technically, every reference has some lifetime associated with it, but the compiler lets you elide (i.e. omit, see "Lifetime Elision") them in common cases.

```<code>fn bar<'a>(...)
</code>```

A function can have ‘generic parameters’ between the <>s, of which lifetimes are one kind. The <> is used to declare lifetimes. This says that bar has one lifetime, 'a.

Rust has two main types of strings: &str and String. The &str are called ‘string slices’. A string slice has a fixed size, and cannot be mutated. It is a reference to a sequence of UTF-8 bytes.

```<code>let greeting = "Hello there."; // greeting: &'static str
</code>```

"Hello there." is a string literal and its type is &'static str. A string literal is a string slice that is statically allocated, meaning that it’s saved inside our compiled program, and exists for the entire duration it runs. The greeting binding is a reference to this statically allocated string. Any function expecting a string slice will also accept a string literal.

In the above example

```<code>struct Person<'a> {  }
</code>```

requires to contain <'a> as the name is defined using:

```<code>name: &'a str,
</code>```

which is called by:

```<code>let name = "Peter";
</code>```

If interested to avoid the usage of 'a then the above code can be re-written as:

```<code>#[derive(Debug)]
struct Person {    // instead of: struct Person<'a> {
    name: String,  // instead of: name: &'a str
    age: u8
}

fn main() {
    let name = String::from("Peter");  // instead of: let name = "Peter"; which is &'static str
    let age = 27;
    let peter = Person { name, age };

    // Pretty print
    println!("{:#?}", peter);
}
</code>```

As mentioned by @DimitrisSfounis in the comments, in short, "Why is 'a there?" ---- Because the struct definition ties it to a referenced object (in this case, every struct Person instance is referencing a &str) you want to specificly declare an arbitary lifetime and tie these two things together: You want a struct Person instance to only live as long as its referenced object (hence Person<'a> and name: &'a str) so dangling references after each other's death is avoided.

Title: What is &'a in Rust Language

Body:
I read here that

A shared reference type is written &type, or &'a type when you need to specify an explicit lifetime.

Understood & is for shared reference but did not understand what is the difference between type and 'a in Rust language

In another location I read this code:

#[derive(Debug)]
struct Person<'a> {
    name: &'a str,
    age: u8
}

fn main() {
    let name = "Peter";
    let age = 27;
    let peter = Person { name, age };

    // Pretty print
    println!("{:#?}", peter);
}

What does 'a in the struct Person<'a> { } means?
and can I build the same struct using struct Person<'type> { } or struct Person<T> { }?

And what is the meaning of name: &'a str?

And how can I re-code it, if want to avoid using the <'a>

Body:
I found this and this and this and this that explains my question.

The 'a reads ‘the lifetime a’. Technically, every reference has some lifetime associated with it, but the compiler lets you elide (i.e. omit, see "Lifetime Elision") them in common cases.

fn bar<'a>(...)

A function can have ‘generic parameters’ between the <>s, of which lifetimes are one kind. The <> is used to declare lifetimes. This says that bar has one lifetime, 'a.

Rust has two main types of strings: &str and String. The &str are called ‘string slices’. A string slice has a fixed size, and cannot be mutated. It is a reference to a sequence of UTF-8 bytes.

let greeting = "Hello there."; // greeting: &'static str

"Hello there." is a string literal and its type is &'static str. A string literal is a string slice that is statically allocated, meaning that it’s saved inside our compiled program, and exists for the entire duration it runs. The greeting binding is a reference to this statically allocated string. Any function expecting a string slice will also accept a string literal.

In the above example

struct Person<'a> {  }

requires to contain <'a> as the name is defined using:

name: &'a str,

which is called by:

let name = "Peter";

If interested to avoid the usage of 'a then the above code can be re-written as:

#[derive(Debug)]
struct Person {    // instead of: struct Person<'a> {
    name: String,  // instead of: name: &'a str
    age: u8
}

fn main() {
    let name = String::from("Peter");  // instead of: let name = "Peter"; which is &'static str
    let age = 27;
    let peter = Person { name, age };

    // Pretty print
    println!("{:#?}", peter);
}

As mentioned by @DimitrisSfounis in the comments, in short, "Why is 'a there?" ---- Because the struct definition ties it to a referenced object (in this case, every struct Person instance is referencing a &str) you want to specificly declare an arbitary lifetime and tie these two things together: You want a struct Person instance to only live as long as its referenced object (hence Person<'a> and name: &'a str) so dangling references after each other's death is avoided.

ContentLicense: CC BY-SA 4.0


问:
Socket sends binary data instead of text data
I have sample code for sending and receiving data about sockets on unix with c.

This is server code:

```<code>#include <string.h>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc, char* argv[]) //server-side
{
    int socket_desc, c, new_socket, val;
    char reply[2];
    //char* msg;
    char *msg1, *msg2, *msg3;
    msg1 = "Your number is less greater than the guessed number\n";
    msg2 = "Your number is greater than the guessed number\n";
    msg3 = "You guessed right\n";
    struct sockaddr_in server, client;
    socket_desc = socket(AF_INET, SOCK_STREAM, 0);

    srand(time(NULL));
    int num = rand() % 99 + 1;

    if(socket_desc < 0){
        printf("Couldn't create socket\n");
        return 1;
    }

    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_family = AF_INET;
    server.sin_port = htons(8888);

    if(bind(socket_desc, (struct sockaddr *)&server, sizeof(server)) < 0){
        printf("Bind error\n");
        return 1;
    }
    printf("Binding done\n");
    listen(socket_desc, 3);
    printf("Waiting for incoming connections\n");
    c = sizeof(struct sockaddr_in);

    printf("Accepted\n");
    while(new_socket = accept(socket_desc, (struct sockaddr *)&client,(socklen_t*) &c)){
        recv(new_socket, reply, strlen(reply), 0);
        val = snprintf(reply, strlen(reply), "%d", val);

        if(num < val){
            send(new_socket, msg1, sizeof(msg1), 0);
        } else if(num > val){
            send(new_socket, msg2, sizeof(msg2), 0);
        } else{
            send(new_socket, msg3, sizeof(msg3), 0);
        }
        //send(new_socket, reply, sizeof(reply), 0);
    }

    return 0;
}
</code>```

And this is client code:

```<code>#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc, char* argv[]) //client-side
{
    int socket_desc, num;
    char data[2];
    char serv_reply[50];
    struct sockaddr_in server;
    socket_desc = socket(AF_INET, SOCK_STREAM, 0);

    if(socket_desc < 0){
        printf("Couldn't create socket\n");
        return 1;
    }

    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_family = AF_INET;
    server.sin_port = htons(8888);

    //int nread = 23;
    //write(socket_desc, &nread, sizeof(nread));

    int conn = connect(socket_desc, (struct sockaddr *)&server, sizeof(server));
    if(conn == -1){
        printf("Cannot establish a connection\n");
        return 1;
    }
    printf("Connected\n");

    printf("Enter a number:\n");
    scanf("%d", &num);
    sprintf(data, "%d", num);
    if(send(socket_desc, data, strlen(data), 0) < 0){
        printf("Send was unsuccessful\n");
        return 1;
    }
    puts("Data sent\n");
    if(recv(socket_desc, serv_reply, strlen(serv_reply), 0) < 0){
        printf("Cannot receive data\n");
        return 1;
    }
    puts(serv_reply);
    return 0;
}
</code>```

I wish to see a message indicating whether random number is less than, greater than or equal to input number.But what i see is this:

I appreciate any help and before any of you ask, this is not a homework just a basic exercise on understanding sockets in unix.

答:
Here:

```<code>send(new_socket, msg1, sizeof(msg1), 0);
</code>```

sizeof(msg) is the size of a pointer.  Either transmit strlen(msg1) + 1 or (better) declare msg1 et al thus:

```<code>const char msg1[] = "Your number is less greater than the guessed number\n";
const char msg2[] = "Your number is greater than the guessed number\n";
const char msg3[] = "You guessed right\n";
</code>```

Furthermore here:

```<code>if(recv(socket_desc, serv_reply, strlen(serv_reply), 0) < 0){
        printf("Cannot receive data\n");
        return 1;
    }
    puts(serv_reply);
</code>```

strlen(serv_reply) is undefined because serv_reply has not been initialised.  Here you did need sizeof(serv_reply). You are then outputting whatever was received regardless of its length and regardless of whether it is nul terminated.

You need to output the received fragments until nothing is received, and not assume nul termination.  For example:

```<code>int received = 0 ;
do
{
    received = recv( socket_desc,
                     serv_reply,
                     sizeof(serv_reply) - 1,
                     0 ) ;
    if( received > 0 )
    {
        serv_reply[received] = '\0' ;
        printf( "%s", serv_reply ) ;
    }
} while( received > 0 ) ;
</code>```

Body:
I have sample code for sending and receiving data about sockets on unix with c.

This is server code:

#include <string.h>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc, char* argv[]) //server-side
{
    int socket_desc, c, new_socket, val;
    char reply[2];
    //char* msg;
    char *msg1, *msg2, *msg3;
    msg1 = "Your number is less greater than the guessed number\n";
    msg2 = "Your number is greater than the guessed number\n";
    msg3 = "You guessed right\n";
    struct sockaddr_in server, client;
    socket_desc = socket(AF_INET, SOCK_STREAM, 0);

    srand(time(NULL));
    int num = rand() % 99 + 1;

    if(socket_desc < 0){
        printf("Couldn't create socket\n");
        return 1;
    }

    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_family = AF_INET;
    server.sin_port = htons(8888);

    if(bind(socket_desc, (struct sockaddr *)&server, sizeof(server)) < 0){
        printf("Bind error\n");
        return 1;
    }
    printf("Binding done\n");
    listen(socket_desc, 3);
    printf("Waiting for incoming connections\n");
    c = sizeof(struct sockaddr_in);

    printf("Accepted\n");
    while(new_socket = accept(socket_desc, (struct sockaddr *)&client,(socklen_t*) &c)){
        recv(new_socket, reply, strlen(reply), 0);
        val = snprintf(reply, strlen(reply), "%d", val);

        if(num < val){
            send(new_socket, msg1, sizeof(msg1), 0);
        } else if(num > val){
            send(new_socket, msg2, sizeof(msg2), 0);
        } else{
            send(new_socket, msg3, sizeof(msg3), 0);
        }
        //send(new_socket, reply, sizeof(reply), 0);
    }

    return 0;
}

And this is client code:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc, char* argv[]) //client-side
{
    int socket_desc, num;
    char data[2];
    char serv_reply[50];
    struct sockaddr_in server;
    socket_desc = socket(AF_INET, SOCK_STREAM, 0);

    if(socket_desc < 0){
        printf("Couldn't create socket\n");
        return 1;
    }

    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_family = AF_INET;
    server.sin_port = htons(8888);

    //int nread = 23;
    //write(socket_desc, &nread, sizeof(nread));

    int conn = connect(socket_desc, (struct sockaddr *)&server, sizeof(server));
    if(conn == -1){
        printf("Cannot establish a connection\n");
        return 1;
    }
    printf("Connected\n");

    printf("Enter a number:\n");
    scanf("%d", &num);
    sprintf(data, "%d", num);
    if(send(socket_desc, data, strlen(data), 0) < 0){
        printf("Send was unsuccessful\n");
        return 1;
    }
    puts("Data sent\n");
    if(recv(socket_desc, serv_reply, strlen(serv_reply), 0) < 0){
        printf("Cannot receive data\n");
        return 1;
    }
    puts(serv_reply);
    return 0;
}

I wish to see a message indicating whether random number is less than, greater than or equal to input number.But what i see is this:

I appreciate any help and before any of you ask, this is not a homework just a basic exercise on understanding sockets in unix.

Body:
Here:

send(new_socket, msg1, sizeof(msg1), 0);

sizeof(msg) is the size of a pointer.  Either transmit strlen(msg1) + 1 or (better) declare msg1 et al thus:

const char msg1[] = "Your number is less greater than the guessed number\n";
const char msg2[] = "Your number is greater than the guessed number\n";
const char msg3[] = "You guessed right\n";

Furthermore here:

if(recv(socket_desc, serv_reply, strlen(serv_reply), 0) < 0){
        printf("Cannot receive data\n");
        return 1;
    }
    puts(serv_reply);

strlen(serv_reply) is undefined because serv_reply has not been initialised.  Here you did need sizeof(serv_reply). You are then outputting whatever was received regardless of its length and regardless of whether it is nul terminated.

You need to output the received fragments until nothing is received, and not assume nul termination.  For example:

int received = 0 ;
do
{
    received = recv( socket_desc,
                     serv_reply,
                     sizeof(serv_reply) - 1,
                     0 ) ;
    if( received > 0 )
    {
        serv_reply[received] = '\0' ;
        printf( "%s", serv_reply ) ;
    }
} while( received > 0 ) ;


问:
Add a default value to form submission in Laravel
In my controller I've got the destination columns and the origin fields for specific data entered in my create function. However, I've got a few default values in here, like below:

```<code>    $shipment->shipment_billing_status = 1;
    $shipment->created_by = $user_id;
    $shipment->cn_billtoName = request('cn_billtoName');
</code>```

As you can see $shipment->shipment_billing_status default value should always be 1. However, in extreme cases, I would like a user to be able to choose (if they need to) between two checkboxes, titled "No Settle" and "No Charge", or their values being 2 and 3.

So in those extreme cases, I want a record to absolutely go to 1 if the "No Settle" or "No Charge" checkboxes aren't selected.

答:
As you mentioned shipment_billing_status is a checkbox and if any of the checkboxes isn't selected form won't have shipment_billing_status field.

A workaround would be:

$shipment->shipment_billing_status = (isset($request->shipment_billing_status) && !empty($request->shipment_billing_status)) ? $request->shipment_billing_status : 1;

Explanation: Condition is if $request has shipment_billing_status  field and it's not empty then shipment_billing_status is used, else default value is assigned.

Body:
In my controller I've got the destination columns and the origin fields for specific data entered in my create function. However, I've got a few default values in here, like below:

    $shipment->shipment_billing_status = 1;
    $shipment->created_by = $user_id;
    $shipment->cn_billtoName = request('cn_billtoName');

As you can see $shipment->shipment_billing_status default value should always be 1. However, in extreme cases, I would like a user to be able to choose (if they need to) between two checkboxes, titled "No Settle" and "No Charge", or their values being 2 and 3.

So in those extreme cases, I want a record to absolutely go to 1 if the "No Settle" or "No Charge" checkboxes aren't selected.


问:
Gmail Api - Get Attachments
is it possible the get all the attachments for a specific message?
i only find a GET AttachmentById

答:
First you get a list of your messages from a specific tag

```<code>            var re = service.Users.Messages.List("me");
            re.LabelIds = "Label_2";
            re.Q = "is:unread";
            var res = re.Execute();
</code>```

Then you get the message through the id

```<code>               foreach (var email in res.Messages)
                {
                   GetAttachments(service, "me", email.Id, credPath);

                 }
</code>```

Title: Gmail Api - Get Attachments

Body:
First you get a list of your messages from a specific tag

            var re = service.Users.Messages.List("me");
            re.LabelIds = "Label_2";
            re.Q = "is:unread";
            var res = re.Execute();

Then you get the message through the id

               foreach (var email in res.Messages)
                {
                   GetAttachments(service, "me", email.Id, credPath);

                 }