问:
mobx contenful simple api call
I have a basic react app (CRA) with mobx and I simply would like to get all the entries of a contentful space.

with a simple store I can see my entries in the react console but I can't find a way to display it in my component.

```<code>class ProjetsStore {

@observable projets = {}

@action fetchAll(){
window.fetch(`${API_BASE_URL}/spaces/${API_SPACE_ID}/entries?
access_token=${API_KEY}&content_type=projet`)
.then(res => res.json())
.then(prj => this.projets = prj)
</code>```

The component is quite basic actually but whatever I try, I can't find a way to simply display anything even if everything is present in this.props.projetsStore in react tool.

```<code>@inject(['projetsStore'])
@observer

class Projets extends Component {

componentDidMount() {
  this.props.projetsStore.fetchAll()
}

render() {
  return (
    <div>
       ...
    </div>
)
}
}
</code>```

If someone can point me to some direction or ressource to simply fetch data from an api with mobx and make it dispo as props via provider, that would be awesome.

Thanks.

答:
I'm not familiar with mobx and I'm not sure how you how the store works but I believe you have to set the data on the component itself, or?</p>

```<code>@inject(['projetsStore'])
@observer

class Projets extends Component {

componentDidMount() {
  this.props.projetsStore.fetchAll()
    .then(data => this.setState({data})
}
</code>```

Title: mobx contenful simple api call

Body:
I have a basic react app (CRA) with mobx and I simply would like to get all the entries of a contentful space.

with a simple store I can see my entries in the react console but I can't find a way to display it in my component.

class ProjetsStore {

@observable projets = {}

@action fetchAll(){
window.fetch(`${API_BASE_URL}/spaces/${API_SPACE_ID}/entries?
access_token=${API_KEY}&content_type=projet`)
.then(res => res.json())
.then(prj => this.projets = prj)

The component is quite basic actually but whatever I try, I can't find a way to simply display anything even if everything is present in this.props.projetsStore in react tool.

@inject(['projetsStore'])
@observer

class Projets extends Component {

componentDidMount() {
  this.props.projetsStore.fetchAll()
}

render() {
  return (

       ...

)
}
}

If someone can point me to some direction or ressource to simply fetch data from an api with mobx and make it dispo as props via provider, that would be awesome.

Thanks.

Body:
I'm not familiar with mobx and I'm not sure how you how the store works but I believe you have to set the data on the component itself, or?

@inject(['projetsStore'])
@observer

class Projets extends Component {

componentDidMount() {
  this.props.projetsStore.fetchAll()
    .then(data => this.setState({data})
}


来源: stackexchange

问:
c# get list of users that have a specific foreign key
I have a many to many relationship between Users and Roles as a user can have many roles and a role can be associated to many users.

As role titles I have guest (id 1) and normalUser(id 2)

I am trying to get all the normalUser that there are in the database but I do not want the guests because i have to set permissions as required

this is my code so far

```<code>    public List<User> GetnormalUsers()
    {
        return Entity.Users.Where(x => x.Roles.Contains(2).ToList());
    }
</code>```

this is giving me an error stating that I cannot convert from 'int' to 'Common.Role'.

How should I fix this?

答:
From the given partial data I would try

```<code>return Entity.Users.Where(user => user.Roles.Any(role => role.Id == 2)).ToList();
</code>```

Two problems where in your statement:

You simply had the closing bracket for the .ToList() statement on the wrong position, materializing the wrong collection.

.Contains() doesn't work that way. Instead you have to use .Any().

ContentLicense: CC BY-SA 3.0

Body:
I have a many to many relationship between Users and Roles as a user can have many roles and a role can be associated to many users.

As role titles I have guest (id 1) and normalUser(id 2)

I am trying to get all the normalUser that there are in the database but I do not want the guests because i have to set permissions as required

this is my code so far

    public List<User> GetnormalUsers()
    {
        return Entity.Users.Where(x => x.Roles.Contains(2).ToList());
    }

this is giving me an error stating that I cannot convert from 'int' to 'Common.Role'.

How should I fix this?

Body:
From the given partial data I would try

return Entity.Users.Where(user => user.Roles.Any(role => role.Id == 2)).ToList();

Two problems where in your statement:

You simply had the closing bracket for the .ToList() statement on the wrong position, materializing the wrong collection.

.Contains() doesn't work that way. Instead you have to use .Any().


答:
Two things: you need to access the Id (presumably) property of Roles in order for your filter to work, and your .ToList() is in the wrong position.</p>

```<code>public List<User> GetnormalUsers()
{
        return Entity.Users.Where(x => x.Roles.Any(y => y.Id == 2)).ToList();
}
</code>```

Title: c# get list of users that have a specific foreign key

Body:
Two things: you need to access the Id (presumably) property of Roles in order for your filter to work, and your .ToList() is in the wrong position.

public List<User> GetnormalUsers()
{
        return Entity.Users.Where(x => x.Roles.Any(y => y.Id == 2)).ToList();
}


问:
How to tidy multiple pairwise.t.tests in R with broom
I am wondering how to tidy the following:

First I gather a selection of columns into a tibble with three columns: strain (=grouping factor), params (names of parameters) and values (the actual values)

```<code>sel <- t_tcellact %>% select(strain, contains("nbr_")) %>% gather(params, values, nbr_DP:nbr_CD3p)
</code>```

Then I perform multiple pairwise.t.test():

```<code> test2 <- sel %>% bind_rows(sel) %>% split(.$params) %>% map(~ pairwise.t.test(x=.$values, g=.$strain, p.adj = "none"))
</code>```

And the result is a list of the results from the pairwise.t.tests which I can start cleaning with:

```<code>test3 <- lapply(test2, tidy)
</code>```

The list looks now like that:

```<code>$nbr_CD3p

group1 group2        p.value

1    SKG Balb/c 0.000001849548

$nbr_DN_CD69nCD25n

group1 group2   p.value

1    SKG Balb/c 0.6295371
</code>```

and so on....

From this I need a tibble with following columns: parameter (e.g. nbr_CD3p), group1, group2, p.value.

In this example I had only two groups, but I want to do it in a generic way also applicable when I have multiple groups.

Does anybody have an idea how to get to this point in an elegant way (without a loop)?

答:
You should be able to use bind_rows(), taking advantage of the .id argument:

```<code>test3 <- lapply(test2, tidy) %>%
     bind_rows(.id = 'parameter')
</code>```

That will use the names of test2 as a new column named parameter in the data frame. All that said, replacing lapply with map_df() as aosmith suggested in a comment above should also work.

Body:
I am wondering how to tidy the following:

First I gather a selection of columns into a tibble with three columns: strain (=grouping factor), params (names of parameters) and values (the actual values)

sel <- t_tcellact %>% select(strain, contains("nbr_")) %>% gather(params, values, nbr_DP:nbr_CD3p)

Then I perform multiple pairwise.t.test():

 test2 <- sel %>% bind_rows(sel) %>% split(.$params) %>% map(~ pairwise.t.test(x=.$values, g=.$strain, p.adj = "none"))

And the result is a list of the results from the pairwise.t.tests which I can start cleaning with:

test3 <- lapply(test2, tidy)

The list looks now like that:

$nbr_CD3p

group1 group2        p.value

1    SKG Balb/c 0.000001849548

$nbr_DN_CD69nCD25n

group1 group2   p.value

1    SKG Balb/c 0.6295371

and so on....

From this I need a tibble with following columns: parameter (e.g. nbr_CD3p), group1, group2, p.value.

In this example I had only two groups, but I want to do it in a generic way also applicable when I have multiple groups.

Does anybody have an idea how to get to this point in an elegant way (without a loop)?

Body:
You should be able to use bind_rows(), taking advantage of the .id argument:

test3 <- lapply(test2, tidy) %>%
     bind_rows(.id = 'parameter')

That will use the names of test2 as a new column named parameter in the data frame. All that said, replacing lapply with map_df() as aosmith suggested in a comment above should also work.


问:
Overriding `Comparison method violates its general contract` exception
I have a comparator like this:

```<code>lazy val seq = mapping.toSeq.sortWith { case ((_, set1), (_, set2)) =>
  // Just propose all the most connected nodes first to the users
  // But also allow less connected nodes to pop out sometimes
  val popOutChance = random.nextDouble <= 0.1D && set2.size > 5
  if (popOutChance) set1.size < set2.size else set1.size > set2.size
}
</code>```

It is my intention to compare sets sizes such that smaller sets may appear higher in a sorted list with 10% chance.

But compiler does not let me do that and throws an Exception: java.lang.IllegalArgumentException: Comparison method violates its general contract! once I try to use it in runtime. How can I override it?

答:
I think the problem here is that, every time two elements are compared, the outcome is random, thus violating the transitive property required of a comparator function in any sorting algorithm.

For example, let's say that some instance a compares as less than b, and then b compares as less than c. These results should imply that a compares as less than c. However, since your comparisons are stochastic, you can't guarantee that outcome. In fact, you can't even guarantee that a will be less than b next time they're compared.

So don't do that. No sort algorithm can handle it. (Such an approach also violates the referential transparency principle of functional programming and will make your program much harder to reason about.)

Instead, what you need to do is to decorate your map's members with a randomly assigned weighting - before attempting to sort them - so that they can be sorted consistently. However, since this happens at the start of a sort operation, the result of the sort will be different each time, which I think is what you're looking for.

It's not clear what type mapping has in your example, but it appears to be something like: Map[Any, Set[_]]. (You can replace the types as required - it's not that important to this approach. For example, say mapping actually has the type Map[String, Set[SomeClass]], then you would replace references below to Any with String and Set[_] to Set[SomeClass].)

First, we'll create a case class that we'll use to score and compare the map elements. Then we'll map the contents of mapping to a sequence of elements of this case class. Next, we sort those elements. Finally, we extract the tuple from the decorated class. The result should look something like this:

```<code>final case class Decorated(x: (Any, Set[_]), rand: Double = random.nextDouble)
extends Ordered[Decorated] {

  // Calculate a rank for this element. You'll need to change this to suit your precise
  // requirements. Here, if rand is less than 0.1 (a 10% chance), I'm adding 5 to the size;
  // otherwise, I'll report the actual size. This allows transitive comparisons, since
  // rand doesn't change once defined. Values are negated so bigger sets come to the fore
  // when sorted.
  private def rank: Int = {
    if(rand < 0.1) -(x._2.size + 5)
    else -x._2.size
  }

  // Compare this element with another, by their ranks.
  override def compare(that: Decorated): Int = rank.compare(that.rank)
}

// Now sort your mapping elements as follows and convert back to tuples.
lazy val seq = mapping.map(x => Decorated(x)).toSeq.sorted.map(_.x)
</code>```

This should put the elements with larger sets towards the front, but there's 10% chance that sets appear 5 bigger and so move up the list. The result will be different each time the last line is re-executed, since map will create new random values for each element. However, during sorting, the ranks will be fixed and will not change.

(Note that I'm setting the rank to a negative value. The Ordered[T] trait sorts elements in ascending order, so that - if we sorted purely by set size - smaller sets would come before larger sets. By negating the rank value, sorting will put larger sets before smaller sets. If you don't want this behavior, remove the negations.)

Body:
I have a comparator like this:

lazy val seq = mapping.toSeq.sortWith { case ((_, set1), (_, set2)) =>
  // Just propose all the most connected nodes first to the users
  // But also allow less connected nodes to pop out sometimes
  val popOutChance = random.nextDouble <= 0.1D && set2.size > 5
  if (popOutChance) set1.size < set2.size else set1.size > set2.size
}

It is my intention to compare sets sizes such that smaller sets may appear higher in a sorted list with 10% chance.

But compiler does not let me do that and throws an Exception: java.lang.IllegalArgumentException: Comparison method violates its general contract! once I try to use it in runtime. How can I override it?

Body:
I think the problem here is that, every time two elements are compared, the outcome is random, thus violating the transitive property required of a comparator function in any sorting algorithm.

For example, let's say that some instance a compares as less than b, and then b compares as less than c. These results should imply that a compares as less than c. However, since your comparisons are stochastic, you can't guarantee that outcome. In fact, you can't even guarantee that a will be less than b next time they're compared.

So don't do that. No sort algorithm can handle it. (Such an approach also violates the referential transparency principle of functional programming and will make your program much harder to reason about.)

Instead, what you need to do is to decorate your map's members with a randomly assigned weighting - before attempting to sort them - so that they can be sorted consistently. However, since this happens at the start of a sort operation, the result of the sort will be different each time, which I think is what you're looking for.

It's not clear what type mapping has in your example, but it appears to be something like: Map[Any, Set[_]]. (You can replace the types as required - it's not that important to this approach. For example, say mapping actually has the type Map[String, Set[SomeClass]], then you would replace references below to Any with String and Set[_] to Set[SomeClass].)

First, we'll create a case class that we'll use to score and compare the map elements. Then we'll map the contents of mapping to a sequence of elements of this case class. Next, we sort those elements. Finally, we extract the tuple from the decorated class. The result should look something like this:

final case class Decorated(x: (Any, Set[_]), rand: Double = random.nextDouble)
extends Ordered[Decorated] {

  // Calculate a rank for this element. You'll need to change this to suit your precise
  // requirements. Here, if rand is less than 0.1 (a 10% chance), I'm adding 5 to the size;
  // otherwise, I'll report the actual size. This allows transitive comparisons, since
  // rand doesn't change once defined. Values are negated so bigger sets come to the fore
  // when sorted.
  private def rank: Int = {
    if(rand < 0.1) -(x._2.size + 5)
    else -x._2.size
  }

  // Compare this element with another, by their ranks.
  override def compare(that: Decorated): Int = rank.compare(that.rank)
}

// Now sort your mapping elements as follows and convert back to tuples.
lazy val seq = mapping.map(x => Decorated(x)).toSeq.sorted.map(_.x)

This should put the elements with larger sets towards the front, but there's 10% chance that sets appear 5 bigger and so move up the list. The result will be different each time the last line is re-executed, since map will create new random values for each element. However, during sorting, the ranks will be fixed and will not change.

(Note that I'm setting the rank to a negative value. The Ordered[T] trait sorts elements in ascending order, so that - if we sorted purely by set size - smaller sets would come before larger sets. By negating the rank value, sorting will put larger sets before smaller sets. If you don't want this behavior, remove the negations.)


问:
Authenticate through AD/LDAP
I don't know much about AD and LDAP, but trying to implement the most trivial LDAP/AD login function in Python. Lo luck so far though I tested several different modules. The most promising one might be ldap3:

```<code>>>> import ldap3
>>> server = ldap3.Server('myserver')
>>> connection = ldap3.Connection(server)
>>> connection.bind()
True
>>> connection.search(search_base='DC=mydomain,DC=com', search_filter='(&(objectClass=person)(userPrincipalName=firstname.lastname@mydomain.com))', search_scope='LEVEL', attributes=ldap3.ALL_ATTRIBUTES)
True
>>> connection.response[0]
{'uri': ['ldap://ForestDnsZones.mydomain.com/DC=ForestDnsZones,DC=mydomain,DC=com??base'], 'type': 'searchResRef'}
>>> connection.result
{'result': 0, 'description': 'success', 'dn': '', 'message': '', 'referrals': None, 'type': 'searchResDone'}
</code>```

Could you give me some pointers if this is on the right path or not?

The setup seems good enough for the basics, as I'm able to extract some type of metadata from it:

```<code>>>> server._get_dsa_info(connection)
>>> server._dsa_info
DSA info (from DSE):
  Supported LDAP versions: 3, 2
  Naming contexts:
    DC=mydomain,DC=com
    CN=Configuration,DC=mydomain,DC=com
    CN=Schema,CN=Configuration,DC=mydomain,DC=com
    DC=DomainDnsZones,DC=mydomain,DC=com
    DC=ForestDnsZones,DC=mydomain,DC=com

  Supported controls:
    1.2.840.113556.1.4.1338 - Verify name - Control - MICROSOFT
    1.2.840.113556.1.4.1339 - Domain scope - Control - MICROSOFT
    1.2.840.113556.1.4.1340 - Search options - Control - MICROSOFT
    ...
</code>```

I've also tried flask-ldap3-login, but is starting to suspect that our AD is not configured according to standard, as I'm getting:

```<code>...
>>> response = ldap_manager.authenticate('me', 'my_pass')
LDAPNoSuchObjectResult - 32 - noSuchObject - CN=Schema,CN=Configuration,DC=mydomain,DC=com - 0000208D: NameErr: DSID-0315270B, problem 2001 (NO_OBJECT), data 0, best match of:
        'CN=Schema,CN=Configuration,DC=mydomain,DC=com'
  - searchResDone - None
</code>```

Please don't hesitate to ask for additional information, and I'll try to figure it out as best I can. For instance, my own user is located in:

```<code>CN=Lastname Firstname,OU=Consultants,OU=Users,OU=SE,OU=MYDOMAIN,DC=mydomain,DC=com
</code>```

Some values are:

```<code>objectClass = top;person;organizationalPerson;user
name = Lastname Firstname
userPrincipalName = Firstname.Lastname@mydomain.com
</code>```

Also, from CN=Schema,CN=Configuration,DC=mydomain,DC=com there is only one subschema, which is CN=Aggregate,CN=Schema,CN=Configuration,DC=mydomain,DC=com and it looks empty. For some reason I believe this is what flask-ldap3-login tries to use.

答:
My problem using the ldap3.Connection was that I didn't use a login when binding. This seems to be a way forward:

```<code>import ldap3
user = 'me@mycompany.com'
password = 'mypassword'
server = ldap3.Server('myserver')
connection = ldap3.Connection(server, user=user, password=password)
connection.bind()
connection.search(search_base='DC=mycompany,DC=com', search_filter='(&(objectClass=user)(userPrincipalName='+user+'))', search_scope='SUBTREE', attributes='*')
</code>```

And if you like to print some data:

```<code>attrs = connection.response[0]['attributes']
print(attrs['displayName'])
for memb in attrs['memberOf']:
    print(memb.partition('=')[2].partition(',')[0])
</code>```

Title: Authenticate through AD/LDAP

Body:
I don't know much about AD and LDAP, but trying to implement the most trivial LDAP/AD login function in Python. Lo luck so far though I tested several different modules. The most promising one might be ldap3:

>>> import ldap3
>>> server = ldap3.Server('myserver')
>>> connection = ldap3.Connection(server)
>>> connection.bind()
True
>>> connection.search(search_base='DC=mydomain,DC=com', search_filter='(&(objectClass=person)(userPrincipalName=firstname.lastname@mydomain.com))', search_scope='LEVEL', attributes=ldap3.ALL_ATTRIBUTES)
True
>>> connection.response[0]
{'uri': ['ldap://ForestDnsZones.mydomain.com/DC=ForestDnsZones,DC=mydomain,DC=com??base'], 'type': 'searchResRef'}
>>> connection.result
{'result': 0, 'description': 'success', 'dn': '', 'message': '', 'referrals': None, 'type': 'searchResDone'}

Could you give me some pointers if this is on the right path or not?

The setup seems good enough for the basics, as I'm able to extract some type of metadata from it:

>>> server._get_dsa_info(connection)
>>> server._dsa_info
DSA info (from DSE):
  Supported LDAP versions: 3, 2
  Naming contexts:
    DC=mydomain,DC=com
    CN=Configuration,DC=mydomain,DC=com
    CN=Schema,CN=Configuration,DC=mydomain,DC=com
    DC=DomainDnsZones,DC=mydomain,DC=com
    DC=ForestDnsZones,DC=mydomain,DC=com

  Supported controls:
    1.2.840.113556.1.4.1338 - Verify name - Control - MICROSOFT
    1.2.840.113556.1.4.1339 - Domain scope - Control - MICROSOFT
    1.2.840.113556.1.4.1340 - Search options - Control - MICROSOFT
    ...

I've also tried flask-ldap3-login, but is starting to suspect that our AD is not configured according to standard, as I'm getting:

...
>>> response = ldap_manager.authenticate('me', 'my_pass')
LDAPNoSuchObjectResult - 32 - noSuchObject - CN=Schema,CN=Configuration,DC=mydomain,DC=com - 0000208D: NameErr: DSID-0315270B, problem 2001 (NO_OBJECT), data 0, best match of:
        'CN=Schema,CN=Configuration,DC=mydomain,DC=com'
  - searchResDone - None

Please don't hesitate to ask for additional information, and I'll try to figure it out as best I can. For instance, my own user is located in:

CN=Lastname Firstname,OU=Consultants,OU=Users,OU=SE,OU=MYDOMAIN,DC=mydomain,DC=com

Some values are:

objectClass = top;person;organizationalPerson;user
name = Lastname Firstname
userPrincipalName = Firstname.Lastname@mydomain.com

Also, from CN=Schema,CN=Configuration,DC=mydomain,DC=com there is only one subschema, which is CN=Aggregate,CN=Schema,CN=Configuration,DC=mydomain,DC=com and it looks empty. For some reason I believe this is what flask-ldap3-login tries to use.

Body:
My problem using the ldap3.Connection was that I didn't use a login when binding. This seems to be a way forward:

import ldap3
user = 'me@mycompany.com'
password = 'mypassword'
server = ldap3.Server('myserver')
connection = ldap3.Connection(server, user=user, password=password)
connection.bind()
connection.search(search_base='DC=mycompany,DC=com', search_filter='(&(objectClass=user)(userPrincipalName='+user+'))', search_scope='SUBTREE', attributes='*')

And if you like to print some data:

attrs = connection.response[0]['attributes']
print(attrs['displayName'])
for memb in attrs['memberOf']:
    print(memb.partition('=')[2].partition(',')[0])


问:
Prevent line break in header
I have an h1 with line breaks. On mobile devices, there should be no line breaks.

This code works on Chrome and iPhone but not on Firefox. So I am afraid it might not work on all devices/browsers.

(The code snippet seems to ignore the media query).

h1 {
  text-align: right;
}

@media screen and (max-width: 839px) {
 h1 {
  br {
   content: "";
   &:after {
    content: " ";
   }
  }
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>This is a<br>header<br>with line breaks</h1></code>```

Note the spaces which get inserted by CSS when the header is on 1 line. And also the header should be able to align to right.
How could I make this cross-browser compatible?

答:
If you leave the header normally spaced and put the
 after each word you want it to break at, a space will be left to the left side of each line which is okay since you want it to be aligned to the right. Then add display:none on the
 at the proper screen size.

h1 {
  text-align: right;
}
@media screen and (max-width: 839px) {
 h1 br{
      display:none;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>This is a<br> header<br> with line breaks</h1></code>```

Title: Prevent line break in header

Body:
I have an h1 with line breaks. On mobile devices, there should be no line breaks.

This code works on Chrome and iPhone but not on Firefox. So I am afraid it might not work on all devices/browsers.

(The code snippet seems to ignore the media query).

h1 {
  text-align: right;
}

@media screen and (max-width: 839px) {
 h1 {
  br {
   content: "";
   &:after {
    content: " ";
   }
  }
 }
}

This is a
header
with line breaks

Note the spaces which get inserted by CSS when the header is on 1 line. And also the header should be able to align to right.
How could I make this cross-browser compatible?

Body:
If you leave the header normally spaced and put the <br> after each word you want it to break at, a space will be left to the left side of each line which is okay since you want it to be aligned to the right. Then add display:none on the <br> at the proper screen size.

h1 {
  text-align: right;
}
@media screen and (max-width: 839px) {
 h1 br{
      display:none;
    }
}

<h1>This is a<br> header<br> with line breaks</h1>


问:
App crashes when I switch from a map activity to another activity, then back to the map activity
I have a small app that receives your current GPS coordinates in latitude and longitude when a "Save Location" button is pressed.  Another activity is started where the map is shown and your current position is marked.  On this map activity, there is a button you can press to go to another activity (let's call this the memo activity), in which there is a button to bring you back to the map activity.  However, the app crashes upon pressing this button that brings you back to the map activity.

Here is the code for the main activity, map activity and the memo activity.

Main Activity

```<code>public class HomeScreen extends AppCompatActivity {

private Button button;
private TextView textView;
private LocationManager locationManager;
private LocationListener locationListener;
private double longitude;
private double latitude;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.homescreen);
    button = (Button) findViewById(R.id.button);
}

public void saveAndGo(View view) {
    GPStracker g = new GPStracker(getApplicationContext());
    Location l = g.getLocation();
    if (l != null)
    {
        longitude =  l.getLongitude();
        latitude  =  l.getLatitude();
    }

    Intent go = new Intent(this, MapsActivity.class);
    go.putExtra("longitude", longitude);
    go.putExtra("latitude", latitude);
    startActivity(go);
    finish();
}
</code>```

Map Activity

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private Double latitude;
private Double longitude;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

        latitude = getIntent().getExtras().getDouble("latitude");
        longitude = getIntent().getExtras().getDouble("longitude");
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    LatLng pos = new LatLng(latitude, longitude);
    mMap.addMarker(new MarkerOptions().position(pos).title("Your Location"));
    mMap.setMinZoomPreference(16.0f);
    mMap.setMaxZoomPreference(20.0f);
    mMap.setMyLocationEnabled(true);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(pos));
}

public void goMemos (View view) {
    Intent go = new Intent(this, MemoScreen.class);
    startActivity(go);
}
</code>```

Memo Activity

```<code>public class MemoScreen extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.memoscreen);
    }

    public void goMap (View view){
        Intent go = new Intent(this, MapsActivity.class);
        startActivity(go);
    }
}
</code>```

I assume it's crashing because when I try to get data from the main activity when switching back to the map activity from the memo activity, the data is null.  The app runs just fine if I remove the getExtras() calls from the map activity.

How do I get around this?

Note: I would like to avoid using finish() in the memo activity since I plan to add more screens to this app, thus using that may end up in undesired behavior (i.e., returning back to the wrong activity).

答:
you have to put simple condition that is

```<code> if(getIntent().getExtras() != null){

    latitude = getIntent().getExtras().getDouble("latitude");
    longitude = getIntent().getExtras().getDouble("longitude");
 }
</code>```

just use this in your mapsactivity
and not forgot to initialize the value of

```<code>private Double latitude=123.45;
private Double longitude=123.45;
</code>```

Body:
I have a small app that receives your current GPS coordinates in latitude and longitude when a "Save Location" button is pressed.  Another activity is started where the map is shown and your current position is marked.  On this map activity, there is a button you can press to go to another activity (let's call this the memo activity), in which there is a button to bring you back to the map activity.  However, the app crashes upon pressing this button that brings you back to the map activity.

Here is the code for the main activity, map activity and the memo activity.

Main Activity

public class HomeScreen extends AppCompatActivity {

private Button button;
private TextView textView;
private LocationManager locationManager;
private LocationListener locationListener;
private double longitude;
private double latitude;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.homescreen);
    button = (Button) findViewById(R.id.button);
}

public void saveAndGo(View view) {
    GPStracker g = new GPStracker(getApplicationContext());
    Location l = g.getLocation();
    if (l != null)
    {
        longitude =  l.getLongitude();
        latitude  =  l.getLatitude();
    }

    Intent go = new Intent(this, MapsActivity.class);
    go.putExtra("longitude", longitude);
    go.putExtra("latitude", latitude);
    startActivity(go);
    finish();
}

Map Activity

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private Double latitude;
private Double longitude;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

        latitude = getIntent().getExtras().getDouble("latitude");
        longitude = getIntent().getExtras().getDouble("longitude");
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    LatLng pos = new LatLng(latitude, longitude);
    mMap.addMarker(new MarkerOptions().position(pos).title("Your Location"));
    mMap.setMinZoomPreference(16.0f);
    mMap.setMaxZoomPreference(20.0f);
    mMap.setMyLocationEnabled(true);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(pos));
}

public void goMemos (View view) {
    Intent go = new Intent(this, MemoScreen.class);
    startActivity(go);
}

Memo Activity

public class MemoScreen extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.memoscreen);
    }

    public void goMap (View view){
        Intent go = new Intent(this, MapsActivity.class);
        startActivity(go);
    }
}

I assume it's crashing because when I try to get data from the main activity when switching back to the map activity from the memo activity, the data is null.  The app runs just fine if I remove the getExtras() calls from the map activity.

How do I get around this?

Note: I would like to avoid using finish() in the memo activity since I plan to add more screens to this app, thus using that may end up in undesired behavior (i.e., returning back to the wrong activity).

Body:
you have to put simple condition that is

 if(getIntent().getExtras() != null){

    latitude = getIntent().getExtras().getDouble("latitude");
    longitude = getIntent().getExtras().getDouble("longitude");
 }

just use this in your mapsactivity
and not forgot to initialize the value of

private Double latitude=123.45;
private Double longitude=123.45;


问:
Web API returns escaped JSON
I have a POST method in a .NET core 2.0 web API project that needs to return a JSON (using newtonsoft). I have the following code at the end of the method:

```<code>ObjectResult objRes = new ObjectResult(JsonConvert.SerializeObject(result, settings));
objRes.ContentTypes.Add(new MediaTypeHeaderValue("application/json"));
return objRes
</code>```

When I test this using Postman I get a result like:

```<code>"{\"name\":\"test\",\"value\":\"test\"}"
</code>```

As you can see, the JSON is still escaped in postman. When I test the exact same code in a .NET core 1.0 project, I get the following in Postman:

```<code>{
  "name": "test",
  "value": "test"
}
</code>```

How can I get the same result in my .NET core 2.0 project?
I was thinking it might have been due to Newtonsoft but when I debug the deserialization into a string, the debugger shows exactly the same (escaped) value in both the .NET core 1.0 and 2.0 project.

答:
You can just return result in the controller and it will be serialized by the framework.

```<code>[HttpPost]
public object Post()
{
    var result = new MyObject { Name = "test", Value = "test" };
    return result;
}
</code>```

Or you can do:

```<code>return new OkObjectResult(result);
</code>```

Or if you inherit from Controller:

```<code>return Ok(result);
</code>```

Title: Web API returns escaped JSON

Body:
I have a POST method in a .NET core 2.0 web API project that needs to return a JSON (using newtonsoft). I have the following code at the end of the method:

ObjectResult objRes = new ObjectResult(JsonConvert.SerializeObject(result, settings));
objRes.ContentTypes.Add(new MediaTypeHeaderValue("application/json"));
return objRes

When I test this using Postman I get a result like:

"{\"name\":\"test\",\"value\":\"test\"}"

As you can see, the JSON is still escaped in postman. When I test the exact same code in a .NET core 1.0 project, I get the following in Postman:

{
  "name": "test",
  "value": "test"
}

How can I get the same result in my .NET core 2.0 project?
I was thinking it might have been due to Newtonsoft but when I debug the deserialization into a string, the debugger shows exactly the same (escaped) value in both the .NET core 1.0 and 2.0 project.

Body:
You can just return result in the controller and it will be serialized by the framework.

[HttpPost]
public object Post()
{
    var result = new MyObject { Name = "test", Value = "test" };
    return result;
}

Or you can do:

return new OkObjectResult(result);

Or if you inherit from Controller:

return Ok(result);


问:
Show another element if current input was changed
I want to show one element if current input was changed.

```<code>$('.type_number').change(function() {
  $(this)
  $('.check-update').css('display', 'block')
})
</code>```

<input class="type_number" type="number" name="amount" value="{{ product.amount }}">
<input type="hidden" name="product" value="{{ product.product.id }}">
<button type="submit" class="btn btn-link check-update">

</button>
```

How to say jquery if current was changed show another element

This creates a difficulty for me and besides I can not figure out how to do it. Please explain me if someone knows about it

答:
This is what you want I guess. It's in pure Javascript

var input = document.querySelector('#my-text-box');

var messages = document.querySelector('#messages');

input.addEventListener('input', function()
{
   messages.style.display = 'block'
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="my-text-box" />

<div id="messages" style="display: none">I was hidden First</div></code>```

It's just a demo to give you an idea of how to get your thing working

Body:
I want to show one element if current input was changed.

$('.type_number').change(function() {
  $(this)
  $('.check-update').css('display', 'block')
})

<input class="type_number" type="number" name="amount" value="{{ product.amount }}">
<input type="hidden" name="product" value="{{ product.product.id }}">
<button type="submit" class="btn btn-link check-update">

</button>

How to say jquery if current was changed show another element

This creates a difficulty for me and besides I can not figure out how to do it. Please explain me if someone knows about it

Body:
This is what you want I guess. It's in pure Javascript

var input = document.querySelector('#my-text-box');

var messages = document.querySelector('#messages');

input.addEventListener('input', function()
{
   messages.style.display = 'block'
});

<input id="my-text-box" />

<div id="messages" style="display: none">I was hidden First</div>

It's just a demo to give you an idea of how to get your thing working


答: I don't think you have to serialize your object before sending it. In .NET Core it will be serialized for you by default.</p>

Title: Web API returns escaped JSON


问:
C initializer element is not constant
I'm getting a "error: initializer element is not constant"
with this code:

```<code>typedef struct {
    const int x;
    const int y;
} my_struct;

const int a = 8;
const int b = 12;

my_struct test = { a, b };
</code>```

Any idea of what's going on and how to fix it ?

答:
Besides macros (which have their downsides), unnamed enumerations are often used for the purpose to just provide compile-time constants. This would change your code like this.

```<code>typedef struct {
    const int x;
    const int y;
} my_struct;

enum {
    a = 8,
    b = 12,
};

my_struct test = { a, b };
</code>```

... also expressions involving compile-time constants can be compile-time constants themselves ...

```<code>my_struct test1 = { a+1, b };
my_struct test2 = { a, 'H' };
</code>```

Also the sizeof operator can produce compile-time constants:

```<code>my_struct test3 = { sizeof(my_struct), b };
</code>```

Even if this example looks not very useful, it compiles.

For learning what exactly constant expressions are, see for example Constant expressions - despite the URL (cppreference.com), this is the C reference part.

Title: C initializer element is not constant

Body:
I'm getting a "error: initializer element is not constant"
with this code:

typedef struct {
    const int x;
    const int y;
} my_struct;

const int a = 8;
const int b = 12;

my_struct test = { a, b };

Any idea of what's going on and how to fix it ?

Body:
Besides macros (which have their downsides), unnamed enumerations are often used for the purpose to just provide compile-time constants. This would change your code like this.

typedef struct {
    const int x;
    const int y;
} my_struct;

enum {
    a = 8,
    b = 12,
};

my_struct test = { a, b };

... also expressions involving compile-time constants can be compile-time constants themselves ...

my_struct test1 = { a+1, b };
my_struct test2 = { a, 'H' };

Also the sizeof operator can produce compile-time constants:

my_struct test3 = { sizeof(my_struct), b };

Even if this example looks not very useful, it compiles.

For learning what exactly constant expressions are, see for example Constant expressions - despite the URL (cppreference.com), this is the C reference part.


问:
D3 tick labels from data values
Im trying to create tick labels on the y axis from key values coming from my data object. The data object is as follows:

Data Object:

```<code>var data = [
      {name: 'E2E Tests', passed: 4, notRun: 4, failed: 0, blocked: 0, notApplicable: 0 },
      {name: '868: Services', passed: 3, notRun: 3, failed: 1, blocked: 0, notApplicable: 0 },
      {name: '869: Services', passed: 2, notRun: 1, failed: 2, blocked: 1, notApplicable: 0 },
      {name: 'Bugs fixed', passed: 1, notRun: 1, failed: 0, blocked: 2, notApplicable: 0 },
      {name: '870: Services', passed: 2, notRun: 0, failed: 1, blocked: 0, notApplicable: 1 },
      {name: '867: Local', passed: 3, notRun: 0, failed: 1, blocked: 0, notApplicable: 0 },
      {name: '866: Local', passed: 3, notRun: 1, failed: 0, blocked: 0, notApplicable: 0 }
];
</code>```

Complete Code:

```<code>var margin = { top: 10, right: 25, bottom: 30, left: 30 };
var width = 600 - margin.left - margin.right;
var height = 400 - margin.top - margin.bottom;

var svg = d3.select('.chart')
  .append('svg')
    .attr('width', width + margin.left + margin.right)
    .attr('height', height + margin.top + margin.bottom)
    .call(responsivefy)
  .append('g')
    .attr('transform', `translate(${margin.left}, ${margin.top})`);

svg.append('rect')
  .attr('width', width)
  .attr('height', height)
  .style('fill', 'lightblue')
  .style('stroke', 'green') ;

// Y Axis
var yScale = d3.scaleLinear()
  .domain([0, 100])
  .range([height, 0]);
var yAxis = d3.axisLeft(yScale);
svg.call(yAxis);

// X Axis
var xScale = d3.scaleTime()
  .domain([0, 8])
  .range([0, width]);

var xAxis = d3.axisBottom(xScale)
  .ticks(8)
  .tickFormat(d3.format("d"));

svg.append('g')
  .attr('transform', `translate(0, ${height})`)
  .call(xAxis);

function responsivefy(svg) {
  var container = d3.select(svg.node().parentNode);
  var width = parseInt(svg.style('width'));
  var height = parseInt(svg.style('height'));
  var aspect = width / height;

  svg.attr('viewBox', '0 0 ' + width + ' ' + height)
     .attr('preserveAspectRatio', 'xMinYMid')
     .call(resize);

  d3.select(window).on('resize.' + container.attr('id'), resize);

  function resize() {
    var targetWidth = parseInt(container.style('width'));
    svg.attr('width', targetWidth);
    svg.attr('height', Math.round(targetWidth / aspect));
  }
}
</code>```

I would like to use the name value as a label for each tick. So far I have tried two ways to get this to work.

Attempt 1:

I tried creating an independent array of the name values and passing it into the tickValues method which I added to the y axis, didn't work:

```<code>var yLabels = data.map(d => d.name);

var yAxis = d3.axisLeft(yScale).tickValues(yLabels);
</code>```

Attempt 2:

Then I tried adding the following changes to the y axis:

```<code>var yAxis = d3.axisLeft(yScale)
    .tickValues(data)
    .tickFormat(d => d.name);
</code>```

This looks like it added the text to the svg but they are all positioned at the top overlapping one another. I feel like there has to be an easy and cleaner way to do this.

答:
The problem is in your scale(you will not use a linear scale for this one):

```<code>var yScale = d3.scaleBand()
.domain(["bob","Tom","Fred"]) // this is where you specify the labels
.range([height, 0]);
</code>```

As the domain is what gets printed on the axis label spans, given a certain value from the range. The Axis rendering function uses the domain of the scale.

Hope this reference helps: https://github.com/d3/d3/blob/master/API.md#scales-d3-scale

If you have any questions feel free to ask.

Title: D3 tick labels from data values

Body:
Im trying to create tick labels on the y axis from key values coming from my data object. The data object is as follows:

Data Object:

var data = [
      {name: 'E2E Tests', passed: 4, notRun: 4, failed: 0, blocked: 0, notApplicable: 0 },
      {name: '868: Services', passed: 3, notRun: 3, failed: 1, blocked: 0, notApplicable: 0 },
      {name: '869: Services', passed: 2, notRun: 1, failed: 2, blocked: 1, notApplicable: 0 },
      {name: 'Bugs fixed', passed: 1, notRun: 1, failed: 0, blocked: 2, notApplicable: 0 },
      {name: '870: Services', passed: 2, notRun: 0, failed: 1, blocked: 0, notApplicable: 1 },
      {name: '867: Local', passed: 3, notRun: 0, failed: 1, blocked: 0, notApplicable: 0 },
      {name: '866: Local', passed: 3, notRun: 1, failed: 0, blocked: 0, notApplicable: 0 }
];

Complete Code:

var margin = { top: 10, right: 25, bottom: 30, left: 30 };
var width = 600 - margin.left - margin.right;
var height = 400 - margin.top - margin.bottom;

var svg = d3.select('.chart')
  .append('svg')
    .attr('width', width + margin.left + margin.right)
    .attr('height', height + margin.top + margin.bottom)
    .call(responsivefy)
  .append('g')
    .attr('transform', `translate(${margin.left}, ${margin.top})`);

svg.append('rect')
  .attr('width', width)
  .attr('height', height)
  .style('fill', 'lightblue')
  .style('stroke', 'green') ;

// Y Axis
var yScale = d3.scaleLinear()
  .domain([0, 100])
  .range([height, 0]);
var yAxis = d3.axisLeft(yScale);
svg.call(yAxis);

// X Axis
var xScale = d3.scaleTime()
  .domain([0, 8])
  .range([0, width]);

var xAxis = d3.axisBottom(xScale)
  .ticks(8)
  .tickFormat(d3.format("d"));

svg.append('g')
  .attr('transform', `translate(0, ${height})`)
  .call(xAxis);

function responsivefy(svg) {
  var container = d3.select(svg.node().parentNode);
  var width = parseInt(svg.style('width'));
  var height = parseInt(svg.style('height'));
  var aspect = width / height;

  svg.attr('viewBox', '0 0 ' + width + ' ' + height)
     .attr('preserveAspectRatio', 'xMinYMid')
     .call(resize);

  d3.select(window).on('resize.' + container.attr('id'), resize);

  function resize() {
    var targetWidth = parseInt(container.style('width'));
    svg.attr('width', targetWidth);
    svg.attr('height', Math.round(targetWidth / aspect));
  }
}

I would like to use the name value as a label for each tick. So far I have tried two ways to get this to work.

Attempt 1:

I tried creating an independent array of the name values and passing it into the tickValues method which I added to the y axis, didn't work:

var yLabels = data.map(d => d.name);

var yAxis = d3.axisLeft(yScale).tickValues(yLabels);

Attempt 2:

Then I tried adding the following changes to the y axis:

var yAxis = d3.axisLeft(yScale)
    .tickValues(data)
    .tickFormat(d => d.name);

This looks like it added the text to the svg but they are all positioned at the top overlapping one another. I feel like there has to be an easy and cleaner way to do this.

Body:
The problem is in your scale(you will not use a linear scale for this one):

var yScale = d3.scaleBand()
.domain(["bob","Tom","Fred"]) // this is where you specify the labels
.range([height, 0]);

As the domain is what gets printed on the axis label spans, given a certain value from the range. The Axis rendering function uses the domain of the scale.

Hope this reference helps: https://github.com/d3/d3/blob/master/API.md#scales-d3-scale

If you have any questions feel free to ask.


问:
Perl captured digits from string are always 1
On my journey to start learning perl...

I encountered this funny behaviour, and can't seem to wrap my head around it.

```<code>my $username = "bandit0";
my $command = "";

sub next_command {
    my ($user) = @_;
    my $num = $user =~ /(\d+)/;
    print "$num\n";
    if ($num == 0){
        return "cat readme";
    }
    elsif ($num == 1){
        return "ls";
    }
}

sub next_level {
    my ($user) = @_;
    my $num = $user =~ /(\d+)/;
    $user =~ s/\d//g;
    $user = $user . $num++;
    return $user;
}

$command = next_command($username);
print $command . "\n";
$username = next_level($username);
$command = next_command($username);
print $command . "\n";
</code>```

After running this small perl program, I would expect something like this:

```<code>0
cat readme
1
ls
</code>```

However I get something like this...

```<code>1
ls
1
ls
</code>```

I don't understand why, at first string bandit0 the $num will be 1 instead of 0

答:
You can try this and see if it works. if it helps, I will explain everything. I cannot test this myself right now.</p>

```<code>use strict;   # always use strict
use warnings; # always use warnings

my $username = "bandit0"; #try bandit1 to ensure it prints 1 and ls instead
my $command = "";

sub next_command {
    my ($user) = @_;
    my ($num) = $user =~ /(\d+)/;
    print "$num\n";
    if ($num == 0){
       return "cat readme";
    }

    elsif ($num == 1){
        return "ls";
    }
}

sub next_level {
    my ($user) = @_;
    my ($num) = $user =~ /(\d+)/;
    $user =~ s/\d//g;
    $user = $user . ++$num;
     return $user;
}

$command = next_command($username);
print $command . "\n";
$username = next_level($username);
$command = next_command($username);
print $command . "\n";
</code>```

Body:
On my journey to start learning perl...

I encountered this funny behaviour, and can't seem to wrap my head around it.

my $username = "bandit0";
my $command = "";

sub next_command {
    my ($user) = @_;
    my $num = $user =~ /(\d+)/;
    print "$num\n";
    if ($num == 0){
        return "cat readme";
    }
    elsif ($num == 1){
        return "ls";
    }
}

sub next_level {
    my ($user) = @_;
    my $num = $user =~ /(\d+)/;
    $user =~ s/\d//g;
    $user = $user . $num++;
    return $user;
}

$command = next_command($username);
print $command . "\n";
$username = next_level($username);
$command = next_command($username);
print $command . "\n";

After running this small perl program, I would expect something like this:

0
cat readme
1
ls

However I get something like this...

1
ls
1
ls

I don't understand why, at first string bandit0 the $num will be 1 instead of 0

Body:
You can try this and see if it works. if it helps, I will explain everything. I cannot test this myself right now.

use strict;   # always use strict
use warnings; # always use warnings

my $username = "bandit0"; #try bandit1 to ensure it prints 1 and ls instead
my $command = "";

sub next_command {
    my ($user) = @_;
    my ($num) = $user =~ /(\d+)/;
    print "$num\n";
    if ($num == 0){
       return "cat readme";
    }

    elsif ($num == 1){
        return "ls";
    }
}

sub next_level {
    my ($user) = @_;
    my ($num) = $user =~ /(\d+)/;
    $user =~ s/\d//g;
    $user = $user . ++$num;
     return $user;
}

$command = next_command($username);
print $command . "\n";
$username = next_level($username);
$command = next_command($username);
print $command . "\n";


问:
Promise resolves to null when resolving this
I have a function that connects to a API. That function returns a Promise. I can't figure out why Promise.resolve returns null when I'm resolving with a constant containing the this context.

```<code>const connect = () => {
  return new Promise((resolve, reject) => {
    Gitana.connect(config, function(err) {
      const platform = this;
      if (err) {
        return reject(err);
      }
      console.log(platform) // Object that I want
      resolve(platform)
    });
  });
}

connect()
  .then(platform => {
    console.log(platform) // null
  })
</code>```

I don't know if it is any help but I know there is a method on the resolve object (platform) called datastore. If I resolve that method, ie resolve(platform.datastore) I get the method, instead of null

I have tried to resolve static values, resolve(25) or resolve('hello') and that works fine.

How do I return/resolve the object?

答:
As you've noted, it looks like this is happening because the value you're trying to pass actually has a .then method, so it is being subsumed in the promise resolution procedure.

One way to pass it without deleting methods would be to wrap it in a container to transport it along:

```<code>const connect = () => {
  return new Promise((resolve, reject) => {
    Gitana.connect(config, function(err) {
      const platform = this;
      if (err) {
        return reject(err);
      }
      resolve({ platform });
    });
  });
}

connect()
  .then(({ platform }) => {
    console.log(platform)
  })
</code>```

Body:
I have a function that connects to a API. That function returns a Promise. I can't figure out why Promise.resolve returns null when I'm resolving with a constant containing the this context.

const connect = () => {
  return new Promise((resolve, reject) => {
    Gitana.connect(config, function(err) {
      const platform = this;
      if (err) {
        return reject(err);
      }
      console.log(platform) // Object that I want
      resolve(platform)
    });
  });
}

connect()
  .then(platform => {
    console.log(platform) // null
  })

I don't know if it is any help but I know there is a method on the resolve object (platform) called datastore. If I resolve that method, ie resolve(platform.datastore) I get the method, instead of null

I have tried to resolve static values, resolve(25) or resolve('hello') and that works fine.

How do I return/resolve the object?

Body:
As you've noted, it looks like this is happening because the value you're trying to pass actually has a .then method, so it is being subsumed in the promise resolution procedure.

One way to pass it without deleting methods would be to wrap it in a container to transport it along:

const connect = () => {
  return new Promise((resolve, reject) => {
    Gitana.connect(config, function(err) {
      const platform = this;
      if (err) {
        return reject(err);
      }
      resolve({ platform });
    });
  });
}

connect()
  .then(({ platform }) => {
    console.log(platform)
  })


问:
What is the DOCKER_CERT_PATH in Docker for Windows on Windows 10?
When I was using Docker Toolbox, I could just run docker-machine env to print all of the current environment variables.

答:
With Docker for Windows, it assumes a cert path of

```<code>%USERPROFILE%\.docker\machine\certs
</code>```

Unless you specify the environment variable

```<code>DOCKER_CERT_PATH
</code>```

If you're switching from Docker Toolbox to Docker for Windows, you might need to remove this environment variable to get things working.

Body:
With Docker for Windows, it assumes a cert path of

%USERPROFILE%\.docker\machine\certs

Unless you specify the environment variable

DOCKER_CERT_PATH

If you're switching from Docker Toolbox to Docker for Windows, you might need to remove this environment variable to get things working.


问:
How to set Apache Spark Executor memory
How can I increase the memory available for Apache spark executor nodes?

I have a 2 GB file that is suitable to loading in to Apache Spark. I am running apache spark for the moment on 1 machine, so the driver and executor are on the same machine. The machine has 8 GB of memory.

When I try count the lines of the file after setting the file to be cached in memory I get these errors:

```<code>2014-10-25 22:25:12 WARN  CacheManager:71 - Not enough space to cache partition rdd_1_1 in memory! Free memory is 278099801 bytes.
</code>```

I looked at the documentation here and set spark.executor.memory to 4g in $SPARK_HOME/conf/spark-defaults.conf

The UI shows this variable is set in the Spark Environment. You can find screenshot here

However when I go to the Executor tab the memory limit for my single Executor is  still set to 265.4 MB.  I also still get the same error.

I tried various things mentioned here but I still get the error and don't have a clear idea where I should change the setting.

I am running my code interactively from the spark-shell

答:
You need to increase the driver memory.On mac(i.e when running on local master), the default driver-memory is 1024M). By default, thus 380Mb is allotted to the executor.

Upon increasing [--driver-memory 2G], executor memory got increased to ~950Mb.

Title: How to set Apache Spark Executor memory

Body:
How can I increase the memory available for Apache spark executor nodes?

I have a 2 GB file that is suitable to loading in to Apache Spark. I am running apache spark for the moment on 1 machine, so the driver and executor are on the same machine. The machine has 8 GB of memory.

When I try count the lines of the file after setting the file to be cached in memory I get these errors:

2014-10-25 22:25:12 WARN  CacheManager:71 - Not enough space to cache partition rdd_1_1 in memory! Free memory is 278099801 bytes.

I looked at the documentation here and set spark.executor.memory to 4g in $SPARK_HOME/conf/spark-defaults.conf

The UI shows this variable is set in the Spark Environment. You can find screenshot here

However when I go to the Executor tab the memory limit for my single Executor is  still set to 265.4 MB.  I also still get the same error.

I tried various things mentioned here but I still get the error and don't have a clear idea where I should change the setting.

I am running my code interactively from the spark-shell


问:
What is the equivalent of this syntax in Java?
Just a quick question about how to convert a certain line of code between c++ and Java. I've been learning about Neural Networks and I've been starting to write my own in the language I have the most experience with, Java. It's been pretty straightforward to translate the code from C++ to Java so far, however there's one little issue I've ran into. I'm puzzled by how to translate this specific line of code into a Java equivalent, and I can't find anything specific to this issue through searching.

The original code is:

```<code>Struct SNeuron {
   //the number of inputs into the neuron

   int m_NumInputs;
   //the weights for each input
   vector<double> m_vecWeight;
   //ctor
   SNeuron(int NumInputs);
};
</code>```

and my code is:

```<code>public class SNeuron {

public int m_NumInputs; // the number of inputs into the neuron
public ArrayList<Double> m_vecWeight = new ArrayList<Double>(); // the weights for each input
// ctor
</code>```

My question is, how do I convert:

```<code>SNeuron(int NumInputs);
</code>```

into its Java equivalent? From what i've read, Structs don't seem to be a feature Java uses, so i'm just struggling a bit to understand what exactly that line of code actually does in the context it's used.

答:
```<code>public class SNeuron
{

// the number of inputs into the neuron

public int m_NumInputs;

// the weights for each input

public List<Double> m_vecWeight = new ArrayList<Double>();

// ctor
SNeuron(int NumInputs) {
   m_NumInputs = NumInputs;
}
</code>```

Body:
Just a quick question about how to convert a certain line of code between c++ and Java. I've been learning about Neural Networks and I've been starting to write my own in the language I have the most experience with, Java. It's been pretty straightforward to translate the code from C++ to Java so far, however there's one little issue I've ran into. I'm puzzled by how to translate this specific line of code into a Java equivalent, and I can't find anything specific to this issue through searching.

The original code is:

Struct SNeuron {
   //the number of inputs into the neuron

   int m_NumInputs;
   //the weights for each input
   vector<double> m_vecWeight;
   //ctor
   SNeuron(int NumInputs);
};

and my code is:

public class SNeuron {

public int m_NumInputs; // the number of inputs into the neuron
public ArrayList<Double> m_vecWeight = new ArrayList<Double>(); // the weights for each input
// ctor

My question is, how do I convert:

SNeuron(int NumInputs);

into its Java equivalent? From what i've read, Structs don't seem to be a feature Java uses, so i'm just struggling a bit to understand what exactly that line of code actually does in the context it's used.


问:
Spring-boot default profile for integration tests
Spring-boot utilizes Spring profiles which allows to have separate config for different environments.
One way I use this feature is to configure the test database to be used by integration tests.
I wonder, however: is it necessary to create my own profile 'test' and explicitly activate this profile in each test file?
Right now, I do it in the following way:

Create application-test.properties inside src/main/resources

Write test-specific config there (just the database name for now)

In every test file, include:

```<code>@ActiveProfiles("test")
</code>```

Is there a smarter / more concise way? For instance, a default test profile?

Edit 1: This question pertains to Spring-Boot 1.4.1

答:
In my case I have different application.properties depending on the environment, something like:

```<code>application.properties (base file)
application-dev.properties
application-qa.properties
application-prod.properties
</code>```

and application.properties contains a property spring.profiles.active to pick the proper file.

For my integration tests, I created a new application-test.properties file inside test/resources and with the @TestPropertySource({ "/application-test.properties" }) annotation this is the file who is in charge of picking the application.properties I want depending on my needs for those tests

ContentLicense: CC BY-SA 4.0

Body:
Spring-boot utilizes Spring profiles which allows to have separate config for different environments.
One way I use this feature is to configure the test database to be used by integration tests.
I wonder, however: is it necessary to create my own profile 'test' and explicitly activate this profile in each test file?
Right now, I do it in the following way:

Create application-test.properties inside src/main/resources

Write test-specific config there (just the database name for now)

In every test file, include:

@ActiveProfiles("test")

Is there a smarter / more concise way? For instance, a default test profile?

Edit 1: This question pertains to Spring-Boot 1.4.1

Body:
In my case I have different application.properties depending on the environment, something like:

application.properties (base file)
application-dev.properties
application-qa.properties
application-prod.properties

and application.properties contains a property spring.profiles.active to pick the proper file.

For my integration tests, I created a new application-test.properties file inside test/resources and with the @TestPropertySource({ "/application-test.properties" }) annotation this is the file who is in charge of picking the application.properties I want depending on my needs for those tests


问:
Plotting exact Solution (error)
This code is to get a plot of an exact function, where the function is the array of y defined in fn1. the error is "have shapes {} and {}".format(x.shape, y.shape))

ValueError: x and y must have same first dimension, but have shapes (401,) and (2, 401)

```<code>def fn1( interval, N):
    x = numpy.linspace(interval[0], interval[1], N+1)
    y = numpy.array([numpy.exp(-1000*x),(1000/999)*(numpy.exp(-x)-numpy.exp(-1000*x))])
    return x, y

interval=numpy.array([0,0.1])
N=400

x,y=fn1(interval,N)
fig = plt.figure()
ax = fig.add_subplot(111)
plt.semilogy(x, y[:,0], 'b+')
</code>```

答:
You defined interval, but you did not use it as the argument into your function fn1, but instead used 0.1 as the argument.

Therefore you need to use this:

```<code>x, y=fn1(interval, 400)
</code>```

Title: Plotting exact Solution (error)

Body:
This code is to get a plot of an exact function, where the function is the array of y defined in fn1. the error is "have shapes {} and {}".format(x.shape, y.shape))

ValueError: x and y must have same first dimension, but have shapes (401,) and (2, 401)

def fn1( interval, N):
    x = numpy.linspace(interval[0], interval[1], N+1)
    y = numpy.array([numpy.exp(-1000*x),(1000/999)*(numpy.exp(-x)-numpy.exp(-1000*x))])
    return x, y

interval=numpy.array([0,0.1])
N=400

x,y=fn1(interval,N)
fig = plt.figure()
ax = fig.add_subplot(111)
plt.semilogy(x, y[:,0], 'b+')

Body:
You defined interval, but you did not use it as the argument into your function fn1, but instead used 0.1 as the argument.

Therefore you need to use this:

x, y=fn1(interval, 400)


答:
As I understand you want to show div when someone starts typing in it. In that case you should use keypress event. Like this:

$('.type_number').keypress(function() {
    $('.check-update').show();
    $('input').attr('type', 'text');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.check-update {
  display: none;
}</code>```

  <input class='type_number' type="text">
  <input type="hidden" name="product" value="{{ product.product.id }}">

Div when somebody starts typing
```

EDIT: OP wants to remove type hidden from input. I've adjusted the code, so that every hidden input will show when user starts to type.

Title: Show another element if current input was changed

Body:
I want to show one element if current input was changed.

$('.type_number').change(function() {
  $(this)
  $('.check-update').css('display', 'block')
})

<input class="type_number" type="number" name="amount" value="{{ product.amount }}">
<input type="hidden" name="product" value="{{ product.product.id }}">
<button type="submit" class="btn btn-link check-update">

</button>

How to say jquery if current was changed show another element

This creates a difficulty for me and besides I can not figure out how to do it. Please explain me if someone knows about it

Body:
As I understand you want to show div when someone starts typing in it. In that case you should use keypress event. Like this:

$('.type_number').keypress(function() {
    $('.check-update').show();
    $('input').attr('type', 'text');
});

.check-update {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <input class='type_number' type="text">
  <input type="hidden" name="product" value="{{ product.product.id }}">
  <div class='check-update'>Div when somebody starts typing</div>

EDIT: OP wants to remove type hidden from input. I've adjusted the code, so that every hidden input will show when user starts to type.


问:
What is the URL for the icon of a UWP app?
Is there some URL for an app's icon on the Windows Store?

I want to link to it, so that if I update that icon, the image on my website will be automatically updated too.

(I'm asking because I think I saw that mentioned somewhere, though searching now, I can't find anything like that.)

答:
What you are trying to do is not possible.

In your app manifest, you must declare the icon/tiles of your app. They will be part of the app package and cannot be changed.

You can still send custom tile update to your application tile but that will never change the default tile/icon.

You can have a look at the appx manifest's VisualElements documentation for the logo, small logo etc images paths remarks:

A string between 1 and 256 characters in length that ends with ".jpg", ".png", or ".jpeg" that can't contain these characters: <, >, :, %, ", |, ?, or *. In this string, the / and \ characters can't be the first or last characters. Also, the string can contain / or \ but not both.

Only local, package relative paths are allowed.


问:
Using WOLA in Liberty WebApp to access CICS
Trying to use WOLA direct from a webapp in Liberty to CICS. Using same CICS region successfully with z/OS Connect V2 (zCEE). With Liberty, I have configured:

```<code> <featureManager>
     <feature>servlet-3.1</feature>
     <feature>jndi-1.0</feature>
     <feature>jaxrs-1.1</feature>
     <feature>zosLocalAdapters-1.0</feature>
 </featureManager>
</code>```

and

```<code> <!-- WOLA group to which others register -->
 <zosLocalAdapters wolaGroup="GROUP" wolaName2="LIBRTOLA" wolaName3="WOLA3" />
 <connectionFactory id="wolaCF" jndiName="eis/ola">
     <properties.ola RegisterName=CICSMLAW/>
 </connectionFactory>
 <resourceAdapter location="/usr/lpp/IBM/zosconnect/v2r0/wlp/lib/ola.rar"/>
</code>```

In the messages.log, I see good and bad items there:

CWWKB0103I: Authorized service group WOLA is available The WebSphere Optimized Local Adapter channel registered with the Liberty profile server using the following name: GROUP LIBRTOLA WOLA3

and the bad:

com.ibm.ws.app.manager.AppMessageHelper E CWWKZ0013E: It is not possible to start two applications called ola.

So the failure on registration: Requestlgth: 97
Requestparms data 1: BBOC START_SRVR RGN=CICSMLA DGN=GROUP NDN=LIBRTOLA
Requestparms data 2: SVN=WOLA3 SVC= MNC=1 MXC=10 TXN=N SEC=N REU=N
Requestparms data 3:
Processing a START SERVER request.
Starting WAS adapters Server task ...
Server transaction id will be: BBO$
Link transaction defaults to: BBO#
Service name will be:
Trace TDQ: BBOQ
Processing a REGISTER API request.
Register name: CICSMLA string len: 7
WAS Daemon: GROUP WAS Node: LIBRTOLA WAS Server: WOLA3
Min. connections: 1
Max. connections: 10
Transactional: N string len: 1
Security propagation: N string len: 1
Invoking OLA Register API for CICSMLA .
on with the Liberty profile server was not successful. The return code is 8, and the reason code 8.

And the failure in the JNDI call:

```<code>Context ctx = new InitialContext();
ConnectionFactory cf = (com.ibm.ws390.ola.jca.ConnectionFactoryImpl)ctx.lookup("java:comp/env/eis/ola");
</code>```

Results in error:

```<code>[err] javax.naming.NameNotFoundException: javax.naming.NameNotFoundException: java:comp/env/eis/ola
[err] at com.ibm.ws.jndi.url.contexts.javacolon.internal.JavaURLContext.lookup(JavaURLContext.java:356) [err] at [internal classes]
[err] at javax.naming.InitialContext.lookup(InitialContext.java:428)
[err] at com.ibm.ctl.bank.impls.CTLBankWolaImpl.(CTLBankWolaImpl.java:51)
[err] at com.ibm.ctl.bank.web.OLTPBankRest.setImpl(OLTPBankRest.java:235)
</code>```

Thanks

答:
You have a lot going on here.

I'm not sure why you're starting ola.rar from the z/OS Connect v2 product, inside of a Liberty server.  The zosLocalAdapters-1.0 feature already loads the ola.rar that ships with Liberty.  You should remove the  configuration from server.xml.  That should resolve the CWWKZ0013E error.

You should see two CWWKB0103I messages in messages.log, one for WOLA (which you included) and one for CLIENT.WOLA.  Please be sure you see both.  It's possible you're on a very old version of Liberty that doesn't print the second CWWKB0103I message, so if this is true, please disregard that part.

I don't think you would have gotten this far without finding the WOLA configuration instructions for the Liberty server in the knowledge center, but here they are for other's benefits:

https://www.ibm.com/support/knowledgecenter/en/was_beta_liberty/com.ibm.websphere.wlp.nd.multiplatform.doc/ae/twlp_dat_enableconnector.html

OK next, I can't see your application to know whether you've got a resource-reference to a connection factory configured.  I assume you do because you're doing a java:comp/env lookup.  You do not need to cast to com.ibm.ws390.ola.jca.ConnectionFactoryImpl, and actually I highly recommend removing that since that is an internal class and subject to change at any time.  It may be that the application class loader doesn't have access to that class, and that may be part of the problem.

Finally, you have a problem in CICS starting the link server.  You are getting RC=8 RSN=8.  A list of services and return/reason codes can be found here:

https://www.ibm.com/support/knowledgecenter/en/was_beta_liberty/com.ibm.websphere.wlp.nd.multiplatform.doc/ae/rwlp_dat_olaapis.html

An 8/8 on BBOA1REG (register) indicates the register token is already in use.  Basically, the RGN= name you picked is already in use.  Are you sure there isn't a PLTPI transaction or something else in the CICS region that is already registered with that name?  Perhaps try a different name just to see if it works, and if it does, maybe try BBOC LIST_SRVR to see what it is?  It's difficult to say how it's getting started without knowing more about your system.

I hope this helps.  Take care!

Body:
Trying to use WOLA direct from a webapp in Liberty to CICS. Using same CICS region successfully with z/OS Connect V2 (zCEE). With Liberty, I have configured:

 <featureManager>
     <feature>servlet-3.1</feature>
     <feature>jndi-1.0</feature>
     <feature>jaxrs-1.1</feature>
     <feature>zosLocalAdapters-1.0</feature>
 </featureManager>

and

 <zosLocalAdapters wolaGroup="GROUP" wolaName2="LIBRTOLA" wolaName3="WOLA3" />
 <connectionFactory id="wolaCF" jndiName="eis/ola">
     <properties.ola RegisterName=CICSMLAW/>
 </connectionFactory>
 <resourceAdapter location="/usr/lpp/IBM/zosconnect/v2r0/wlp/lib/ola.rar"/>

In the messages.log, I see good and bad items there:

CWWKB0103I: Authorized service group WOLA is available The WebSphere Optimized Local Adapter channel registered with the Liberty profile server using the following name: GROUP LIBRTOLA WOLA3

and the bad:

com.ibm.ws.app.manager.AppMessageHelper E CWWKZ0013E: It is not possible to start two applications called ola.

So the failure on registration: Requestlgth: 97
Requestparms data 1: BBOC START_SRVR RGN=CICSMLA DGN=GROUP NDN=LIBRTOLA
Requestparms data 2: SVN=WOLA3 SVC= MNC=1 MXC=10 TXN=N SEC=N REU=N
Requestparms data 3:
Processing a START SERVER request.
Starting WAS adapters Server task ...
Server transaction id will be: BBO$
Link transaction defaults to: BBO#
Service name will be:
Trace TDQ: BBOQ
Processing a REGISTER API request.
Register name: CICSMLA string len: 7
WAS Daemon: GROUP WAS Node: LIBRTOLA WAS Server: WOLA3
Min. connections: 1
Max. connections: 10
Transactional: N string len: 1
Security propagation: N string len: 1
Invoking OLA Register API for CICSMLA .
on with the Liberty profile server was not successful. The return code is 8, and the reason code 8.

And the failure in the JNDI call:

Context ctx = new InitialContext();
ConnectionFactory cf = (com.ibm.ws390.ola.jca.ConnectionFactoryImpl)ctx.lookup("java:comp/env/eis/ola");

Results in error:

[err] javax.naming.NameNotFoundException: javax.naming.NameNotFoundException: java:comp/env/eis/ola
[err] at com.ibm.ws.jndi.url.contexts.javacolon.internal.JavaURLContext.lookup(JavaURLContext.java:356) [err] at [internal classes]
[err] at javax.naming.InitialContext.lookup(InitialContext.java:428)
[err] at com.ibm.ctl.bank.impls.CTLBankWolaImpl.(CTLBankWolaImpl.java:51)
[err] at com.ibm.ctl.bank.web.OLTPBankRest.setImpl(OLTPBankRest.java:235)

Thanks


问:
regex to find table name from sql query using shell script
I need to find table name from query and store the table name to variable.

Here is the query:

```<code>INSERT INTO CS_POLICY_TERM_PREM_TRANS(SOURCE_SYSTEM_CD)
    VALUES ( ?, ?)
</code>```

答:
Try this:

```<code>INSERT\s+INTO\s+(\w+)
</code>```

Take the first match group

Body:
I need to find table name from query and store the table name to variable.

Here is the query:

INSERT INTO CS_POLICY_TERM_PREM_TRANS(SOURCE_SYSTEM_CD)
    VALUES ( ?, ?)

Body:
Try this:

INSERT\s+INTO\s+(\w+)

Take the first match group


问:
Automating Chrome
I've seen some wild things happen when I paste some urlencoded Javascript into a URL on Firefox and Chrome. Is it possible to use this technique to tell Chrome to visit a URL and then save it as a file? I'm trying to automate Chrome, and Selenium looked extremely daunting.

EDIT: Unfortunately, I forgot to be more clear here. Let me explain. Things like wget, curl, etc. won't work because I have to get through logins in some of these scripts. And I've looked at iMacros, but found that I can't get them to run from command line except on Windows, unless I pay for the $499 package. Some other advantages of GCEs are that the dev platform is free and open to some degree, and they are cross-platform. (I use Linux.)

EDIT: At this point, I'm learning about Google Chrome Extensions. It appears they are easy to build and will let me (I think) tell the browser to open a new tab, go to a page, manipulate the DOM on that page (such as populating some fields and logging in), and then manipulate the DOM on the response page. GCEs don't let you do File I/O, so they are not like Firefox Extensions with XPCOM, but you can get around that by using AJAX to send data to a backend script (like a PHP script on a LAMP server) to save that data.

EDIT: By the way, and this is slightly off-topic (but I add to clarify) those "wild things" in Javascript that I mentioned were when you manipulate the DOM creating a URL that looks like so:

```<code>javascript:(function(){...your URL-encoded Javascript here...})();
</code>```

答:
You could try iMacros for Chrome. It is a pretty easy to use automation system.

Open iMacros

Click Record.

Go about you browsing routine.

Click stop.

I don't think it can get any easier than that. The scripts it saves are in plain text so you can edit them for some fine grain control if need be.

ContentLicense: CC BY-SA 2.5

Title: Automating Chrome

Body:
I've seen some wild things happen when I paste some urlencoded Javascript into a URL on Firefox and Chrome. Is it possible to use this technique to tell Chrome to visit a URL and then save it as a file? I'm trying to automate Chrome, and Selenium looked extremely daunting.

EDIT: Unfortunately, I forgot to be more clear here. Let me explain. Things like wget, curl, etc. won't work because I have to get through logins in some of these scripts. And I've looked at iMacros, but found that I can't get them to run from command line except on Windows, unless I pay for the $499 package. Some other advantages of GCEs are that the dev platform is free and open to some degree, and they are cross-platform. (I use Linux.)

EDIT: At this point, I'm learning about Google Chrome Extensions. It appears they are easy to build and will let me (I think) tell the browser to open a new tab, go to a page, manipulate the DOM on that page (such as populating some fields and logging in), and then manipulate the DOM on the response page. GCEs don't let you do File I/O, so they are not like Firefox Extensions with XPCOM, but you can get around that by using AJAX to send data to a backend script (like a PHP script on a LAMP server) to save that data.

EDIT: By the way, and this is slightly off-topic (but I add to clarify) those "wild things" in Javascript that I mentioned were when you manipulate the DOM creating a URL that looks like so:

javascript:(function(){...your URL-encoded Javascript here...})();


问:
C# Correctly aborting a always running thread with a BlockingCollection
I am running a thread that has a

```<code>while(isRunning)
{
    blockingCollection.Take()
}
</code>```

First I am setting isRunning to false. Then I call thread.Interrupt which stops the blockingCollection from waiting for new items. After that I call my Dispose Method for the class running the Thread inside the catch block.

Is that the best/correct way to do this?

答:
A BlockingCollection has a CompleteAdding() method and full support for Cancellation. </p>

```<code>while(isRunning && ! blockingCollection.IsCompleted)
{
   isRunning = blockingCollection.TryTake(out someThing, -1, cancelToken);
}
</code>```

<p>This way you can and should let the Thread end normally, always the better option. </p>

Body:
I am running a thread that has a

while(isRunning)
{
    blockingCollection.Take()
}

First I am setting isRunning to false. Then I call thread.Interrupt which stops the blockingCollection from waiting for new items. After that I call my Dispose Method for the class running the Thread inside the catch block.

Is that the best/correct way to do this?

Body:
A BlockingCollection has a CompleteAdding() method and full support for Cancellation.

while(isRunning && ! blockingCollection.IsCompleted)
{
   isRunning = blockingCollection.TryTake(out someThing, -1, cancelToken);
}

This way you can and should let the Thread end normally, always the better option.


问:
Make your NPM package support multiple versions of peer dependency
I have a package on NPM that is using React version 15 as peer dependency. However, I want it to stop from throwing warnings for users that upgraded their React version. How do I make package support both version 15 and 16?

```<code>"peerDependencies": {
    "react-dom": "^15.0.0"
  },
</code>```

which is the most convenient way to deal with these?

Is "*15.0.0" good enough?

答:
Just checked some other packages on GitHub how they do it.

Using * didn't work out for me and therefore seems like bad practice anyway.

Better solution:

```<code>  "peerDependencies": {
    "react": ">=0.14.0 <= 16",
    "react-dom": ">=0.14.0 <= 16"
  }
</code>```

Body:
I have a package on NPM that is using React version 15 as peer dependency. However, I want it to stop from throwing warnings for users that upgraded their React version. How do I make package support both version 15 and 16?

"peerDependencies": {
    "react-dom": "^15.0.0"
  },

which is the most convenient way to deal with these?

Is "*15.0.0" good enough?

Body:
Just checked some other packages on GitHub how they do it.

Using * didn't work out for me and therefore seems like bad practice anyway.

Better solution:

  "peerDependencies": {
    "react": ">=0.14.0 <= 16",
    "react-dom": ">=0.14.0 <= 16"
  }


问:
OHCL (Open-high-low-close) T-SQL Query
I'm trying to do a OHCL sql query (SQL Server 2012) on a StockData table. There are thousands of rows per day added to the table and I want to get the Open, High, Low and Close data for each day.

The create table sql is below:

```<code>  CREATE TABLE [dbo].[StockData](
    [ID] [bigint] IDENTITY(1,1) NOT NULL,
    [StockExchangeID] [bigint] NOT NULL,
    [DataDateTime] [datetime] NOT NULL,
    [ExportCost] [bigint] NOT NULL,
 CONSTRAINT [PK_StockData] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
</code>```

Using the query below I can get the High, Low and Average but I'm having difficulty getting the Open (earliest ExportCost based on DataDateTime) and Close (latest ExportCost based on DataDateTime) of the ExportCost for the day.

My query so far is below. If there is a more efficient way to do it then any suggestions welcome.

```<code>DECLARE @IntervalDays INT, @StartDate DATETIME, @EndDate DATETIME;
SET @IntervalDays = 1;
SET @StartDate = '01/01/2017'
SET @EndDate = '01/01/2018'

-- Create the database table
SELECT
    StockExchangeID,
    DATEADD(DAY, DATEDIFF(DAY,0,[DataDateTime]) / @IntervalDays * @IntervalDays, 0) AS [DateDay],
    MAX(ExportCost) AS DayHigh,
    MIN(ExportCost) AS DayLow,
    AVG(ExportCost) AS DayAverage,
    '??????????' As DayOpen, --Not sure how to get the start price for the day i.e. ExportCost for the first record for that day based on [DataDateTime]
    '??????????' As DatClose
FROM StockData
WHERE [DataDateTime] >= @StartDate AND [DataDateTime] <= @EndDate
GROUP BY DATEADD(DAY, DATEDIFF(DAY,0,[DataDateTime]) / @IntervalDays * @IntervalDays, 0), StockExchangeID
ORDER BY [DateDay]
</code>```

答:
For older versions of SQL Server use can use a correlated subquery:

```<code>SELECT
    StockExchangeID,
    DATEADD(DAY, DATEDIFF(DAY,0,[DataDateTime]) / @IntervalDays * @IntervalDays, 0) AS [DateDay],
    MAX(ExportCost) AS DayHigh,
    MIN(ExportCost) AS DayLow,
    AVG(ExportCost) AS DayAverage,
    (SELECT TOP 1 DO.ExportCost FROM StockData AS DO WHERE DO.[DataDateTime] = MIN( A.[DataDateTime] ) ORDER BY ID ASC ) As DayOpen,
    (SELECT TOP 1 DC.ExportCost FROM StockData AS DC WHERE DC.[DataDateTime] = MAX( A.[DataDateTime] ) ORDER BY ID DESC ) As DatClose
FROM StockData AS A
WHERE [DataDateTime] >= @StartDate AND [DataDateTime] <= @EndDate
GROUP BY DATEADD(DAY, DATEDIFF(DAY,0,[DataDateTime]) / @IntervalDays * @IntervalDays, 0), StockExchangeID
ORDER BY [DateDay]
</code>```

Note: Order By ID is used just in case you have more than 1 record with the same date.

For newer versions, take a look at @Serg comment about FIRST_VALUE

Title: OHCL (Open-high-low-close) T-SQL Query

Body:
I'm trying to do a OHCL sql query (SQL Server 2012) on a StockData table. There are thousands of rows per day added to the table and I want to get the Open, High, Low and Close data for each day.

The create table sql is below:

  CREATE TABLE [dbo].[StockData](
    [ID] [bigint] IDENTITY(1,1) NOT NULL,
    [StockExchangeID] [bigint] NOT NULL,
    [DataDateTime] [datetime] NOT NULL,
    [ExportCost] [bigint] NOT NULL,
 CONSTRAINT [PK_StockData] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Using the query below I can get the High, Low and Average but I'm having difficulty getting the Open (earliest ExportCost based on DataDateTime) and Close (latest ExportCost based on DataDateTime) of the ExportCost for the day.

My query so far is below. If there is a more efficient way to do it then any suggestions welcome.

DECLARE @IntervalDays INT, @StartDate DATETIME, @EndDate DATETIME;
SET @IntervalDays = 1;
SET @StartDate = '01/01/2017'
SET @EndDate = '01/01/2018'

-- Create the database table
SELECT
    StockExchangeID,
    DATEADD(DAY, DATEDIFF(DAY,0,[DataDateTime]) / @IntervalDays * @IntervalDays, 0) AS [DateDay],
    MAX(ExportCost) AS DayHigh,
    MIN(ExportCost) AS DayLow,
    AVG(ExportCost) AS DayAverage,
    '??????????' As DayOpen, --Not sure how to get the start price for the day i.e. ExportCost for the first record for that day based on [DataDateTime]
    '??????????' As DatClose
FROM StockData
WHERE [DataDateTime] >= @StartDate AND [DataDateTime] <= @EndDate
GROUP BY DATEADD(DAY, DATEDIFF(DAY,0,[DataDateTime]) / @IntervalDays * @IntervalDays, 0), StockExchangeID
ORDER BY [DateDay]

Body:
For older versions of SQL Server use can use a correlated subquery:

SELECT
    StockExchangeID,
    DATEADD(DAY, DATEDIFF(DAY,0,[DataDateTime]) / @IntervalDays * @IntervalDays, 0) AS [DateDay],
    MAX(ExportCost) AS DayHigh,
    MIN(ExportCost) AS DayLow,
    AVG(ExportCost) AS DayAverage,
    (SELECT TOP 1 DO.ExportCost FROM StockData AS DO WHERE DO.[DataDateTime] = MIN( A.[DataDateTime] ) ORDER BY ID ASC ) As DayOpen,
    (SELECT TOP 1 DC.ExportCost FROM StockData AS DC WHERE DC.[DataDateTime] = MAX( A.[DataDateTime] ) ORDER BY ID DESC ) As DatClose
FROM StockData AS A
WHERE [DataDateTime] >= @StartDate AND [DataDateTime] <= @EndDate
GROUP BY DATEADD(DAY, DATEDIFF(DAY,0,[DataDateTime]) / @IntervalDays * @IntervalDays, 0), StockExchangeID
ORDER BY [DateDay]

Note: Order By ID is used just in case you have more than 1 record with the same date.

For newer versions, take a look at @Serg comment about FIRST_VALUE


问:
How to get screenshot of full webpage using Selenium and Java?
How to take a screenshot of the entire web page (full-page screenshot), not only partial (top-to-bottom) using Selenium WebDriver?

My code: (Java bindings)

```<code>System.setProperty("webdriver.chrome.driver","/home/alex/Downloads/chromedriver_linux64/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://google.com");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(RESULT_FILENAME));
</code>```

Any ideas on how to tackle this?

答:
For some pages I neeed to take screenshot of begin and end of page. So I use to take 2 screenshots:</p>

```<code>public static String javaIoTmpDir = System.getProperty("java.io.tmpdir"); //tmp dir
//create screenshot
    driver.manage().window().fullscreen();
    //For large pages - body over 850 px highh - take addition screenshot of the end of page
    if (driver.findElements(By.id("panel_body")).size()>0) {
        WebElement body = driver.findElement(By.id("panel_body"));
        int bodyHight = body.getSize().getHeight();
        if (bodyHight > 850) {
            Robot robot = new Robot();
            robot.keyPress(KeyEvent.VK_END);
            robot.keyRelease(KeyEvent.VK_END);
            Thread.sleep(1000);
            File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            String timePictureEnd = javaIoTmpDir+"\\scr_"+String.valueOf(System.currentTimeMillis())+getClass().toString().substring(getClass().toString().lastIndexOf(".qa.")+3)+".png";
            FileUtils.copyFile(scrFile, new File(timePictureEnd));
            robot.keyPress(KeyEvent.VK_HOME); //back to top page for next screen
            robot.keyRelease(KeyEvent.VK_HOME);
            Thread.sleep(1000);
        }
    }
    String timePicture = javaIoTmpDir+"\\scr_"+String.valueOf(System.currentTimeMillis())+getClass().toString().substring(getClass().toString().lastIndexOf(".qa.")+3)+".png";
    File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File(timePicture));
</code>```

Body:
How to take a screenshot of the entire web page (full-page screenshot), not only partial (top-to-bottom) using Selenium WebDriver?

My code: (Java bindings)

System.setProperty("webdriver.chrome.driver","/home/alex/Downloads/chromedriver_linux64/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://google.com");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(RESULT_FILENAME));

Any ideas on how to tackle this?

Body:
For some pages I neeed to take screenshot of begin and end of page. So I use to take 2 screenshots:

public static String javaIoTmpDir = System.getProperty("java.io.tmpdir"); //tmp dir
//create screenshot
    driver.manage().window().fullscreen();
    //For large pages - body over 850 px highh - take addition screenshot of the end of page
    if (driver.findElements(By.id("panel_body")).size()>0) {
        WebElement body = driver.findElement(By.id("panel_body"));
        int bodyHight = body.getSize().getHeight();
        if (bodyHight > 850) {
            Robot robot = new Robot();
            robot.keyPress(KeyEvent.VK_END);
            robot.keyRelease(KeyEvent.VK_END);
            Thread.sleep(1000);
            File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            String timePictureEnd = javaIoTmpDir+"\\scr_"+String.valueOf(System.currentTimeMillis())+getClass().toString().substring(getClass().toString().lastIndexOf(".qa.")+3)+".png";
            FileUtils.copyFile(scrFile, new File(timePictureEnd));
            robot.keyPress(KeyEvent.VK_HOME); //back to top page for next screen
            robot.keyRelease(KeyEvent.VK_HOME);
            Thread.sleep(1000);
        }
    }
    String timePicture = javaIoTmpDir+"\\scr_"+String.valueOf(System.currentTimeMillis())+getClass().toString().substring(getClass().toString().lastIndexOf(".qa.")+3)+".png";
    File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File(timePicture));


问:
Modifying object for each web service call
In our web application we have a lot of REST services. Suddenly it found out that we need to modify one object inside of each request before we go on.
So let's say we have n different controllers with REST services. In each controller, before we call the service from next layer, we need to modify an object inside the request.

The question is how to achieve this without providing hundreds of changes inside the controllers... Is there any simple way to do this?

UPDATE:

```<code>@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    @RequestMapping(path = "/order", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public OrderResponse getOrderData(@RequestHeader HttpHeaders httpHeaders,
            @RequestBody OrderDataRequest orderDataRequest) {

        // Use here interceptor to modify the object Details
        // (inside OrderDataRequest) before below call:
        OrderResponse resp = orderService.getOrderData(orderDataRequest);

        return resp;
    }

    @RequestMapping(path = "/cancel/{orderId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public boolean cancelOrder(@RequestHeader HttpHeaders httpHeaders,
            @RequestBody Details details, @PathVariable Integer orderId) {

        // Use here interceptor to modify object Details before below call:
        return orderService.cancelOrder(details, orderId);
    }
}
</code>```

In each controller I need to modift the object Details, which as you can see could be inside another object like in the first example or exist alone like in the second option.

答:
You should consider writing an interceptor, that would allow you to do what you want .

You could also use AOP to do this.. though, I think it's quite over-complicated, especially when such a solution already exists through interceptors!

EDIT :
A few other links :

EDIT 2 :
Follow the "before advice" from mykong.com example, then go that way to edit your specific object according to its class (for exemple) :

```<code>package com.your.company;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

public class HijackBeforeMethod implements MethodBeforeAdvice
{
    @Override
    public void before(Method method, Object[] args, Object target)
        throws Throwable {
            for(Object arg :  args) {
                if(com.your.company.OrderDataRequest.class.isAssignableFrom(arg.getClass())) {
                    // update you object here
                }
            }
    }
}
</code>```

- Get response body
 - Json To Java

Body:
In our web application we have a lot of REST services. Suddenly it found out that we need to modify one object inside of each request before we go on.
So let's say we have n different controllers with REST services. In each controller, before we call the service from next layer, we need to modify an object inside the request.

The question is how to achieve this without providing hundreds of changes inside the controllers... Is there any simple way to do this?

UPDATE:

@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    @RequestMapping(path = "/order", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public OrderResponse getOrderData(@RequestHeader HttpHeaders httpHeaders,
            @RequestBody OrderDataRequest orderDataRequest) {

        // Use here interceptor to modify the object Details
        // (inside OrderDataRequest) before below call:
        OrderResponse resp = orderService.getOrderData(orderDataRequest);

        return resp;
    }

    @RequestMapping(path = "/cancel/{orderId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public boolean cancelOrder(@RequestHeader HttpHeaders httpHeaders,
            @RequestBody Details details, @PathVariable Integer orderId) {

        // Use here interceptor to modify object Details before below call:
        return orderService.cancelOrder(details, orderId);
    }
}

In each controller I need to modift the object Details, which as you can see could be inside another object like in the first example or exist alone like in the second option.

Body:
You should consider writing an interceptor, that would allow you to do what you want .

You could also use AOP to do this.. though, I think it's quite over-complicated, especially when such a solution already exists through interceptors!

EDIT :
A few other links :

EDIT 2 :
Follow the "before advice" from mykong.com example, then go that way to edit your specific object according to its class (for exemple) :

package com.your.company;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

public class HijackBeforeMethod implements MethodBeforeAdvice
{
    @Override
    public void before(Method method, Object[] args, Object target)
        throws Throwable {
            for(Object arg :  args) {
                if(com.your.company.OrderDataRequest.class.isAssignableFrom(arg.getClass())) {
                    // update you object here
                }
            }
    }
}

- Get response body
 - Json To Java


问:
How to import multiple csv files in local DB?
I have a requirement of importing multiple files from a folder into a local DB table. column structures are same. Row count varies from 25 k to 200 k in each file.

which tool can be used to do it faster? like Sql server, oracle or Mysql

答:
You can use SQL Server with OPENROWSET.
    1. https://learn.microsoft.com/en-us/sql/t-sql/functions/openrowset-transact-sql
You can import multiple files in one query but it will depend on your needs.</p>


问:
Why there is not `package` type of thing by default in postgres like oracle have?
Why postgres have not given  package like thing ,so that same type of function can be placed inside a individual collective unit . In current approach if postgres we have too write individual function that make to messy for origination of code.

答:
There is Schema to classify function is needed.
If a schema name is included, then the function is created in the specified schema. Otherwise it is created in the current schema. The name of the new function must not match any existing function with the same input argument types in the same schema. However, functions of different argument types can share a name (this is called overloading).</p>