问:
Docker container cannot access internet, only ping works
After hours of searching and trying solutions I am at an end.

When I start a Docker container on a Centos7 machine, this is what happens:

Cannot communicate via TCP (e.g. run apt update). ping works fine.

Switching network mode to --net=host fixes the issue, but I want to use the default bridge

I added net.ipv4.ip_forward=1 to /etc/sysctl.conf

Container is registered in the bridge network seen via docker network inspect bridge

DNS is configured properly, pinging hostnames works as well as addresses.

Further info

Running apt update shows messages such as:

```<code>Ign http://security.debian.org jessie/updates InRelease
Err http://security.debian.org jessie/updates Release.gpg
  Unable to connect to security.debian.org:http: [IP: 212.211.132.32 80]
</code>```

iptables configuration:

```<code>$ iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
ACCEPT     icmp --  anywhere             anywhere
           tcp  --  anywhere             anywhere             tcp dpt:http /* HTTP-IN */
           tcp  --  anywhere             anywhere             tcp dpt:http flags:FIN,SYN,RST,ACK/SYN /* HTTP-SYN */
           tcp  --  anywhere             anywhere             tcp dpt:https /* HTTPS-IN */
           tcp  --  anywhere             anywhere             tcp dpt:https flags:FIN,SYN,RST,ACK/SYN /* HTTPS-SYN */
ACCEPT     tcp  --  anywhere             anywhere             tcp flags:!FIN,SYN,RST,ACK/SYN
ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:https
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh match-set avast_internal src
ACCEPT     udp  --  anywhere             anywhere             udp dpt:snmp match-set avast_internal src
ACCEPT     tcp  --  anywhere             anywhere             tcp match-set avast_internal src

Chain FORWARD (policy DROP)
target     prot opt source               destination
DOCKER-ISOLATION  all  --  anywhere             anywhere
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
           tcp  --  anywhere             anywhere             tcp spt:http /* HTTP-OUT */
           tcp  --  anywhere             anywhere             tcp spt:https /* HTTPS-OUT */

Chain DOCKER (2 references)
target     prot opt source               destination

Chain DOCKER-ISOLATION (1 references)
target     prot opt source               destination
DROP       all  --  anywhere             anywhere
DROP       all  --  anywhere             anywhere
RETURN     all  --  anywhere             anywhere
</code>```

What could be the cause of this?

Edit:

After opening the firewall using these commands I was able to connect to the internet from the docker container:

```<code>sudo iptables -P INPUT ACCEPT
sudo iptables -P FORWARD ACCEPT
sudo iptables -P OUTPUT ACCEPT

sudo iptables -t nat -F
sudo iptables -t mangle -F
sudo iptables -F
sudo iptables -X
</code>```

However, after resetting the rules to find out which exactly caused the problem, I am unable to get it back to a working state, even after clearing all iptables rules and restarting docker daemon.

Edit 2:

Turns out there were some rules in the raw table as well, which I did not see before. The following rule was blocking Docker containers from the internet:

```<code>Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination

CT         tcp  --  anywhere             anywhere             NOTRACK
</code>```

答:
Turns out there were some rules in the raw table as well, which I did not see before. The following rule was blocking Docker containers from the internet:

```<code>Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination

CT         tcp  --  anywhere             anywhere             NOTRACK
</code>```

Deleting this rule fixed the problem.

Body:
After hours of searching and trying solutions I am at an end.

When I start a Docker container on a Centos7 machine, this is what happens:

Cannot communicate via TCP (e.g. run apt update). ping works fine.

Switching network mode to --net=host fixes the issue, but I want to use the default bridge

I added net.ipv4.ip_forward=1 to /etc/sysctl.conf

Container is registered in the bridge network seen via docker network inspect bridge

DNS is configured properly, pinging hostnames works as well as addresses.

Further info

Running apt update shows messages such as:

Ign http://security.debian.org jessie/updates InRelease
Err http://security.debian.org jessie/updates Release.gpg
  Unable to connect to security.debian.org:http: [IP: 212.211.132.32 80]

iptables configuration:

$ iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
ACCEPT     icmp --  anywhere             anywhere
           tcp  --  anywhere             anywhere             tcp dpt:http /* HTTP-IN */
           tcp  --  anywhere             anywhere             tcp dpt:http flags:FIN,SYN,RST,ACK/SYN /* HTTP-SYN */
           tcp  --  anywhere             anywhere             tcp dpt:https /* HTTPS-IN */
           tcp  --  anywhere             anywhere             tcp dpt:https flags:FIN,SYN,RST,ACK/SYN /* HTTPS-SYN */
ACCEPT     tcp  --  anywhere             anywhere             tcp flags:!FIN,SYN,RST,ACK/SYN
ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:https
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh match-set avast_internal src
ACCEPT     udp  --  anywhere             anywhere             udp dpt:snmp match-set avast_internal src
ACCEPT     tcp  --  anywhere             anywhere             tcp match-set avast_internal src

Chain FORWARD (policy DROP)
target     prot opt source               destination
DOCKER-ISOLATION  all  --  anywhere             anywhere
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
           tcp  --  anywhere             anywhere             tcp spt:http /* HTTP-OUT */
           tcp  --  anywhere             anywhere             tcp spt:https /* HTTPS-OUT */

Chain DOCKER (2 references)
target     prot opt source               destination

Chain DOCKER-ISOLATION (1 references)
target     prot opt source               destination
DROP       all  --  anywhere             anywhere
DROP       all  --  anywhere             anywhere
RETURN     all  --  anywhere             anywhere

What could be the cause of this?

Edit:

After opening the firewall using these commands I was able to connect to the internet from the docker container:

sudo iptables -P INPUT ACCEPT
sudo iptables -P FORWARD ACCEPT
sudo iptables -P OUTPUT ACCEPT

sudo iptables -t nat -F
sudo iptables -t mangle -F
sudo iptables -F
sudo iptables -X

However, after resetting the rules to find out which exactly caused the problem, I am unable to get it back to a working state, even after clearing all iptables rules and restarting docker daemon.

Edit 2:

Turns out there were some rules in the raw table as well, which I did not see before. The following rule was blocking Docker containers from the internet:

Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination

CT         tcp  --  anywhere             anywhere             NOTRACK

Body:
Turns out there were some rules in the raw table as well, which I did not see before. The following rule was blocking Docker containers from the internet:

Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination

CT         tcp  --  anywhere             anywhere             NOTRACK

Deleting this rule fixed the problem.


来源: stackexchange

问:
reactjs - how to set inline style of backgroundcolor?
I want to set the style properties of some elements but I don't have the syntax correct.  Can anyone suggest where I am wrong?

```<code>import React from 'react';
import debug from 'debug'

const log = debug('app:component:Header');

var bgColors = { "Default": "#81b71a",
                    "Blue": "#00B1E1",
                    "Cyan": "#37BC9B",
                    "Green": "#8CC152",
                    "Red": "#E9573F",
                    "Yellow": "#F6BB42",
};

export default class SideBar extends React.Component {

  constructor(props) {
    super(props);

  }

  render() {

    return (

    <a style="{{backgroundColor: {bgColors.Default}}}" >default</a>
    <a style="{{backgroundColor: {bgColors.Blue}}}" >blue</a>
    <a style="{{backgroundColor: {bgColors.Cyan}}}" >cyan</a>
    <a style="{{backgroundColor: {bgColors.Green}}}" >green</a>
    <a style="{{backgroundColor: {bgColors.Red}}}"  >red</a>
    <a style="{{backgroundColor: {bgColors.Yellow}}}" >yellow</a>
           );
  }

}
</code>```

UPDATE: for anyone looking at this please see comments this is not working code.

答:
Your quotes are in the wrong spot.  Here's a simple example:</p>

```<code><div style={{backgroundColor: "#FF0000"}}>red</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to set the style properties of some elements but I don't have the syntax correct.  Can anyone suggest where I am wrong?

import React from 'react';
import debug from 'debug'

const log = debug('app:component:Header');

var bgColors = { "Default": "#81b71a",
                    "Blue": "#00B1E1",
                    "Cyan": "#37BC9B",
                    "Green": "#8CC152",
                    "Red": "#E9573F",
                    "Yellow": "#F6BB42",
};

export default class SideBar extends React.Component {

  constructor(props) {
    super(props);

  }

  render() {

    return (

    default
    blue
    cyan
    green
    red
    yellow
           );
  }

}

UPDATE: for anyone looking at this please see comments this is not working code.

Body:
Your quotes are in the wrong spot.  Here's a simple example:

<div style={{backgroundColor: "#FF0000"}}>red</div>


问:
superpose densities, non exclusive subsets
I need to have several density functions onto a single plot. Each density corresponds to a subset of my overall dataset. The subsets are defined by the value taken by one of the variables in the dataset.

Concretely, I would like to draw a density function for 1, 3, and 10 years horizons. Of course, the 10 years horizons includes the shorter ones. Likewise, the 3 year horizon density should be constructed taking data from the last year.
The subsets need to correspond to data[period == 1,], data[period <= 3, ], data[period == 10,].

I have managed to do so by adding geom_densitys on top of each other, i.e., by redefining the data each time.

```<code>  ggplot() +
    geom_density(data = data[period <=3,], aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="red") +
    geom_density(data = data[period ==1,], aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="grey") +
    geom_density(data = data, aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="green")
</code>```

It works fine but I feel like this is not the right way to do it (and indeed, it makes e.g., the creation of a legend cumbersome).

On the other hand, doing like that :

```<code>ggplot(data, aes(x=BEST_CUR_EV_TO_EBITDA, color=period)) +
  geom_density(alpha=.2, fill="blue")
</code>```

won't do because then the periods are taken to be mutually exclusive.

Is there a way to specify aes(color) based on the value taken by period where subsets overlap?

Running code:

```<code>library(data.table)
library(lubridate)
library(ggplot2)
  YEARS <- 10
  today <- Sys.Date()
  lastYr <- Sys.Date()-years(1)
  last3Yr <- Sys.Date()-years(3)
  start.date  = Sys.Date()-years(YEARS)
  date = seq(start.date, Sys.Date(), by=1)
  BEST_CUR_EV_TO_EBITDA <- rnorm(length(date), 3,1)
  data <- cbind.data.frame(date, BEST_CUR_EV_TO_EBITDA)
  data <- cbind.data.frame(data, period = rep(10, nrow(data)))

  subPeriods <- function(aDf, from, to, value){
    aDf[aDf$date >= from & aDf$date <= to, "period"] = value
    return(aDf)
  }

  data <- subPeriods(data, last3Yr, today, 3)
  data <- subPeriods(data, lastYr, today, 1)
  data <- data.table(data)

  colScale <- scale_colour_manual(
    name = "horizon"
    , values = c("1 Y" = "grey", "3 Y" = "red", "10 Y" = "green"))

  ggplot() +
    geom_density(data = data[period <=3,], aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="red") +
    geom_density(data = data[period ==1,], aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="grey") +
    geom_density(data = data, aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="green") +
    colScale
</code>```

答:
One of the ways to deal with dependent grouping is to create an independent grouping based on the existing groups. The way I'd opted to do it below is by creating three new columns (period_one, period_three and period_ten) with mutate function, where

period_one= BEST_CUR_EV_TO_EBITDA values for period==1

period_three= BEST_CUR_EV_TO_EBITDA values for period<=1

period_ten= BEST_CUR_EV_TO_EBITDA values for all periods

These columns were then converted into the long-format using gather function, where the columns (period_one, period_three and period_ten) are stacked in "period" variable, and the corresponding values in the column "val".

```<code>df2 <- data %>%
    mutate(period_one=ifelse(period==1, BEST_CUR_EV_TO_EBITDA, NA),
            period_three=ifelse(period<=3, BEST_CUR_EV_TO_EBITDA, NA),
            period_ten=BEST_CUR_EV_TO_EBITDA) %>%
   select(date, starts_with("period_")) %>%
   gather(period, val, period_one, period_three, period_ten)
</code>```

The ggplot is straightforward with long format consisting of independent  grouping:

```<code>ggplot(df2, aes(val, fill=period)) + geom_density(alpha=.2)
</code>```

Body:
I need to have several density functions onto a single plot. Each density corresponds to a subset of my overall dataset. The subsets are defined by the value taken by one of the variables in the dataset.

Concretely, I would like to draw a density function for 1, 3, and 10 years horizons. Of course, the 10 years horizons includes the shorter ones. Likewise, the 3 year horizon density should be constructed taking data from the last year.
The subsets need to correspond to data[period == 1,], data[period <= 3, ], data[period == 10,].

I have managed to do so by adding geom_densitys on top of each other, i.e., by redefining the data each time.

  ggplot() +
    geom_density(data = data[period <=3,], aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="red") +
    geom_density(data = data[period ==1,], aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="grey") +
    geom_density(data = data, aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="green")

It works fine but I feel like this is not the right way to do it (and indeed, it makes e.g., the creation of a legend cumbersome).

On the other hand, doing like that :

ggplot(data, aes(x=BEST_CUR_EV_TO_EBITDA, color=period)) +
  geom_density(alpha=.2, fill="blue")

won't do because then the periods are taken to be mutually exclusive.

Is there a way to specify aes(color) based on the value taken by period where subsets overlap?

Running code:

library(data.table)
library(lubridate)
library(ggplot2)
  YEARS <- 10
  today <- Sys.Date()
  lastYr <- Sys.Date()-years(1)
  last3Yr <- Sys.Date()-years(3)
  start.date  = Sys.Date()-years(YEARS)
  date = seq(start.date, Sys.Date(), by=1)
  BEST_CUR_EV_TO_EBITDA <- rnorm(length(date), 3,1)
  data <- cbind.data.frame(date, BEST_CUR_EV_TO_EBITDA)
  data <- cbind.data.frame(data, period = rep(10, nrow(data)))

  subPeriods <- function(aDf, from, to, value){
    aDf[aDf$date >= from & aDf$date <= to, "period"] = value
    return(aDf)
  }

  data <- subPeriods(data, last3Yr, today, 3)
  data <- subPeriods(data, lastYr, today, 1)
  data <- data.table(data)

  colScale <- scale_colour_manual(
    name = "horizon"
    , values = c("1 Y" = "grey", "3 Y" = "red", "10 Y" = "green"))

  ggplot() +
    geom_density(data = data[period <=3,], aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="red") +
    geom_density(data = data[period ==1,], aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="grey") +
    geom_density(data = data, aes(x=BEST_CUR_EV_TO_EBITDA), alpha=.2, fill="green") +
    colScale

Body:
One of the ways to deal with dependent grouping is to create an independent grouping based on the existing groups. The way I'd opted to do it below is by creating three new columns (period_one, period_three and period_ten) with mutate function, where

period_one= BEST_CUR_EV_TO_EBITDA values for period==1

period_three= BEST_CUR_EV_TO_EBITDA values for period<=1

period_ten= BEST_CUR_EV_TO_EBITDA values for all periods

These columns were then converted into the long-format using gather function, where the columns (period_one, period_three and period_ten) are stacked in "period" variable, and the corresponding values in the column "val".

df2 <- data %>%
    mutate(period_one=ifelse(period==1, BEST_CUR_EV_TO_EBITDA, NA),
            period_three=ifelse(period<=3, BEST_CUR_EV_TO_EBITDA, NA),
            period_ten=BEST_CUR_EV_TO_EBITDA) %>%
   select(date, starts_with("period_")) %>%
   gather(period, val, period_one, period_three, period_ten)

The ggplot is straightforward with long format consisting of independent  grouping:

ggplot(df2, aes(val, fill=period)) + geom_density(alpha=.2)


问:
Split string into array in Python
I have a string with the following structure.

string = "[abcd, abc, a, b, abc]"

I would like to convert that into an array. I keep using the split function in Python but I get spaces and the brackets on the start and the end of my new array. I tried working around it with some if statements but I keep missing letters in the end from some words.

Keep in mind that I don't know the length of the elements in the string. It could be 1, 2, 3 etc.

答:
You can also do this</p>

```<code>>>> s = string[1:len(string)-1].split(", ")
>>> s
['abcd', 'abc', 'a', 'b', 'abc']
</code>```

Title: Split string into array in Python

Body:
You can also do this

>>> s = string[1:len(string)-1].split(", ")
>>> s
['abcd', 'abc', 'a', 'b', 'abc']


问:
Intent with multiple startactivity paramaters
I want a value to be passed from the first to the last activity when a button is clicked.

At the same time I want this button to bring me to the second activity. Somehow this doesn't work.

```<code>private void imagebutton1 () {
          ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
            btn.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  //startActivity (new Intent(Akt1.this,Akt2.class));

                  String data1 = "data1";

                  Intent intent = new Intent (Akt1.this,Akt2.class);
                  Intent passdata_intent = new Intent(Akt1.this, Akt6.class);
                  passdata_intent.putExtra("data1",data1);

                 startActivity(passdata_intent);

              }
          });
</code>```

答:
```<code>private void imagebutton1 () {
        ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String data1 = "data1";

                Intent intent = new Intent (Akt1.this,Akt2.class);
                intent.putExtra("data1",data1);

               startActivity(intent );

            }
        });
</code>```

For example :

In MainActivity :

```<code>Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra(OtherActivity.KEY_EXTRA, yourDataObject);
startActivity(intent);
</code>```

In OtherActivity :

```<code>public static final String KEY_EXTRA = "com.example.yourapp.KEY_BOOK";

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  String yourDataObject = null;

  if (getIntent().hasExtra(KEY_EXTRA)) {
      yourDataObject = getIntent().getStringExtra(KEY_EXTRA);
  } else {
      throw new IllegalArgumentException("Activity cannot find  extras " + KEY_EXTRA);
  }
  // do stuff
}
</code>```

More informations here : http://developer.android.com/reference/android/content/Intent.html

Body:
I want a value to be passed from the first to the last activity when a button is clicked.

At the same time I want this button to bring me to the second activity. Somehow this doesn't work.

private void imagebutton1 () {
          ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
            btn.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  //startActivity (new Intent(Akt1.this,Akt2.class));

                  String data1 = "data1";

                  Intent intent = new Intent (Akt1.this,Akt2.class);
                  Intent passdata_intent = new Intent(Akt1.this, Akt6.class);
                  passdata_intent.putExtra("data1",data1);

                 startActivity(passdata_intent);

              }
          });

Body:
private void imagebutton1 () {
        ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String data1 = "data1";

                Intent intent = new Intent (Akt1.this,Akt2.class);
                intent.putExtra("data1",data1);

               startActivity(intent );

            }
        });

For example :

In MainActivity :

Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra(OtherActivity.KEY_EXTRA, yourDataObject);
startActivity(intent);

In OtherActivity :

public static final String KEY_EXTRA = "com.example.yourapp.KEY_BOOK";

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  String yourDataObject = null;

  if (getIntent().hasExtra(KEY_EXTRA)) {
      yourDataObject = getIntent().getStringExtra(KEY_EXTRA);
  } else {
      throw new IllegalArgumentException("Activity cannot find  extras " + KEY_EXTRA);
  }
  // do stuff
}

More informations here : http://developer.android.com/reference/android/content/Intent.html


问:
Laravel Route : route::resource
I'm very new in laravel,
I'm following some tutorial

this code work fine

```<code>Route::group(['middleware' => 'web'], function() {
    Route::resource('tes', 'TesController');
});
<form action="{{ route('tes.destroy',3) }}" method="post">
</code>```

until i modified it like this one

```<code>Route::resource('tes/keren', 'TesController');

<form action="{{ route('tes/keren.destroy',3) }}" method="post">
</code>```

It said tes/keren.destroy undefined....
just simple question, which should I modify so, I can route with /

Thank you

答:
The route helper function takes the route name as the parameter. When you changed the route url, the route name changed to keren.destroy from tes.destroy. So you need to change your form action to

```<code><form action="{{ route('keren.destroy', 3) }}" method="post">
</code>```

If you ever want to check your route names, just run php artisan route:list from the terminal/console. In this case it should show you something like this.

```<code>| GET|HEAD  | tes/keren              | keren.index   | App\Http\Controllers\TesController@index   | web          |
| POST      | tes/keren              | keren.store   | App\Http\Controllers\TesController@store   | web          |
| GET|HEAD  | tes/keren/create       | keren.create  | App\Http\Controllers\TesController@create  | web          |
| GET|HEAD  | tes/keren/{keren}      | keren.show    | App\Http\Controllers\TesController@show    | web          |
| PUT|PATCH | tes/keren/{keren}      | keren.update  | App\Http\Controllers\TesController@update  | web          |
| DELETE    | tes/keren/{keren}      | keren.destroy | App\Http\Controllers\TesController@destroy | web          |
| GET|HEAD  | tes/keren/{keren}/edit | keren.edit    | App\Http\Controllers\TesController@edit    | web          |
</code>```

Title: Laravel Route : route::resource

Body:
I'm very new in laravel,
I'm following some tutorial

this code work fine

Route::group(['middleware' => 'web'], function() {
    Route::resource('tes', 'TesController');
});
<form action="{{ route('tes.destroy',3) }}" method="post">

until i modified it like this one

Route::resource('tes/keren', 'TesController');

<form action="{{ route('tes/keren.destroy',3) }}" method="post">

It said tes/keren.destroy undefined....
just simple question, which should I modify so, I can route with /

Thank you

Body:
The route helper function takes the route name as the parameter. When you changed the route url, the route name changed to keren.destroy from tes.destroy. So you need to change your form action to

<form action="{{ route('keren.destroy', 3) }}" method="post">

If you ever want to check your route names, just run php artisan route:list from the terminal/console. In this case it should show you something like this.

| GET|HEAD  | tes/keren              | keren.index   | App\Http\Controllers\TesController@index   | web          |
| POST      | tes/keren              | keren.store   | App\Http\Controllers\TesController@store   | web          |
| GET|HEAD  | tes/keren/create       | keren.create  | App\Http\Controllers\TesController@create  | web          |
| GET|HEAD  | tes/keren/{keren}      | keren.show    | App\Http\Controllers\TesController@show    | web          |
| PUT|PATCH | tes/keren/{keren}      | keren.update  | App\Http\Controllers\TesController@update  | web          |
| DELETE    | tes/keren/{keren}      | keren.destroy | App\Http\Controllers\TesController@destroy | web          |
| GET|HEAD  | tes/keren/{keren}/edit | keren.edit    | App\Http\Controllers\TesController@edit    | web          |


答: i don't know why you need to start two activies with one button, but you can start first activity and in your first activity's on create you can start second activity (you can recreate your intent in first activity.)</p>

Title: Intent with multiple startactivity paramaters


问:
LifecycleObserver is not working
Observer methods are not being called. I tested ViewPagerCycler as in old school ways and working perfect. Thanks for help.

```<code>public final class ViewPagerCycler implements LifecycleObserver {

    private static final int PERIOD = 3000;

    private Timer mTimer;
    private TimerTask mTask;
    private Activity mActivity;
    private ViewPager mPager;

    public ViewPagerCycler(Activity activity, ViewPager pager) {
        mActivity = activity;
        mPager = pager;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void start() {
        int count = mPager
            .getAdapter()
            .getCount();

        mTimer = new Timer();
        mTask = new TimerTask() {
            @Override public void run() {
                mActivity.runOnUiThread(new TimerTask() {
                    @Override public void run() {
                        mPager.setCurrentItem((mPager.getCurrentItem() + 1) % count, true);
                    }
                });
            }
        };
        mTimer.schedule(mTask, PERIOD, PERIOD);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void stop() {
        mTask.cancel();
        mTimer.cancel();
        mTimer.purge();
    }
}
</code>```

Activity is just summarized. I didn't add findViewByIds.

```<code>public class SummariziedActivity extends Activity implements LifecycleOwner {
   private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);

   @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       mRegistry.addObserver(new ViewPagerCycler(mPager));
   }
}
</code>```

In the build.gradle:

```<code>compile "android.arch.lifecycle:runtime:1.0.0-alpha2"
compile "android.arch.lifecycle:extensions:1.0.0-alpha2"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha2"
</code>```

答:
Seems like implementing LifecycleRegistryOwner is not enough.

I came across the same problem in 1.0.0-alpha1 and I actually needed to forward lifecycle events to the Lifecycle instance myself in order to make it work. This is because either the documentation does not conform to the implementation, or this is a bug in the library.

I only used onStart() and onStop() in my Observers, so I forwarded these lifecycle events to the Lifecycle.

```<code>abstract class LifecyclePreferenceFragment : PreferenceFragment(), LifecycleRegistryOwner {

    private val mLifecycleRegistry = LifecycleRegistry(this)

    override fun getLifecycle() = mLifecycleRegistry

    override fun onStart() {
        super.onStart()
        lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_START)
    }

    override fun onStop() {
        super.onStop()
        lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
    }
}
</code>```

Title: LifecycleObserver is not working

Body:
Observer methods are not being called. I tested ViewPagerCycler as in old school ways and working perfect. Thanks for help.

public final class ViewPagerCycler implements LifecycleObserver {

    private static final int PERIOD = 3000;

    private Timer mTimer;
    private TimerTask mTask;
    private Activity mActivity;
    private ViewPager mPager;

    public ViewPagerCycler(Activity activity, ViewPager pager) {
        mActivity = activity;
        mPager = pager;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void start() {
        int count = mPager
            .getAdapter()
            .getCount();

        mTimer = new Timer();
        mTask = new TimerTask() {
            @Override public void run() {
                mActivity.runOnUiThread(new TimerTask() {
                    @Override public void run() {
                        mPager.setCurrentItem((mPager.getCurrentItem() + 1) % count, true);
                    }
                });
            }
        };
        mTimer.schedule(mTask, PERIOD, PERIOD);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void stop() {
        mTask.cancel();
        mTimer.cancel();
        mTimer.purge();
    }
}

Activity is just summarized. I didn't add findViewByIds.

public class SummariziedActivity extends Activity implements LifecycleOwner {
   private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);

   @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       mRegistry.addObserver(new ViewPagerCycler(mPager));
   }
}

In the build.gradle:

compile "android.arch.lifecycle:runtime:1.0.0-alpha2"
compile "android.arch.lifecycle:extensions:1.0.0-alpha2"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha2"

Body:
Seems like implementing LifecycleRegistryOwner is not enough.

I came across the same problem in 1.0.0-alpha1 and I actually needed to forward lifecycle events to the Lifecycle instance myself in order to make it work. This is because either the documentation does not conform to the implementation, or this is a bug in the library.

I only used onStart() and onStop() in my Observers, so I forwarded these lifecycle events to the Lifecycle.

abstract class LifecyclePreferenceFragment : PreferenceFragment(), LifecycleRegistryOwner {

    private val mLifecycleRegistry = LifecycleRegistry(this)

    override fun getLifecycle() = mLifecycleRegistry

    override fun onStart() {
        super.onStart()
        lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_START)
    }

    override fun onStop() {
        super.onStop()
        lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
    }
}


问:
ES6 Dyanmic Promise Chaining from array
Scenario

I have an array of URLs that I need to download, however each must also be supplied with a unique transaction ID that must be requested from the server and only increments when a request is successful.

Problem

As I loop through the array I need to wait for both the request for the transaction ID and the request for the file to complete before starting the next iteration of the loop but the number of files is not fixed so need to dynamically build a chain of promises.

Pseudocode

Below is some pseudocode, getFiles() is the problem because all the requests get the same transaction Id as they don't wait for the previous request to finish.

```<code>function getTransationId(){
    return new Promise((resolve,reject)=> {
        let id = getNextTransactionId();
        if(id!=error){
            resolve(id);
        }else{
            reject(error);
        }
    })
}

function getFile(url, transactionId){
    return new Promise((resolve,reject)=>{
        http.request(url+transactionId, function(err,response){
            if(err){
                reject(err);
            }else{
                resolve(response);
            }
        });
    });
}

function getFilesFromArray(urlArray){
    for(let url of urlArray){
        getTransactionId().then(resolve=>getFile(url,resolve),reject=>console.error(reject));
    }
}
</code>```

Question

How do I chain chain promises together dynamically?

Answer

Here's a JSFiddle of Ovidiu's answer

答:
Try using async/await.

Read more here

```<code>async function getFilesFromArray(urlArray) {
      for(let url of urlArray){
         //wrap this in a try/catch block if you want to continue with execution
         //if you receive an error from one of the functions
         const transactionId =await getTransactionId()
         const file = await getFile(url,transactionId)
}
}
</code>```

Title: ES6 Dyanmic Promise Chaining from array

Body:
Scenario

I have an array of URLs that I need to download, however each must also be supplied with a unique transaction ID that must be requested from the server and only increments when a request is successful.

Problem

As I loop through the array I need to wait for both the request for the transaction ID and the request for the file to complete before starting the next iteration of the loop but the number of files is not fixed so need to dynamically build a chain of promises.

Pseudocode

Below is some pseudocode, getFiles() is the problem because all the requests get the same transaction Id as they don't wait for the previous request to finish.

function getTransationId(){
    return new Promise((resolve,reject)=> {
        let id = getNextTransactionId();
        if(id!=error){
            resolve(id);
        }else{
            reject(error);
        }
    })
}

function getFile(url, transactionId){
    return new Promise((resolve,reject)=>{
        http.request(url+transactionId, function(err,response){
            if(err){
                reject(err);
            }else{
                resolve(response);
            }
        });
    });
}

function getFilesFromArray(urlArray){
    for(let url of urlArray){
        getTransactionId().then(resolve=>getFile(url,resolve),reject=>console.error(reject));
    }
}

Question

How do I chain chain promises together dynamically?

Answer

Here's a JSFiddle of Ovidiu's answer

Body:
Try using async/await.

Read more here

async function getFilesFromArray(urlArray) {
      for(let url of urlArray){
         //wrap this in a try/catch block if you want to continue with execution
         //if you receive an error from one of the functions
         const transactionId =await getTransactionId()
         const file = await getFile(url,transactionId)
}
}


问:
Set default font size in styles.xml
I am working on an android project.

I have a tabbed page and the title of the pages are very big.
What i want to do is to decrease font size by changing values in styles.xml

do you know if it is possible ?

The project is written with Xamarin, so i want to avoid to write some specific code, like renderers.

Thanks a lot

答:
This is possible
styles.xml as follow:

```<code> <style name="FontTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:textSize">20sp</item>
        <item name="android:textColor">@color/black</item>
 </style>
</code>```

use code:

```<code><TextView
    style="@style/FontTheme"
    android:layout_marginTop="100dp"
    android:text="test1"/>
</code>```

Title: Set default font size in styles.xml

Body:
This is possible
styles.xml as follow:

 <style name="FontTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:textSize">20sp</item>
        <item name="android:textColor">@color/black</item>
 </style>

use code:

<TextView
    style="@style/FontTheme"
    android:layout_marginTop="100dp"
    android:text="test1"/>


问:
How does the browser render Images with different sizes ( tag in HTML)?
If an HTML document has three images in different sizes (5MB, 50KB and 10MB) then which image will be rendered first in the page? Does the browser process  tags synchronously? That is, will the render sequence  be

5_mb_img.jpg > 50_kb_img.jpg > 10_mb_img.jpg

OR

might 50_kb_img.jpg be rendered first because  it is smallest in size?

```<code><img src="5_mb_img.jpg" /> <!-- a 5MB image file -->
<img src="50_kb_img.jpg" /> <!-- a 50KB image file -->
<img src="10_mb_img.jpg" /> <!-- a 10MB image file -->
</code>```

WHY A BOUNTY? I know the answer but am expecting a very good explanation that helps someone who is searching it in Stack Overflow

答:
The browser don't know the file size before it start download ;-)

So usaly a browser loads the file in the order of the source code. But files like background image that the browser don't need to render loads later.

Depending of the browser it load up to 8-10 files at the same time. The maximium was limited during the Mellisa virus in the 80'ies to limited DOD from one maschine. Today with Https2 more request are possible (and still file push)

If you wan't swicth the files size depending on the screen resolution use srcset.

Main context is the browser loads the files first that he need to render the screen, like css files, sync .js with write comand etc. So if you add the witdh and height attribute to your img tag the browser can calculate the Rendering without loading the image. It will first load other file that the he need to render.

Title: How does the browser render Images with different sizes (<img> tag in HTML)?

Body:
If an HTML document has three images in different sizes (5MB, 50KB and 10MB) then which image will be rendered first in the page? Does the browser process  tags synchronously? That is, will the render sequence  be

5_mb_img.jpg > 50_kb_img.jpg > 10_mb_img.jpg

OR

might 50_kb_img.jpg be rendered first because  it is smallest in size?

WHY A BOUNTY? I know the answer but am expecting a very good explanation that helps someone who is searching it in Stack Overflow


问:
SQLSTATE[42S22]: Column not found: 1054 Unknown column one to many(inverse) relation laravel
I have two models Tour.php and TourCategory.php:

Tour.php

```<code>protected $table = `tours`;

public function category()
{
    return $this->belongsTo('App\TourCategory');
}
</code>```

TourCategory.php

```<code>protected $table = 'tcategories';

public function tours()
{
    return $this->hasMany('App\Tour');
}
</code>```

My db tables are as follows:

tours table

id|title|category_id|content|

tcatgegories table

id|name

And I have a view to show the all tours belonging to a category with the following code:

```<code>    @foreach ($category->tours as $tour)
     <tr>
        <th>{{ $tour->id}}</th>
        <td>{{ $tour->title}}</td>
        <td>
            <span class="label label-default">{{$category->name}}</span>
        </td>
     </tr>
    @endforeach
</code>```

With this above code I'm getting error of:

```<code>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tours.tour_category_id' in
'where clause' (SQL: select * from `tours` where `tours`.`tour_category_id` = 1 and
`tours`.`tour_category_id` is not null) (View: F:\multiauth_tutorial-master\resources\
views\admin\categories\show.blade.php
</code>```

I have used same code for my previous projects also but didn't had any errors. Or am I missing something ?

答:
in Tour.php </p>

```<code> /**
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function tours()
{
    return $this->hasMany(Tour::class, 'category_id');
}
</code>```

<p>in TourCategory.php </p>

```<code>/**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function category()
    {
        return $this->belongsTo(TourCategory::class, 'category_id');
    }
</code>```

Body:
I have two models Tour.php and TourCategory.php:

Tour.php

protected $table = `tours`;

public function category()
{
    return $this->belongsTo('App\TourCategory');
}

TourCategory.php

protected $table = 'tcategories';

public function tours()
{
    return $this->hasMany('App\Tour');
}

My db tables are as follows:

tours table

id|title|category_id|content|

tcatgegories table

id|name

And I have a view to show the all tours belonging to a category with the following code:

    @foreach ($category->tours as $tour)

        {{ $tour->id}}
        {{ $tour->title}}

            {{$category->name}}

    @endforeach

With this above code I'm getting error of:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tours.tour_category_id' in
'where clause' (SQL: select * from `tours` where `tours`.`tour_category_id` = 1 and
`tours`.`tour_category_id` is not null) (View: F:\multiauth_tutorial-master\resources\
views\admin\categories\show.blade.php

I have used same code for my previous projects also but didn't had any errors. Or am I missing something ?

Body:
in Tour.php

 /**
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function tours()
{
    return $this->hasMany(Tour::class, 'category_id');
}

in TourCategory.php

/**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function category()
    {
        return $this->belongsTo(TourCategory::class, 'category_id');
    }


问:
SQL Query with JOIN, WHERE and AND clause to convert in Laravel queries
I'm having problem converting my SQL query to laravel queries. I want to join two tables users and messages so that i can get the users that has conversation with other users.

Database Structure:

Users:

Messages:

This is my SQL query where I get what I want:

```<code>SELECT u.id, c.id, u.first_name, u.last_name FROM messages c, users u
      WHERE (CASE WHEN c.user_one =  @USERID THEN c.user_two = u.ID WHEN c.user_two = @USERID THEN c.user_one= u.id END )
      AND ( c.user_one = @USERID OR c.user_two = @USERID ) Order by c.id DESC Limit 20
</code>```

This is my Laravel query:

```<code>DB::table('messages')
   ->join('users', function($join) use ($user_id) {
        $join->select(DB::raw('CASE WHEN messages.user_one = ' . $user_id . ' THEN messages.user_two = ' . $user_id . 'WHEN messages.user_two = ' . $user_id . ' THEN messages.user_one = ' . $user_id));
        $join->on(function($query) use ($user_id)
        {
             $query->where('messages.user_one', '=', $user_id);
             $query->orWhere('messages.user_two', '=',$user_id);
        });
   })
   ->select('users.*', 'messages.*')
   ->get();
</code>```

答:
UPDATE:
Sorry my original answer was not injecting variables in a secure way. Please use this for securely injecting variables in raw queries.

SQL injection security in raw statements.

In raw queries we need remember to pass all variables to our mysql
database using provided second argument.

In your case, you just place question marks placeholders, where you want to have your variables injected and then put your variables in same order as your placeholders in your second argument array.

Source: http://s4.jeffsbio.co.uk/laravel-5-query-builder-where-raw-2

Updated Query:-

```<code>DB::table('messages as m')
        ->join('users as u',function($join){
            $join->on('u.id','=','m.user_one')
            ->orOn('u.id','=','m.user_two');
        })
        ->where(function($query) use($user_id){
            $query->where('m.user_one','=',$user_id);
            $query->orWhere('m.user_two','=',$user_id);
        })
       ->where(function($query) use($user_id){
            $query->whereRaw(
                        'CASE WHEN m.user_one = ?'.
                        ' THEN m.user_two = u.id'.
                        ' WHEN m.user_two = ?'.
                        ' THEN m.user_one = u.id END',[$user_id,$user_id]);
                    //here we passed the variables in exact order of their usage in query
       })
      ->select('u.id as user_id', 'm.id as messages_id','u.first_name','u.last_name')
      ->orderBy('m.id','DESC')
      ->limit('20')
      ->get(
</code>```

Original Answer:
You can't use select clause in join clause like you have.

Use this :-

```<code>DB::table('messages as m')
->join('users as u',function($join){
     $join->on('u.id','=','m.user_one')
     ->orOn('u.id','=','m.user_two');
})
->where(function($query) use($user_id){
    $query->where('m.user_one','=',$user_id);
    $query->orWhere('m.user_two','=',$user_id);
})
->where(function($query) use($user_id){
    $query->whereRaw(DB::raw(
           'CASE WHEN m.user_one = '.$user_id.
           ' THEN m.user_two = u.id'.
           ' WHEN m.user_two = '.$user_id.
           ' THEN m.user_one = u.id END'));
   })
->select('u.id as user_id', 'm.id as messages_id','u.first_name','u.last_name')
 ->orderBy('m.id','DESC')
 ->limit('20')
 ->get();
</code>```

Body:
I'm having problem converting my SQL query to laravel queries. I want to join two tables users and messages so that i can get the users that has conversation with other users.

Database Structure:

Users:

Messages:

This is my SQL query where I get what I want:

SELECT u.id, c.id, u.first_name, u.last_name FROM messages c, users u
      WHERE (CASE WHEN c.user_one =  @USERID THEN c.user_two = u.ID WHEN c.user_two = @USERID THEN c.user_one= u.id END )
      AND ( c.user_one = @USERID OR c.user_two = @USERID ) Order by c.id DESC Limit 20

This is my Laravel query:

DB::table('messages')
   ->join('users', function($join) use ($user_id) {
        $join->select(DB::raw('CASE WHEN messages.user_one = ' . $user_id . ' THEN messages.user_two = ' . $user_id . 'WHEN messages.user_two = ' . $user_id . ' THEN messages.user_one = ' . $user_id));
        $join->on(function($query) use ($user_id)
        {
             $query->where('messages.user_one', '=', $user_id);
             $query->orWhere('messages.user_two', '=',$user_id);
        });
   })
   ->select('users.*', 'messages.*')
   ->get();

Body:
UPDATE:
Sorry my original answer was not injecting variables in a secure way. Please use this for securely injecting variables in raw queries.

SQL injection security in raw statements.

In raw queries we need remember to pass all variables to our mysql
database using provided second argument.

In your case, you just place question marks placeholders, where you want to have your variables injected and then put your variables in same order as your placeholders in your second argument array.

Source: http://s4.jeffsbio.co.uk/laravel-5-query-builder-where-raw-2

Updated Query:-

DB::table('messages as m')
        ->join('users as u',function($join){
            $join->on('u.id','=','m.user_one')
            ->orOn('u.id','=','m.user_two');
        })
        ->where(function($query) use($user_id){
            $query->where('m.user_one','=',$user_id);
            $query->orWhere('m.user_two','=',$user_id);
        })
       ->where(function($query) use($user_id){
            $query->whereRaw(
                        'CASE WHEN m.user_one = ?'.
                        ' THEN m.user_two = u.id'.
                        ' WHEN m.user_two = ?'.
                        ' THEN m.user_one = u.id END',[$user_id,$user_id]);
                    //here we passed the variables in exact order of their usage in query
       })
      ->select('u.id as user_id', 'm.id as messages_id','u.first_name','u.last_name')
      ->orderBy('m.id','DESC')
      ->limit('20')
      ->get(

Original Answer:
You can't use select clause in join clause like you have.

Use this :-

DB::table('messages as m')
->join('users as u',function($join){
     $join->on('u.id','=','m.user_one')
     ->orOn('u.id','=','m.user_two');
})
->where(function($query) use($user_id){
    $query->where('m.user_one','=',$user_id);
    $query->orWhere('m.user_two','=',$user_id);
})
->where(function($query) use($user_id){
    $query->whereRaw(DB::raw(
           'CASE WHEN m.user_one = '.$user_id.
           ' THEN m.user_two = u.id'.
           ' WHEN m.user_two = '.$user_id.
           ' THEN m.user_one = u.id END'));
   })
->select('u.id as user_id', 'm.id as messages_id','u.first_name','u.last_name')
 ->orderBy('m.id','DESC')
 ->limit('20')
 ->get();


问:
Why does Python's CONTINUE_LOOP allow an outer loop, when BREAK_LOOP doesn't?
I've noticed an intriguing peculiarity in Python's bytecode here.

The CONTINUE_LOOP opcode takes in a target argument that denotes the instruction of the loop to continue executing, which is a FOR_ITER instruction.

The BREAK_LOOP opcode, however, does not do this. It only breaks out of the current (innermost) loop.

What is the reason behind this? Why should it be possible to continue but not break an outer loop?

答:
You are misunderstanding the target. The value is not needed to handle nested loops. Instead, the target marks the point in the bytecode stream to move to after the instruction. BREAK doesn't need such a target because that value is already defined elsewhere.

BREAK_LOOP ends a loop and thus execution continues after the loop. The SETUP_LOOP instruction has defined the endpoint already, so the interpreter doesn't need any additional information to execute this opcode.

CONTINUE_LOOP on the other hand needs to be told where to continue to. In most loops, a JUMP_ABSOLUTE opcode is used, and CONTINUE_LOOP echoes that instruction here. CONTINUE_LOOP records a bit more information to handle try statements (to track stack unwinding).

In the evaluation loop, exception handling (try: ... except: and try
: ... finally:) as well as context managers (with ...: and async with ...:) use a generalised concept of a frame block, which has an exit point recorded for it, which is what the BREAK_LOOP instruction relies on here. Not having to track an offset is simpler this way and avoids the compiler and evaluation loop having to repeat themselves (the exit point is used for other scenarios too, not just the break statement).

But jumps are more generic and so their offsets are easier to track tied to the instruction itself.


问:
Event value keeps changing when an object equal to the event is changed
The following code is being used to map an event with an object:

```<code>//shortened the function for better visibility
moveToolbar.on("graphic-move-stop", function (evt) {
    oldGraphicMove = evt.graphic;
    oldGraphicMove.geometry.rings[0][0] = 42173;
    newGraphicMove = evt.graphic;
});
</code>```

However when changing the value of oldGraphicMove the value of the event is also changing to mimic it even though no change is being made to the event itself. Is there any way to prevent this?

答:
the objects are passed by reference. to pass it by value you can use the anonymous function or you need to clone object</p>

```<code>//shortened the function for better visibility
moveToolbar.on("graphic-move-stop", function (evt) {
  oldGraphicMove = (function(x){
    var obj = Object.create( x );
    obj.geometry.rings[0][0] = 42173;
    return obj;
  })(evt.graphic);
  newGraphicMove = evt.graphic;
});
</code>```

Body:
The following code is being used to map an event with an object:

//shortened the function for better visibility
moveToolbar.on("graphic-move-stop", function (evt) {
    oldGraphicMove = evt.graphic;
    oldGraphicMove.geometry.rings[0][0] = 42173;
    newGraphicMove = evt.graphic;
});

However when changing the value of oldGraphicMove the value of the event is also changing to mimic it even though no change is being made to the event itself. Is there any way to prevent this?

Body:
the objects are passed by reference. to pass it by value you can use the anonymous function or you need to clone object

//shortened the function for better visibility
moveToolbar.on("graphic-move-stop", function (evt) {
  oldGraphicMove = (function(x){
    var obj = Object.create( x );
    obj.geometry.rings[0][0] = 42173;
    return obj;
  })(evt.graphic);
  newGraphicMove = evt.graphic;
});


问:
Search within a big vector in C++
I have following vectors:

```<code>std::vector<A*> vec;
std::vector<std::pair<A*, A*>> vec_pair;
</code>```

vec_pair size is much more than vec size. I would like to find a pair within vec_pair which both members are inside vec.

contents of the vec_pair are constant. However after each iteration the contents of the vec will change and I would like to do the test again.

I know I can do a for loop and do the check. However considering size difference and recurrence of the job, I am looking for a smart and efficient way to do it.

答:
You can use an unordered_set (you don't really need a map) which allows O(1) search and insert.

1) From vec you build an unordered_set S;

2) For each pair in vec_pair you can check if both elements are present in S

Something like the following will do the job in average O(vec_pair.size())

```<code>std::vector<A*> vec;
std::vector<std::pair<A*, A*>> vec_pair;

unordered_set<A*> S;
for(auto a: vec)
    S.insert(a);

for(auto p : vec_pair){
    if(s.find(p.first)!=S.end() &&
        s.find(p.second)!=S.end())
    {
        //PAIR GOOD
    }else{
        //THIS PAIR IS NOT GOOD
    }
}
</code>```

Title: Search within a big vector in C++

Body:
I have following vectors:

std::vector vec;
std::vector<std::pair> vec_pair;

vec_pair size is much more than vec size. I would like to find a pair within vec_pair which both members are inside vec.

contents of the vec_pair are constant. However after each iteration the contents of the vec will change and I would like to do the test again.

I know I can do a for loop and do the check. However considering size difference and recurrence of the job, I am looking for a smart and efficient way to do it.

Body:
You can use an unordered_set (you don't really need a map) which allows O(1) search and insert.

1) From vec you build an unordered_set<A*> S;

2) For each pair in vec_pair you can check if both elements are present in S

Something like the following will do the job in average O(vec_pair.size())

std::vector<A*> vec;
std::vector<std::pair<A*, A*>> vec_pair;

unordered_set<A*> S;
for(auto a: vec)
    S.insert(a);

for(auto p : vec_pair){
    if(s.find(p.first)!=S.end() &&
        s.find(p.second)!=S.end())
    {
        //PAIR GOOD
    }else{
        //THIS PAIR IS NOT GOOD
    }
}


答:
If you do not want to use strip, it can be done by following rather clumsy way:

```<code>arr = [e[1:] for e in string.split(',')]
arr[len(arr)-1]=arr[len(arr)-1].replace(']', '')

print(arr)
['abcd', 'abc', 'a', 'b', 'abc']
</code>```

Title: Split string into array in Python

Body:
I have a string with the following structure.

string = "[abcd, abc, a, b, abc]"

I would like to convert that into an array. I keep using the split function in Python but I get spaces and the brackets on the start and the end of my new array. I tried working around it with some if statements but I keep missing letters in the end from some words.

Keep in mind that I don't know the length of the elements in the string. It could be 1, 2, 3 etc.

Body:
If you do not want to use strip, it can be done by following rather clumsy way:

arr = [e[1:] for e in string.split(',')]
arr[len(arr)-1]=arr[len(arr)-1].replace(']', '')

print(arr)
['abcd', 'abc', 'a', 'b', 'abc']


问:
Laravel Broadcasting
My Scenario

Im trying to get laravel to work with pusher without the use of laravel echo, everything works on a public channel but when i switch to a private channel in the broadcastOn() method of my event pusher on the frontend doesn't pick anything up anymore. It gets logged in my pusher applications event log as a private channel but pusher on the frontend just sais no.

I've set up and returned true for the channel code like this:

```<code>Broadcast::channel('application', function ($post, $username) {
    if(true){
        return true;
    }
});
</code>```

This is my event code:

```<code>public function broadcastOn()
{
    return new PrivateChannel('application');
}
</code>```

The class implements ShouldBroadcast and lastly here is my front end code:

```<code> <script>
    //instantiate a Pusher object with our Credential's key
    var pusher = new Pusher('MY_KEY', {
        cluster: 'en',
        encrypted: true
    });

    //Subscribe to the channel we specified in our Laravel Event
    var channel = pusher.subscribe('application');

    //Bind a function to a Event (the full Laravel class)
    channel.bind('App\\Events\\PostMessage', function(){
        console.log('Event Logged');
    });
</script>
</code>```

My Question

Why is my pusher front end code not detecting my private broadcast?

答:
Hehehe I think I found it:
https://pusher.com/docs/client_api_guide/client_private_channels

You need to prefix the channel name with 'private-'. One of the things Echo does automatically for you!

Here's the rest for reference. The final advice still stands and would've at least helped you with debugging this issue ;-)

A few things you want to check when using Pusher without Echo in Laravel:

Make sure you have your cluster set correctly. I just checked my own
dashboard and had mt1 as a cluster. It could be the defaults are
obsolete.

Echo is set up to do a lot of things out of sight. One of those is
converting easy to remember strings to their full namespaced
counterparts when communicating with Pusher. So if you want to skip
Echo, you want to make sure you emulate this behaviour 1 on 1, or
else it will break.

On that last note, it could be that you need to do something like this:

```<code>var channel = pusher.subscribe('App/Events/application');
</code>```

Try copying the docs 1 on 1 as well, adding some code that make the
channel unique. I don't know the internals, but it could be that the
PrivateChannel requires a unique parameter, and doesn't function
without:

Like this:

```<code>public function broadcastOn()
{
    return new PrivateChannel('order.'.$this->update->order_id);
}
</code>```

And then for your channel:

```<code>Broadcast::channel('order.{orderId}', function ($user, $orderId) {
    return $user->id === Order::findOrNew($orderId)->user_id;
});
</code>```

Try using Echo first, to get everything running following the docs. It provides a great layer of convenience. Then break it down from there. At least that way you know you have all the basics down and communications between your app and Pusher are working! :-)

That's all I could think of right now without actually coding it myself! Hope one of them works for you.

Title: Laravel Broadcasting

Body:
My Scenario

Im trying to get laravel to work with pusher without the use of laravel echo, everything works on a public channel but when i switch to a private channel in the broadcastOn() method of my event pusher on the frontend doesn't pick anything up anymore. It gets logged in my pusher applications event log as a private channel but pusher on the frontend just sais no.

I've set up and returned true for the channel code like this:

Broadcast::channel('application', function ($post, $username) {
    if(true){
        return true;
    }
});

This is my event code:

public function broadcastOn()
{
    return new PrivateChannel('application');
}

The class implements ShouldBroadcast and lastly here is my front end code:

My Question

Why is my pusher front end code not detecting my private broadcast?

Body:
Hehehe I think I found it:
https://pusher.com/docs/client_api_guide/client_private_channels

You need to prefix the channel name with 'private-'. One of the things Echo does automatically for you!

Here's the rest for reference. The final advice still stands and would've at least helped you with debugging this issue ;-)

A few things you want to check when using Pusher without Echo in Laravel:

Make sure you have your cluster set correctly. I just checked my own
dashboard and had mt1 as a cluster. It could be the defaults are
obsolete.

Echo is set up to do a lot of things out of sight. One of those is
converting easy to remember strings to their full namespaced
counterparts when communicating with Pusher. So if you want to skip
Echo, you want to make sure you emulate this behaviour 1 on 1, or
else it will break.

On that last note, it could be that you need to do something like this:

var channel = pusher.subscribe('App/Events/application');

Try copying the docs 1 on 1 as well, adding some code that make the
channel unique. I don't know the internals, but it could be that the
PrivateChannel requires a unique parameter, and doesn't function
without:

Like this:

public function broadcastOn()
{
    return new PrivateChannel('order.'.$this->update->order_id);
}

And then for your channel:

Broadcast::channel('order.{orderId}', function ($user, $orderId) {
    return $user->id === Order::findOrNew($orderId)->user_id;
});

Try using Echo first, to get everything running following the docs. It provides a great layer of convenience. Then break it down from there. At least that way you know you have all the basics down and communications between your app and Pusher are working! :-)

That's all I could think of right now without actually coding it myself! Hope one of them works for you.


问:
Unable to load an iframe on my site
I'm inserting an iframe on my webpage with the following code.

```<code><iframe src="[url]" width="400" height="700">
</code>```

But in the browser I only see a blank box. In the browser console I'm seeing the following message.

```<code>Load denied by X-Frame-Options: [url] does not permit cross-origin framing.
</code>```

[url] is an https url. Accessing the [url] directly in the browser is working.

Can anyone tell me why it is not displaying?

答:
Is a security restriction. If you want to be able to insert the iframe in your page, you must tell the owner/admin of the origin site, from where you get the content, to set the X-Frame-Options so that you could share his content

X-Frame-Options: ALLOW-FROM https://example.com/

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options

Title: Unable to load an iframe on my site

Body:
I'm inserting an iframe on my webpage with the following code.

But in the browser I only see a blank box. In the browser console I'm seeing the following message.

Load denied by X-Frame-Options: [url] does not permit cross-origin framing.

[url] is an https url. Accessing the [url] directly in the browser is working.

Can anyone tell me why it is not displaying?


答:
If you are not going to change content of vec, create an std::unordered_set with the same content and search for occurrences there. Searching in an unordered_set is approximately O(1), so this would be a simple win.

The easiest and the most efficient way to construct an unordered_set from a vector is to use the constructor taking two iterators:

```<code>unordered_set<A*> us(vec.begin(), vec.end());
</code>```

Title: Search within a big vector in C++

Body:
If you are not going to change content of vec, create an std::unordered_set<A*> with the same content and search for occurrences there. Searching in an unordered_set is approximately O(1), so this would be a simple win.

The easiest and the most efficient way to construct an unordered_set from a vector is to use the constructor taking two iterators:

unordered_set<A*> us(vec.begin(), vec.end());


问:
How to Transfer with minimum Balance Fee
Hello I'm trying to make my program run so that when you are transferring money a transfer fee of $2.0 is ONLY applied to accounts with a balance less than $10,000.

The issue I am having is that my code is charging me a transfer fee regardless of my balance. If I have a balance of $5,000,000 and I transfer $9,999 dollars it charges me a transfer fee of 2.0.

If I try to transfer > $10,000 there is NO transfer fee. Please spot my error. Thank you so much.

There are 5 classes so i'm going to paste all the relevant information below.

```<code>// CLASS 1
public class AccountConstants {
private final double CHECKING_BALANCE_THRESHOLD = 10000;
private final double TRANSFER_FEE = 2.0;

public double getFee(double amount){
    if (amount < CHECKING_BALANCE_THRESHOLD){
        return TRANSFER_FEE;
    }
    return 0.0;
}

public class CheckingAccount extends Account{
public CheckingAccount(String number, String name, GregorianCalendar
openDate, double balance){
    super(number,name,openDate,balance);
}

//CLASS 2
    @override
    public int transferTo(Account account, double amount) {
    AccountConstants ac = new AccountConstants();
    double fee = ac.getFee(amount);
    if (this.getBalance() < amount)
        return -2;
    else if (this.getBalance() < (amount+fee))
        return -1;
    else if (this.getBalance()>=(amount+fee)&& fee==2.0){
       this.setBalance(-(amount+fee));
       account.setBalance(amount);
       return 1;
    }
    else
        this.setBalance(-amount);
        account.setBalance(amount);
        return 0;
}

//CLASS 3
if (result == 0)
{
    au.setBalance(jComboBox1.getSelectedIndex(),
    accounts.getBalance());
    au.setBalance(index, accounts_to.getBalance());
    NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
    txtBalance.setText(defaultFormat.format(accounts.getBalance()));
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index),
    au.getCustomerName(index), au.getBalance(index));
    index = jComboBox1.getSelectedIndex();
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index), au.getCustomerName(index), au.getBalance(index));
    JOptionPane.showMessageDialog(this, defaultFormat.format(amount)+" was transfered to "+accountNumber,"Transfer successful", JOptionPane.INFORMATION_MESSAGE);
}

else if (result == 1)
{
    au.setBalance(jComboBox1.getSelectedIndex(), accounts.getBalance());
    au.setBalance(index, accounts_to.getBalance());
    NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
    txtBalance.setText(defaultFormat.format(accounts.getBalance()));
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index),au.getCustomerName(index), au.getBalance(index));
    index = jComboBox1.getSelectedIndex();
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index), au.getCustomerName(index), au.getBalance(index));
    JOptionPane.showMessageDialog(this, defaultFormat.format(amount)+" was transfered to "+accountNumber+"\n$2.0 transfer fee was applied", "Transfer successful", JOptionPane.INFORMATION_MESSAGE);
}
</code>```

答:
You are sending the amount to the getFee function instead of the balance.

Change:

```<code>double fee = ac.getFee(amount);
</code>```

To:

```<code>double fee = ac.getFee(this.getBalance());
</code>```

Also this is bad:

```<code>else if (this.getBalance()>=(amount+fee)&& fee==2.0){
</code>```

You should change it to:

```<code>else if (this.getBalance()>=(amount+fee)&& fee==TRANSFER_FEE){
</code>```

Or even better:

```<code>else if (this.getBalance()>=(amount+fee)&& fee > 0.0){
</code>```

Body:
Hello I'm trying to make my program run so that when you are transferring money a transfer fee of $2.0 is ONLY applied to accounts with a balance less than $10,000.

The issue I am having is that my code is charging me a transfer fee regardless of my balance. If I have a balance of $5,000,000 and I transfer $9,999 dollars it charges me a transfer fee of 2.0.

If I try to transfer > $10,000 there is NO transfer fee. Please spot my error. Thank you so much.

There are 5 classes so i'm going to paste all the relevant information below.

// CLASS 1
public class AccountConstants {
private final double CHECKING_BALANCE_THRESHOLD = 10000;
private final double TRANSFER_FEE = 2.0;

public double getFee(double amount){
    if (amount < CHECKING_BALANCE_THRESHOLD){
        return TRANSFER_FEE;
    }
    return 0.0;
}

public class CheckingAccount extends Account{
public CheckingAccount(String number, String name, GregorianCalendar
openDate, double balance){
    super(number,name,openDate,balance);
}

//CLASS 2
    @override
    public int transferTo(Account account, double amount) {
    AccountConstants ac = new AccountConstants();
    double fee = ac.getFee(amount);
    if (this.getBalance() < amount)
        return -2;
    else if (this.getBalance() < (amount+fee))
        return -1;
    else if (this.getBalance()>=(amount+fee)&& fee==2.0){
       this.setBalance(-(amount+fee));
       account.setBalance(amount);
       return 1;
    }
    else
        this.setBalance(-amount);
        account.setBalance(amount);
        return 0;
}

//CLASS 3
if (result == 0)
{
    au.setBalance(jComboBox1.getSelectedIndex(),
    accounts.getBalance());
    au.setBalance(index, accounts_to.getBalance());
    NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
    txtBalance.setText(defaultFormat.format(accounts.getBalance()));
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index),
    au.getCustomerName(index), au.getBalance(index));
    index = jComboBox1.getSelectedIndex();
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index), au.getCustomerName(index), au.getBalance(index));
    JOptionPane.showMessageDialog(this, defaultFormat.format(amount)+" was transfered to "+accountNumber,"Transfer successful", JOptionPane.INFORMATION_MESSAGE);
}

else if (result == 1)
{
    au.setBalance(jComboBox1.getSelectedIndex(), accounts.getBalance());
    au.setBalance(index, accounts_to.getBalance());
    NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
    txtBalance.setText(defaultFormat.format(accounts.getBalance()));
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index),au.getCustomerName(index), au.getBalance(index));
    index = jComboBox1.getSelectedIndex();
    au.updateFile(au.getAccountNumber(index), au.getOpenDate(index), au.getCustomerName(index), au.getBalance(index));
    JOptionPane.showMessageDialog(this, defaultFormat.format(amount)+" was transfered to "+accountNumber+"\n$2.0 transfer fee was applied", "Transfer successful", JOptionPane.INFORMATION_MESSAGE);
}

Body:
You are sending the amount to the getFee function instead of the balance.

Change:

double fee = ac.getFee(amount);

To:

double fee = ac.getFee(this.getBalance());

Also this is bad:

else if (this.getBalance()>=(amount+fee)&& fee==2.0){

You should change it to:

else if (this.getBalance()>=(amount+fee)&& fee==TRANSFER_FEE){

Or even better:

else if (this.getBalance()>=(amount+fee)&& fee > 0.0){


问:
mkdir throws 'unknown option' error
I have a problem with mkdir command.
When I run mkdir -p "-AFolder", I am getting the following error:

```<code>mkdir: unknown option -- A
</code>```

What's is causing the error?

答:
The mkdir command tries to interpret "-AFolder/" as an option as it begins with a -.

Use the -- dummy argument to tell explicitly that you are not providing an option :

```<code>mkdir -- -AFolder
</code>```

From the Bash manpage:

Unless  otherwise  noted,  each builtin command documented in this
  section as accepting options preceded by - accepts -- to signify the
  end of the options.

Title: mkdir throws 'unknown option' error

Body:
I have a problem with mkdir command.
When I run mkdir -p "-AFolder", I am getting the following error:

mkdir: unknown option -- A

What's is causing the error?

Body:
The mkdir command tries to interpret "-AFolder/" as an option as it begins with a -.

Use the -- dummy argument to tell explicitly that you are not providing an option :

mkdir -- -AFolder

From the Bash manpage:

Unless  otherwise  noted,  each builtin command documented in this
  section as accepting options preceded by - accepts -- to signify the
  end of the options.


问:
PowerShell two parameters either of them can be null but not both null
I'm wondering if this can be done at the parameter level rather in code:
I have 2 parameter: $School and $Class

```<code>Get-Students -School SchooName # Will give me all Students name in all classes in that School
Get-Students -Class ClassName  # Will give me all Students name in that Class across all schools
Get-Students                   # Should return parameter level error.
</code>```

I tried to use following:

```<code>function Get-Students{
param(
    [parameter(ParameterSetName="School no null")]
    [ValidateNotNullOrEmpty()]
    [string]$School,
    [parameter(ParameterSetName="School no null")]
    [AllowNull()]
    [string]$Class,
    [parameter(ParameterSetName="Class no null")]
    [AllowNull()]
    [string]$School,
    [parameter(ParameterSetName="Class no null")]
    [ValidateNotNullOrEmpty()]
    [string]$Class
)
}
</code>```

But it doesn't work in this way...

Hope I explained this correctly. Or if there is no way can do this from parameter only inside of the code?

Thanks
River

答:
Updated. The following commented code snippet is based on Add a parameter to multiple Parameter Sets article. Allows supplying -Class or -School parameter or  both of them all together.

```<code>function Get-Students{
param(
    [parameter(Mandatory=$false)][switch]$SomeThing, # any type instead of [switch]
    # ↑↑↑ parameter(s) in all Parameter Sets

    [parameter(Mandatory=$true,  ParameterSetName="School No Null")]
    [parameter(Mandatory=$true,  ParameterSetName="Class And School")]
    [ValidateNotNullOrEmpty()]
    [string]$School,

    [parameter(Mandatory=$true,  ParameterSetName="Class No Null")]
    [parameter(Mandatory=$true,  ParameterSetName="Class And School")]
    [ValidateNotNullOrEmpty()]
    [string]$Class
)
    Write-Host $PsCmdlet.ParameterSetName -ForegroundColor Cyan
    switch ($PsCmdlet.ParameterSetName)
    {
        "School No Null"   { "$School/*,$($SomeThing.IsPresent)"; break}
        "Class No Null"    { "*/$Class,$($SomeThing.IsPresent)";  break}
        "Class And School" { "$School/$Class,$($SomeThing.IsPresent)";  break}
    }
}
Get-Students -Class "A"
Get-Students -School "West" -SomeThing
Get-Students -Class "A" -School "West"

### errors raised:
#   Get-Students
### Parameter set cannot be resolved using the specified named parameters.
### + FullyQualifiedErrorId : AmbiguousParameterSet,Get-Students
#   Get-Students -Class ""
#   Get-Students -School ""
### Cannot validate argument on parameter '…'. The argument is null or empty.
### + FullyQualifiedErrorId : ParameterArgumentValidationError,Get-Students
</code>```

Original answer (a code snippet based on PowerShell V2: ParameterSets article from PowerShell Team Blog and on MSDN help article) does not allow supplying both -Class and -School parameters all together:

```<code>function Get-Students{
param(
 [parameter(Mandatory=$true,  ParameterSetName="School No Null")][ValidateNotNullOrEmpty()]
 [parameter(Mandatory=$false, ParameterSetName="Class No Null")] #[AllowNull()]
 [string]$School,

 [parameter(Mandatory=$true,  ParameterSetName="Class No Null")] [ValidateNotNullOrEmpty()]
 [parameter(Mandatory=$false, ParameterSetName="School No Null")]#[AllowNull()]
 [string]$Class
)
    Write-Host $PsCmdlet.ParameterSetName -ForegroundColor Cyan
    switch ($PsCmdlet.ParameterSetName)
    {
        "School No Null" { $School; break}
        "Class No Null"  { $Class;  break}
    }
}

### valid calls:

Get-Students -Class "A"
Get-Students -School "West"

### errors raised:
### Parameter set cannot be resolved using the specified named parameters.
# Get-Students
# Get-Students -Class "A" -School "West"
### The argument is null or empty.
# Get-Students -Class ""
# Get-Students -School ""
</code>```

Body:
I'm wondering if this can be done at the parameter level rather in code:
I have 2 parameter: $School and $Class

Get-Students -School SchooName # Will give me all Students name in all classes in that School
Get-Students -Class ClassName  # Will give me all Students name in that Class across all schools
Get-Students                   # Should return parameter level error.

I tried to use following:

function Get-Students{
param(
    [parameter(ParameterSetName="School no null")]
    [ValidateNotNullOrEmpty()]
    [string]$School,
    [parameter(ParameterSetName="School no null")]
    [AllowNull()]
    [string]$Class,
    [parameter(ParameterSetName="Class no null")]
    [AllowNull()]
    [string]$School,
    [parameter(ParameterSetName="Class no null")]
    [ValidateNotNullOrEmpty()]
    [string]$Class
)
}

But it doesn't work in this way...

Hope I explained this correctly. Or if there is no way can do this from parameter only inside of the code?

Thanks
River

Body:
Updated. The following commented code snippet is based on Add a parameter to multiple Parameter Sets article. Allows supplying -Class or -School parameter or  both of them all together.

function Get-Students{
param(
    [parameter(Mandatory=$false)][switch]$SomeThing, # any type instead of [switch]
    # ↑↑↑ parameter(s) in all Parameter Sets

    [parameter(Mandatory=$true,  ParameterSetName="School No Null")]
    [parameter(Mandatory=$true,  ParameterSetName="Class And School")]
    [ValidateNotNullOrEmpty()]
    [string]$School,

    [parameter(Mandatory=$true,  ParameterSetName="Class No Null")]
    [parameter(Mandatory=$true,  ParameterSetName="Class And School")]
    [ValidateNotNullOrEmpty()]
    [string]$Class
)
    Write-Host $PsCmdlet.ParameterSetName -ForegroundColor Cyan
    switch ($PsCmdlet.ParameterSetName)
    {
        "School No Null"   { "$School/*,$($SomeThing.IsPresent)"; break}
        "Class No Null"    { "*/$Class,$($SomeThing.IsPresent)";  break}
        "Class And School" { "$School/$Class,$($SomeThing.IsPresent)";  break}
    }
}
Get-Students -Class "A"
Get-Students -School "West" -SomeThing
Get-Students -Class "A" -School "West"

### errors raised:
#   Get-Students
### Parameter set cannot be resolved using the specified named parameters.
### + FullyQualifiedErrorId : AmbiguousParameterSet,Get-Students
#   Get-Students -Class ""
#   Get-Students -School ""
### Cannot validate argument on parameter '…'. The argument is null or empty.
### + FullyQualifiedErrorId : ParameterArgumentValidationError,Get-Students

Original answer (a code snippet based on PowerShell V2: ParameterSets article from PowerShell Team Blog and on MSDN help article) does not allow supplying both -Class and -School parameters all together:

function Get-Students{
param(
 [parameter(Mandatory=$true,  ParameterSetName="School No Null")][ValidateNotNullOrEmpty()]
 [parameter(Mandatory=$false, ParameterSetName="Class No Null")] #[AllowNull()]
 [string]$School,

 [parameter(Mandatory=$true,  ParameterSetName="Class No Null")] [ValidateNotNullOrEmpty()]
 [parameter(Mandatory=$false, ParameterSetName="School No Null")]#[AllowNull()]
 [string]$Class
)
    Write-Host $PsCmdlet.ParameterSetName -ForegroundColor Cyan
    switch ($PsCmdlet.ParameterSetName)
    {
        "School No Null" { $School; break}
        "Class No Null"  { $Class;  break}
    }
}

### valid calls:

Get-Students -Class "A"
Get-Students -School "West"

### errors raised:
### Parameter set cannot be resolved using the specified named parameters.
# Get-Students
# Get-Students -Class "A" -School "West"
### The argument is null or empty.
# Get-Students -Class ""
# Get-Students -School ""


问:
Missing certain GCDA files after test execution
I'm currently facing an issue with generating .gcda files for coverage data of a static library. I can get coverage data for most files, but not all.

I'll refer to the object file with the missing coverage data as X.

Some things to note:

I have compiled the library and test executable with the appropriate flags.

The .gcno files are generated for all objects, including X.

The .gcda files are generated for MOST objects, excepting X.

The symbol dump of X's object file has the gcov symbols present in its disassembly.

When running a test that uses X, .gcda files are generated for other files, just not X.

What could be happening that prevents a single .gcda file from being generated?

-

Operating System: OS X  10.12

LLVM Compiler Version:  8.0.0

答:
I think you might need your kernel enable for gcov.

Enable CONFIG_DEBUG_FS, CONFIG_GCOV_KERNEL, CONFIG_GCOV_FORMAT_AUTODETECT and CONFIG_GCOV_PROFILE_ALL

and the gcda file for static lib will be under /sys/kernel/debug/gcov/


答:
```<code>mkdir -p  -- "-AFolder"
</code>```

Use -- to tell the bash command that anything that follows is not a flag, its a part of the argument. From man bage:

--        A -- signals the end of options and disables further option
  processing.  Any arguments after the -- are treated as filenames and
  argu-
                   ments.  An argument of - is equivalent to --.

Title: mkdir throws 'unknown option' error

Body:
mkdir -p  -- "-AFolder"

Use -- to tell the bash command that anything that follows is not a flag, its a part of the argument. From man bage:

--        A -- signals the end of options and disables further option
  processing.  Any arguments after the -- are treated as filenames and
  argu-
                   ments.  An argument of - is equivalent to --.


问:
Control axis size matplotlib pyplot
I can't find a way to control the alignment of points in matplotlib.pyplot in order to more properly center samples within a window. Below is an example where I am plotting two averaged samples with stdev and instead of being uniformly spaced within the window, they are pushed off onto the edges of the plot.

Is there a way to better control this alignment? My code is below for reference.

```<code>plt.clf()
plt.errorbar(np.arange(len(rmean)),rmean,yerr=rstddev, linestyle="None", fmt='o')
plt.xlabel('Probes', fontsize=1)
plt.ylabel('VAF')
plt.title('Average VAF Along Probed Regions')
plt.tight_layout()
plt.xticks(np.arange(len(rmean)),labels,rotation='90')
plt.tight_layout()
plt.show()
</code>```

答:
You may manually set the limits on the xaxis to give more space. Here you have values of 0 and 1 on the axis, so setting e.g. plt.xlim(-2,3) gives you some more space.

You could also automatically assign some proportion of the axes to be left free, e.g. to get 50% margin, you'd do

```<code>plt.margins(x=0.5)
</code>```

Title: Control axis size matplotlib pyplot

Body:
I can't find a way to control the alignment of points in matplotlib.pyplot in order to more properly center samples within a window. Below is an example where I am plotting two averaged samples with stdev and instead of being uniformly spaced within the window, they are pushed off onto the edges of the plot.

Is there a way to better control this alignment? My code is below for reference.

plt.clf()
plt.errorbar(np.arange(len(rmean)),rmean,yerr=rstddev, linestyle="None", fmt='o')
plt.xlabel('Probes', fontsize=1)
plt.ylabel('VAF')
plt.title('Average VAF Along Probed Regions')
plt.tight_layout()
plt.xticks(np.arange(len(rmean)),labels,rotation='90')
plt.tight_layout()
plt.show()

Body:
You may manually set the limits on the xaxis to give more space. Here you have values of 0 and 1 on the axis, so setting e.g. plt.xlim(-2,3) gives you some more space.

You could also automatically assign some proportion of the axes to be left free, e.g. to get 50% margin, you'd do

plt.margins(x=0.5)


问:
Can I use with clause while opening a CURSOR
Can I use WITH clause while using cursor </p>

```<code>OPEN CURSOR_NAME FOR
WITH view1 as (Select v_name from tablename),
view2 as (Select p_name from tablename2)
Select * from view1, view2;
</code>```

答:
Yes it is possible to use with clause in cursor. Check the below example.

```<code>DECLARE
   l_cur sys_refcursor;
   l_val VARCHAR2 (1000);
BEGIN
   DBMS_OUTPUT.ENABLE;

   OPEN l_cur FOR
      WITH tab AS
           (SELECT 'hello'
              FROM DUAL)
      SELECT *
        FROM tab;

   FETCH l_cur
    INTO l_val;

   CLOSE l_cur;

   DBMS_OUTPUT.put_line (l_val);
END;
</code>```

Output: hello

Body:
Can I use WITH clause while using cursor

OPEN CURSOR_NAME FOR
WITH view1 as (Select v_name from tablename),
view2 as (Select p_name from tablename2)
Select * from view1, view2;

Body:
Yes it is possible to use with clause in cursor. Check the below example.

DECLARE
   l_cur sys_refcursor;
   l_val VARCHAR2 (1000);
BEGIN
   DBMS_OUTPUT.ENABLE;

   OPEN l_cur FOR
      WITH tab AS
           (SELECT 'hello'
              FROM DUAL)
      SELECT *
        FROM tab;

   FETCH l_cur
    INTO l_val;

   CLOSE l_cur;

   DBMS_OUTPUT.put_line (l_val);
END;

Output: hello


问:
Spring-boot jackson error on Maven with war file, but not jar file with com.fasterxml.jackson.core.JsonFactory.requiresPropertyOrdering()Z
I have a very weird problem with Spring-boot 1.5.2 build with Maven to war package which it has error with Jackson dependency, only on Ubuntu 16.04 as I'm using another Centos 7 and no problem with starting application as war or jar file.

After building with Maven to jar or war, I can run built package with

```<code>javar -jar target/project.war (or project.jar)
</code>```

and Embedded Tomcat will start. Also the war package could be deployed to an external Tomcat in webapps directory of Centos 7. For Ubuntu 16.04, I could only run .jar file with Tomcat embedded but not war file with Tomcat Embedded/External.

```<code>Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.filter.OrderedHttpPutFormContentFilter]: Factory method 'httpPutFormContentFilter' threw exception; nested exception is java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonFactory.requiresPropertyOrdering()Z
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 26 more
Caused by: java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonFactory.requiresPropertyOrdering()Z
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:564)
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:474)
    at org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.build(Jackson2ObjectMapperBuilder.java:588)
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.<init>(MappingJackson2HttpMessageConverter.java:57)
    at org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter.<init>(AllEncompassingFormHttpMessageConverter.java:61)
    at org.springframework.web.filter.HttpPutFormContentFilter.<init>(HttpPutFormContentFilter.java:63)
    at org.springframework.boot.web.filter.OrderedHttpPutFormContentFilter.<init>(OrderedHttpPutFormContentFilter.java:29)
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.httpPutFormContentFilter(WebMvcAutoConfiguration.java:142)
</code>```

Here is the pom file https://pastebin.com/13MwTm89 which I only add another dependency from Jackson for deserializing XML to object.

```<code> <dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.8.7</version>
</dependency>
</code>```

here is the full dependencies for Jackson

```<code>mvn dependency:tree | grep 'jackson'
[INFO] +- com.fasterxml.jackson.dataformat:jackson-dataformat-xml:jar:2.8.7:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-core:jar:2.8.7:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.8.0:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.8.7:compile
[INFO] |  +- com.fasterxml.jackson.module:jackson-module-jaxb-annotations:jar:2.8.7:compile
</code>```

答:
I finally found the problem after trying to comment out each dependency individually in pom.xml, it is due to a fasterxml from very old version in an internally project which is generated to jar file and I included in pom.xml of main project.

The internal project contains some dependencies and I think one of them contains this old jackson-core library, I think it is grpc or protobuf.

```<code><dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-all</artifactId>
            <version>0.12.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>3.0.0-beta-1</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
</code>```

Somehow in Ubuntu 16.04, Maven 3.3.9 prefer this jackson-core instead of newest version from Spring boot or specified directly in pom.xml.

It does not happen when in Centos 7 with Maven 3.5.0 when it runs without problem with Jackson as it used the newest dependency.

Body:
I have a very weird problem with Spring-boot 1.5.2 build with Maven to war package which it has error with Jackson dependency, only on Ubuntu 16.04 as I'm using another Centos 7 and no problem with starting application as war or jar file.

After building with Maven to jar or war, I can run built package with

javar -jar target/project.war (or project.jar)

and Embedded Tomcat will start. Also the war package could be deployed to an external Tomcat in webapps directory of Centos 7. For Ubuntu 16.04, I could only run .jar file with Tomcat embedded but not war file with Tomcat Embedded/External.

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.filter.OrderedHttpPutFormContentFilter]: Factory method 'httpPutFormContentFilter' threw exception; nested exception is java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonFactory.requiresPropertyOrdering()Z
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 26 more
Caused by: java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonFactory.requiresPropertyOrdering()Z
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:564)
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:474)
    at org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.build(Jackson2ObjectMapperBuilder.java:588)
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.<init>(MappingJackson2HttpMessageConverter.java:57)
    at org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter.<init>(AllEncompassingFormHttpMessageConverter.java:61)
    at org.springframework.web.filter.HttpPutFormContentFilter.<init>(HttpPutFormContentFilter.java:63)
    at org.springframework.boot.web.filter.OrderedHttpPutFormContentFilter.<init>(OrderedHttpPutFormContentFilter.java:29)
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.httpPutFormContentFilter(WebMvcAutoConfiguration.java:142)

Here is the pom file https://pastebin.com/13MwTm89 which I only add another dependency from Jackson for deserializing XML to object.

 <dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.8.7</version>
</dependency>

here is the full dependencies for Jackson

mvn dependency:tree | grep 'jackson'
[INFO] +- com.fasterxml.jackson.dataformat:jackson-dataformat-xml:jar:2.8.7:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-core:jar:2.8.7:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.8.0:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.8.7:compile
[INFO] |  +- com.fasterxml.jackson.module:jackson-module-jaxb-annotations:jar:2.8.7:compile

Body:
I finally found the problem after trying to comment out each dependency individually in pom.xml, it is due to a fasterxml from very old version in an internally project which is generated to jar file and I included in pom.xml of main project.

The internal project contains some dependencies and I think one of them contains this old jackson-core library, I think it is grpc or protobuf.

<dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-all</artifactId>
            <version>0.12.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>3.0.0-beta-1</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

Somehow in Ubuntu 16.04, Maven 3.3.9 prefer this jackson-core instead of newest version from Spring boot or specified directly in pom.xml.

It does not happen when in Centos 7 with Maven 3.5.0 when it runs without problem with Jackson as it used the newest dependency.


问:
opengl topdown<->bottomup textures?
When i load an image via FreeImage, the bits are bottom to top.
My GL code expects all images to be topdown. Whats the best way to flip the image when i copy the bits to the texture?</p>

答:
I think it's wise to do an in-place flip using simple array arithmetic and 1 temporary longword value. (so flip per pixel, 4 bytes).

You could of course flip texture coords but that would be unwise IMHO, as you probably don't want to pollute your code with the info that the texture is upside down.

ContentLicense: CC BY-SA 2.5

Title: opengl topdown<->bottomup textures?

OwnerDisplayName: Frans Bouma


问:
2D openGL drawing lines that don't exactly fit pixel raster
I'm drawing something similar to a LED VU meter in OpenGL. Result should be like on vertical bar of this:

Unfortunately, my drawing space is restricted, and I have to fit exactly 18 bars on it. That yields a spacing between bars of 3.6 pixels.

When drawn, this causes visible differences in the gaps between lines, because the gaps are either 2 or 1 pixel wide. I'm looking for a solution to use subpixel rendering and than "fake" the lines by some kind of anti-aliasing, so that all gaps appear of the same width.

This is my code so far

```<code>glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH, GL_NICEST);
for (int i = 0; i < 18; ++i) {
            float bBottom = barBottom + i*3.6f;
            glBegin(GL_LINES);
            glLineWidth(2);
            glVertex2f(bRight,bBottom);
            glVertex2f(bLeft,bBottom);
            glEnd();
}
glDisable(GL_LINE_SMOOTH);
</code>```

Unfortunately, turning on line smoothing showed no visible effect. Any suggestions?

答:
Two ideas:

Draw all the bars to a large off screen texture such that the gaps and widths are all equal and then use bilinear filtering to blit the result to the required screen position and size.

Get an artist to draw all the fully lit bars so that the look good, then draw black rectangles with an alpha channel from the top of each bar downwards to darken the required parts of the image.

Body:
I'm drawing something similar to a LED VU meter in OpenGL. Result should be like on vertical bar of this:

Unfortunately, my drawing space is restricted, and I have to fit exactly 18 bars on it. That yields a spacing between bars of 3.6 pixels.

When drawn, this causes visible differences in the gaps between lines, because the gaps are either 2 or 1 pixel wide. I'm looking for a solution to use subpixel rendering and than "fake" the lines by some kind of anti-aliasing, so that all gaps appear of the same width.

This is my code so far

glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH, GL_NICEST);
for (int i = 0; i < 18; ++i) {
            float bBottom = barBottom + i*3.6f;
            glBegin(GL_LINES);
            glLineWidth(2);
            glVertex2f(bRight,bBottom);
            glVertex2f(bLeft,bBottom);
            glEnd();
}
glDisable(GL_LINE_SMOOTH);

Unfortunately, turning on line smoothing showed no visible effect. Any suggestions?