问:
MySQL query with several nested JOINs
I have 3 tables:

soccer_players

playersPoints

soccer_fixtures

and I took me hours to build this query here:

```<code>SELECT * FROM `soccer_players`

INNER JOIN `playersPoints` ON `soccer_players`.player_id
=`playersPoints`.playerID

INNER JOIN `soccer_fixtures`
    ON soccer_players.team_id = soccer_fixtures.home_team_id

WHERE soccer_fixtures.home_team_id IN (528,529,530, 531, 532, 533,
534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545)

AND soccer_fixtures.season_id = 2201
AND position != 'Coach' AND soccer_fixtures.status = "NS"
AND soccer_fixtures.game_week = 32

ORDER BY `soccer_players`.`player_name` ASC
</code>```

and my result is good, but my problem is that I want to add after

```<code>INNER JOIN `soccer_fixtures`
    ON soccer_players.team_id = soccer_fixtures.home_team_id
</code>```

this:

```<code>INNER JOIN `soccer_fixtures`
    ON soccer_players.team_id = soccer_fixtures.away_team_id
</code>```

My goal is to filter football players from a table, join them with the points of these players and join this result then with the fixtures of this gameweek that I can display, which player is playing on which date.

I know what the problem is but I don't know how to solve it.

There can't be 2 INNER JOINs with the same name but how can I group these two INNER JOINs to one?

EDIT:

I have also tried the following:

```<code>SELECT * FROM `soccer_players`

INNER JOIN `playersPoints` ON `soccer_players`.player_id
=`playersPoints`.playerID

INNER JOIN `soccer_fixtures`
    RIGHT JOIN soccer_players
    (
        ON soccer_fixtures.team_id = soccer_fixtures.home_team_id
        ON soccer_fixtures.team_id = soccer_fixtures.a_team_id
    )

WHERE

soccer_fixtures.home_team_id IN (528,529,530, 531, 532, 533,
534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545)

OR

soccer_fixtures.a_team_id IN (528,529,530, 531, 532, 533,
534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545)

AND soccer_fixtures.season_id = 2201
AND position != 'Coach' AND soccer_fixtures.status = "NS"
AND soccer_fixtures.game_week = 32

ORDER BY `soccer_players`.`player_name` ASC
</code>```

without success, but I think that's close to the solution.

EDIT2:

ok now I have this solution here:
the result is wonderfull! I am wondered a lil bit about the perfomance, it took really long now to get the correct result. Can i modify the query a lil bit to get the results from my 3 tabkles faster?

here is my modiefied version now:

Big Thx to Thorsten!

答:
You want to select players that have a match with status NS in week 32. So select from players. Criteria (match with status and week) belongs in the WHERE clause. As a player can have many points, add up each players point and outer join them to the players.

```<code>select sp.name, coalesce(pp.total_points, 0) as points
from soccer_players sp
left join
(
  select playerid, sum(points) as total_points
  from playerspoints
  group by playerid
) pp on pp.playerid = sp.player_id
where exists
(
  select *
  from soccer_fixtures sf
  where sf.season_id = 2201
    and sf.game_week = 32
    and sf.status = 'NS'
    and sp.team_id in (sf.home_team_id, sf.away_team_id)
);
</code>```

(Instead of putting the points subquery in the FROM clause, you can also have it in the SELECT clause, but generally we prefer the outer join in FROM, so we can select more than one column if necessary.)

Title: MySQL query with several nested JOINs

Body:
I have 3 tables:

soccer_players

playersPoints

soccer_fixtures

and I took me hours to build this query here:

SELECT * FROM `soccer_players`

INNER JOIN `playersPoints` ON `soccer_players`.player_id
=`playersPoints`.playerID

INNER JOIN `soccer_fixtures`
    ON soccer_players.team_id = soccer_fixtures.home_team_id

WHERE soccer_fixtures.home_team_id IN (528,529,530, 531, 532, 533,
534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545)

AND soccer_fixtures.season_id = 2201
AND position != 'Coach' AND soccer_fixtures.status = "NS"
AND soccer_fixtures.game_week = 32

ORDER BY `soccer_players`.`player_name` ASC

and my result is good, but my problem is that I want to add after

INNER JOIN `soccer_fixtures`
    ON soccer_players.team_id = soccer_fixtures.home_team_id

this:

INNER JOIN `soccer_fixtures`
    ON soccer_players.team_id = soccer_fixtures.away_team_id

My goal is to filter football players from a table, join them with the points of these players and join this result then with the fixtures of this gameweek that I can display, which player is playing on which date.

I know what the problem is but I don't know how to solve it.

There can't be 2 INNER JOINs with the same name but how can I group these two INNER JOINs to one?

EDIT:

I have also tried the following:

SELECT * FROM `soccer_players`

INNER JOIN `playersPoints` ON `soccer_players`.player_id
=`playersPoints`.playerID

INNER JOIN `soccer_fixtures`
    RIGHT JOIN soccer_players
    (
        ON soccer_fixtures.team_id = soccer_fixtures.home_team_id
        ON soccer_fixtures.team_id = soccer_fixtures.a_team_id
    )

WHERE

soccer_fixtures.home_team_id IN (528,529,530, 531, 532, 533,
534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545)

OR

soccer_fixtures.a_team_id IN (528,529,530, 531, 532, 533,
534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545)

AND soccer_fixtures.season_id = 2201
AND position != 'Coach' AND soccer_fixtures.status = "NS"
AND soccer_fixtures.game_week = 32

ORDER BY `soccer_players`.`player_name` ASC

without success, but I think that's close to the solution.

EDIT2:

ok now I have this solution here:
the result is wonderfull! I am wondered a lil bit about the perfomance, it took really long now to get the correct result. Can i modify the query a lil bit to get the results from my 3 tabkles faster?

here is my modiefied version now:

Big Thx to Thorsten!

Body:
You want to select players that have a match with status NS in week 32. So select from players. Criteria (match with status and week) belongs in the WHERE clause. As a player can have many points, add up each players point and outer join them to the players.

select sp.name, coalesce(pp.total_points, 0) as points
from soccer_players sp
left join
(
  select playerid, sum(points) as total_points
  from playerspoints
  group by playerid
) pp on pp.playerid = sp.player_id
where exists
(
  select *
  from soccer_fixtures sf
  where sf.season_id = 2201
    and sf.game_week = 32
    and sf.status = 'NS'
    and sp.team_id in (sf.home_team_id, sf.away_team_id)
);

(Instead of putting the points subquery in the FROM clause, you can also have it in the SELECT clause, but generally we prefer the outer join in FROM, so we can select more than one column if necessary.)


来源: stackexchange

问:
Is this too many dependencies to inject into an object through the constructor?
I am working on a social network type project in OO PHP and I do not want to use an existing framework.  The main point of doing this project is to help me learn about more stuff.

This question is more about dependency injection.

Let's say I have these classes:

core class - some core methods to do stuff in the app

config class - loads site config stuff

database class - connects to mysql and does all database related stuff

logger class - used to log errors and debug info

captcha class - for captcha on forms

session class - initiates a session start and adds, removes, gets session variables to use in the app

cache class - similar to session class but for caches items (files cache, memcache, apc cache.  I may even add my session stuff to this class someday since all these cache's can use the same type of methods)

All the classes above will most likely be used on every page load in my app (I probably missed some more classes that will be added later on)

Now in addition to the above classes which will need to be injected into most other classes, I will have many many more classes.  I will have a secion called modules which will have stuff like...

account class - creates new users, authenticates users, logs users in and out of the app, update user settings, and much more.

users class - shows users profiles, shows users online, new users, all stuff to show users of the site

forums class - will be for the forums section

blogs class - for the blogs section

photos class - all photo related stuff

comments class - handles comments for photos and profiles

There will be many more of these type of classes for different sections of the site.

This second set of classes listed above for sections will most likely require most of the classes from the first set to be injected into them.

So should I use a registry to store the objects from the first set of classes and just inject the registry into all the class objects in the second set of classes?

Or should I use the constructor to load them?  In this example there would be like 7 objects to inject into the other classes, that seems like a lot.  Am I going about this wrong?

---EDIT---

I am aware of the singleton pattern but I don't think it is my best option here

---EDIT 2---

As some have mention, needing to pass in as much as 7 objects does seem like a LOT and that is why I am looking for suggestions.  Luckily for me this project is at the beginning stages so now is the time for changes to the structure.

An example would be a class in my forums section.  The forums class would need access to session data, possible cached data, the configs object, database object.  AM I going about this the wrong way?

答:
Or should I use the constructor to load them? In this example there would be like 7 objects to inject into the other classes, that seems like a lot. Am I going about this wrong?

When you start needing to inject that many objects, you need to ask whether the object that receives them is responsible for too much.  Can it be broken down into smaller pieces?

If it really can't, then consider encapsulating related objects in another class.  Perhaps your session, logger, and config objects can be injected into an App or Application object?

Edit: I notice most of the other answers so far talk about Singletons.  Note that Singletons are the enemy of DI.  Great Google tech talk on this here.

Edit 2:

What I mean by encapsulating is, instead of injecting Session, Logger, Config, etc. all into your Account class, maybe they should be injected into an Application class, and an Application instance can be injected into Account.

To be honest, this is still a piece of DI I'm wrapping me head around, but what I'm starting to see is this: You should only inject into Account the objects it will directly need to manipulate.  Those objects may need to manipulate yet other objects, but Account doesn't need to know about it.

Often, you'll find you don't even need as many "layers" as you thought, though.  If you find you're injecting stuff all over the place, consider various ways of re-structuring your application.  Let me pull a piece of code from the Pylons documentation on the model:

```<code>a = model.Person()
a.name = "Aaa"
a.email = "aaa@example.com"
meta.Session.add(a)
</code>```

(Don't worry about meta.Session... basically it handles interaction with the database.)

Here, we instantiate a Person, set a couple of its attributes, and then save it.  You'll notice the Person class knows nothing about the database, and in fact doesn't even have a save() method.  Instead, we pass it to the database class (meta.Session) which saves it.  We've separated concern for Person logic from the database code.  meta.Session could work a dozen different ways, but as long as it knows how to read Person, we're fine. (in this case, during application initialization, it read the definition of all the application's models).

Okay, I'm going to sum up, because I've obviously rambled a lot here.  There is no one "correct" answer to your question (as far as I know, but I don't proclaim to be a DI expert by any means).

Yes, injecting several objects is probably indication of some need to restructure, but you have a number of considerations to make:

Is the object receiving the injection responsible for too much; can it be separated out?

Are you only injecting objects that the recipient class will directly need to utilize?

Are you injecting the wrong direction; can your Account object be injected into your Database instead of the other way around?

ContentLicense: CC BY-SA 3.0

Body:
Or should I use the constructor to load them? In this example there would be like 7 objects to inject into the other classes, that seems like a lot. Am I going about this wrong?

When you start needing to inject that many objects, you need to ask whether the object that receives them is responsible for too much.  Can it be broken down into smaller pieces?

If it really can't, then consider encapsulating related objects in another class.  Perhaps your session, logger, and config objects can be injected into an App or Application object?

Edit: I notice most of the other answers so far talk about Singletons.  Note that Singletons are the enemy of DI.  Great Google tech talk on this here.

Edit 2:

What I mean by encapsulating is, instead of injecting Session, Logger, Config, etc. all into your Account class, maybe they should be injected into an Application class, and an Application instance can be injected into Account.

To be honest, this is still a piece of DI I'm wrapping me head around, but what I'm starting to see is this: You should only inject into Account the objects it will directly need to manipulate.  Those objects may need to manipulate yet other objects, but Account doesn't need to know about it.

Often, you'll find you don't even need as many "layers" as you thought, though.  If you find you're injecting stuff all over the place, consider various ways of re-structuring your application.  Let me pull a piece of code from the Pylons documentation on the model:

a = model.Person()
a.name = "Aaa"
a.email = "aaa@example.com"
meta.Session.add(a)

(Don't worry about meta.Session... basically it handles interaction with the database.)

Here, we instantiate a Person, set a couple of its attributes, and then save it.  You'll notice the Person class knows nothing about the database, and in fact doesn't even have a save() method.  Instead, we pass it to the database class (meta.Session) which saves it.  We've separated concern for Person logic from the database code.  meta.Session could work a dozen different ways, but as long as it knows how to read Person, we're fine. (in this case, during application initialization, it read the definition of all the application's models).

Okay, I'm going to sum up, because I've obviously rambled a lot here.  There is no one "correct" answer to your question (as far as I know, but I don't proclaim to be a DI expert by any means).

Yes, injecting several objects is probably indication of some need to restructure, but you have a number of considerations to make:

Is the object receiving the injection responsible for too much; can it be separated out?

Are you only injecting objects that the recipient class will directly need to utilize?

Are you injecting the wrong direction; can your Account object be injected into your Database instead of the other way around?

ContentLicense: CC BY-SA 2.5


问:
JPA/Hibernate Custom Queries with optional parameters
I have an Entity

```<code>@Entity
@Table(name = "EVENT")
public class Event {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @Column(name = "EVENT", columnDefinition="VARCHAR(100)", nullable = false)
    private String event;

    @Column(name = "DATE", columnDefinition="DATETIME", nullable = false)
    @Convert(converter = InstantConverter.class)
    private Instant date;
}
</code>```

And a SearchParams class where all of the fields are optional

```<code>public class SearchParams {
    private Long id;
    private Instant startDate;
    private Instant endDate;
    private String event;

    public Optional<Long> getID() {
        return Optional.ofNullable(id);
    }
    // ... Similar for other fields ...
}
</code>```

I would like to be able to search like:

```<code>public List<Event> search(SearchParams searchParams) {
    // Do something with Entity Manager/another hibernate class to create a custom query based off the search params.
    return events;
}
</code>```

What's the easiest way to achieve this in JPA? Or is this not the right framework to use?

I could always resort to sql string building but its not a nice way of doing it.

答:
The Spring Data JPA query-by-example technique uses Examples and ExampleMatchers to convert entity instances into the underlying query. The current official documentation clarifies that only exact matching is available for non-string attributes. Since your requirement involves a Date field, you can only have exact matching with the query-by-example technique.

Refer https://stackoverflow.com/a/39555487/4939174

You can also refer this link for Spring Data JPA - Specifications and Querydsl

Body:
I have an Entity

@Entity
@Table(name = "EVENT")
public class Event {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @Column(name = "EVENT", columnDefinition="VARCHAR(100)", nullable = false)
    private String event;

    @Column(name = "DATE", columnDefinition="DATETIME", nullable = false)
    @Convert(converter = InstantConverter.class)
    private Instant date;
}

And a SearchParams class where all of the fields are optional

public class SearchParams {
    private Long id;
    private Instant startDate;
    private Instant endDate;
    private String event;

    public Optional<Long> getID() {
        return Optional.ofNullable(id);
    }
    // ... Similar for other fields ...
}

I would like to be able to search like:

public List<Event> search(SearchParams searchParams) {
    // Do something with Entity Manager/another hibernate class to create a custom query based off the search params.
    return events;
}

What's the easiest way to achieve this in JPA? Or is this not the right framework to use?

I could always resort to sql string building but its not a nice way of doing it.


问:
How to "clear" an object?
What's the better way to clear an object:

Write a method inside the class that clears all the members of the class: MyObject.Clear();

Inside my code, in the business logic, null the object: MyObject = null;

答:
I would recommend just constructing a new instance of the object, instead of clearing it.

If you are done with an object, but not the class containing its reference, setting it to null may be appropriate.  However, if it's just being used within a method, you don't have to do anything (the garbage collector will clean it up sometime after there are no references to the object) - just let it "go away" by letting it fall out of scope.  If it's in a collection, you can just remove it from the collection.

The one exception is if the object implements IDisposable.  In this case, you may want to call it's Dispose() method, or try to structure your code to use it within a using block, in order for its resources to be cleaned up appropriately.

ContentLicense: CC BY-SA 4.0

Title: How to "clear" an object?


问:
GCC does not complain about re-definition of external variable?
This simple code (MCVE):

```<code>#include <stdio.h>

int a = 3;
int main(){
    printf("%d\n", a);
    return 0;
}
int a; // This line
</code>```

To my surprise, GCC (MinGW GCC 4.8.2, 4.9.2 and 6.3.0) does not give any error, not even warnings about the marked line! However it does if I assign a value to a at its second definition.

More strangely, g++ tells me that the second re-definition is an error, but gcc doesn't.

Isn't it supposed to be a re-definition of an existing variable because there's no keyword extern?

答:
It is called tentative definitions in C.

Cppreference say's :

Tentative definitions

A tentative definition is an external declaration without an
  initializer, and either without a storage-class specifier or with the
  specifier static.

A tentative definition is a declaration that may or may not act as a
  definition. If an actual external definition is found earlier or later
  in the same translation unit, then the tentative definition just acts
  as a declaration.

[...]

```<code>int i3; // tentative definition, external linkage

int i3; // tentative definition, external linkage

extern int i3; // declaration, external linkage
</code>```

Body:
This simple code (MCVE):

#include <stdio.h>

int a = 3;
int main(){
    printf("%d\n", a);
    return 0;
}
int a; // This line

To my surprise, GCC (MinGW GCC 4.8.2, 4.9.2 and 6.3.0) does not give any error, not even warnings about the marked line! However it does if I assign a value to a at its second definition.

More strangely, g++ tells me that the second re-definition is an error, but gcc doesn't.

Isn't it supposed to be a re-definition of an existing variable because there's no keyword extern?

Body:
It is called tentative definitions in C.

Cppreference say's :

Tentative definitions

A tentative definition is an external declaration without an
  initializer, and either without a storage-class specifier or with the
  specifier static.

A tentative definition is a declaration that may or may not act as a
  definition. If an actual external definition is found earlier or later
  in the same translation unit, then the tentative definition just acts
  as a declaration.

[...]

int i3; // tentative definition, external linkage

int i3; // tentative definition, external linkage

extern int i3; // declaration, external linkage


问:
How to get from a subscriptions data to transactional data in Tableau?
I have a chunk of data with subscriptions looking as following:

```<code>customer_name    start_date   end_date     subscription_amount
A                1-7-2017     31-10-2017   4 USD/month
B                1-8-2017     30-09-2017   2 USD/month
C                1-10-2017    30-11-2017   3 USD/month
</code>```

I need to convert it to transactional data, so the end result should look as following:

```<code>customer_name    payment_date    amount
A                1-7-2017        4 USD
A                1-8-2017        4 USD
A                1-9-2017        4 USD
A                1-10-2017       4 USD
B                1-8-2017        2 USD
B                1-9-2017        2 USD
C                1-10-2017       3 USD
C                1-11-2017       3 USD
</code>```

I need to do this conversion to run the analysis in Tableau, but Excel solutions are also acceptable. I do not want to do it manually, rather I am looking for automated solution with SQL or Python (I am new to both of those)

答:
Using python (you need a little format your data to match exactly with your Question, but the idea is here) http://rextester.com/OENHUT92986

use this comprehensive list listMonths = [dt.strftime("%Y-%m-01") for dt in rrule(MONTHLY, dtstart=dtstart, until=until) to list every first day of each month between 2 date.

```<code>import datetime
import time
from dateutil import parser
from dateutil.rrule import rrule, MONTHLY

data=[
      {"customer_name":"A" ,"start_date":"2017-07-01","end_date":"2017-10-31","subscription_amount":"4 USD/month"},
      {"customer_name":"B" ,"start_date":"2017-08-01","end_date":"2017-09-30","subscription_amount":"2 USD/month"},
      {"customer_name":"C" ,"start_date":"2017-10-01","end_date":"2017-11-30","subscription_amount":"3 USD/month"}
     ]

for datum in data :
    dtstart=parser.parse(datum["start_date"])
    until=parser.parse(datum["end_date"])

    listMonths = [dt.strftime("%Y-%m-01") for dt in rrule(MONTHLY, dtstart=dtstart, until=until)]

    for month in listMonths :
         print datum["customer_name"],month,datum["subscription_amount"]
</code>```

will produce :

```<code>A 2017-07-01 4 USD/month
A 2017-08-01 4 USD/month
A 2017-09-01 4 USD/month
A 2017-10-01 4 USD/month
B 2017-08-01 2 USD/month
B 2017-09-01 2 USD/month
C 2017-10-01 3 USD/month
C 2017-11-01 3 USD/month
</code>```

Body:
I have a chunk of data with subscriptions looking as following:

customer_name    start_date   end_date     subscription_amount
A                1-7-2017     31-10-2017   4 USD/month
B                1-8-2017     30-09-2017   2 USD/month
C                1-10-2017    30-11-2017   3 USD/month

I need to convert it to transactional data, so the end result should look as following:

customer_name    payment_date    amount
A                1-7-2017        4 USD
A                1-8-2017        4 USD
A                1-9-2017        4 USD
A                1-10-2017       4 USD
B                1-8-2017        2 USD
B                1-9-2017        2 USD
C                1-10-2017       3 USD
C                1-11-2017       3 USD

I need to do this conversion to run the analysis in Tableau, but Excel solutions are also acceptable. I do not want to do it manually, rather I am looking for automated solution with SQL or Python (I am new to both of those)

Body:
Using python (you need a little format your data to match exactly with your Question, but the idea is here) http://rextester.com/OENHUT92986

use this comprehensive list listMonths = [dt.strftime("%Y-%m-01") for dt in rrule(MONTHLY, dtstart=dtstart, until=until) to list every first day of each month between 2 date.

import datetime
import time
from dateutil import parser
from dateutil.rrule import rrule, MONTHLY

data=[
      {"customer_name":"A" ,"start_date":"2017-07-01","end_date":"2017-10-31","subscription_amount":"4 USD/month"},
      {"customer_name":"B" ,"start_date":"2017-08-01","end_date":"2017-09-30","subscription_amount":"2 USD/month"},
      {"customer_name":"C" ,"start_date":"2017-10-01","end_date":"2017-11-30","subscription_amount":"3 USD/month"}
     ]

for datum in data :
    dtstart=parser.parse(datum["start_date"])
    until=parser.parse(datum["end_date"])

    listMonths = [dt.strftime("%Y-%m-01") for dt in rrule(MONTHLY, dtstart=dtstart, until=until)]

    for month in listMonths :
         print datum["customer_name"],month,datum["subscription_amount"]

will produce :

A 2017-07-01 4 USD/month
A 2017-08-01 4 USD/month
A 2017-09-01 4 USD/month
A 2017-10-01 4 USD/month
B 2017-08-01 2 USD/month
B 2017-09-01 2 USD/month
C 2017-10-01 3 USD/month
C 2017-11-01 3 USD/month


问:
history.pushState not working in Chrome on iOS when executing without an interaction
It seems like history.pushState is not working in Chrome on iOS when executed manually without any touch/click interaction.

I need help with understanding why iOS Chrome does this, and if possible, how to fix it.

https://codepen.io/grymer/pen/OOmebv

Here is a codepen with a minimum working example.
To test it, you need to fork the pen and go into debug view in Chrome on an iOS device.

Then you will see "a button that says "To B". Press it and then use browser back. You will see that this behavior differs from any other browser.

```<code>var React, { Component } = React;
var { BrowserRouter, Redirect, Route, Switch } = ReactRouterDOM;

class App extends Component {
  render() {
    return (
      <BrowserRouter basename={location.href}>
        <Switch>
          <Route path="/b" component={B} />
          <Route component={A} />
        </Switch>
      </BrowserRouter>
    );
  }
}

class A extends Component {
  constructor() {
    super();

    this.state = {};

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

  render() {
    if(this.state.redirect) {
      return <Redirect push to="/b" />
    }

    return (
      <div>
        On page A
        <button onClick={this.handleClick}>To B</button>
      </div>
    );
  }

  handleClick() {
    this.setState({ redirect: true });
  }
}

class B extends Component {
  constructor() {
    super();

    this.state = {
      showModal: false
    };

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

  componentDidMount() {
    this.button.click(); // comment this line to manually open the modal by tapping the button
  }

  render() {
    return (
      <div>
        On page B
        { this.state.showModal ? <Modal history={this.props.history} onClose={() => this.setState({ showModal: false }) } /> : null }
        <button ref={(el) => this.button = el } onClick={this.handleClick}>Open modal</button>
      </div>
    );
  }

  handleClick() {
    this.setState({
      showModal: true
    });
  }
}

class Modal extends Component {
  constructor() {
    super();

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

  componentDidMount() {
    this.props.history.push(this.props.history.location.pathname, { type: 'modal' });
    window.addEventListener('popstate', this.onPopState);
  }

  componentWillUnmount() {
    window.removeEventListener('popstate', this.onPopState);
  }

  render() {
    return (
      <div>
        Modal is opened
        <button onClick={this.handleClick}>Close modal</button>
      </div>
    );
  }

  handleClick() {
    this.props.onClose();
    this.props.history.goBack();
  }

  onPopState() {
    this.props.onClose();
  }
}

ReactDOM.render(<App />, document.getElementById('react-container'));
</code>```

答:
Chromium team has acknowledged and they are working on a fix.

https://bugs.chromium.org/p/chromium/issues/detail?id=783382#c3

Body:
It seems like history.pushState is not working in Chrome on iOS when executed manually without any touch/click interaction.

I need help with understanding why iOS Chrome does this, and if possible, how to fix it.

https://codepen.io/grymer/pen/OOmebv

Here is a codepen with a minimum working example.
To test it, you need to fork the pen and go into debug view in Chrome on an iOS device.

Then you will see "a button that says "To B". Press it and then use browser back. You will see that this behavior differs from any other browser.

var React, { Component } = React;
var { BrowserRouter, Redirect, Route, Switch } = ReactRouterDOM;

class App extends Component {
  render() {
    return (
      <BrowserRouter basename={location.href}>
        <Switch>
          <Route path="/b" component={B} />
          <Route component={A} />
        </Switch>
      </BrowserRouter>
    );
  }
}

class A extends Component {
  constructor() {
    super();

    this.state = {};

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

  render() {
    if(this.state.redirect) {
      return <Redirect push to="/b" />
    }

    return (

        On page A
        <button onClick={this.handleClick}>To B</button>

    );
  }

  handleClick() {
    this.setState({ redirect: true });
  }
}

class B extends Component {
  constructor() {
    super();

    this.state = {
      showModal: false
    };

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

  componentDidMount() {
    this.button.click(); // comment this line to manually open the modal by tapping the button
  }

  render() {
    return (

        On page B
        { this.state.showModal ? <Modal history={this.props.history} onClose={() => this.setState({ showModal: false }) } /> : null }
        <button ref={(el) => this.button = el } onClick={this.handleClick}>Open modal</button>

    );
  }

  handleClick() {
    this.setState({
      showModal: true
    });
  }
}

class Modal extends Component {
  constructor() {
    super();

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

  componentDidMount() {
    this.props.history.push(this.props.history.location.pathname, { type: 'modal' });
    window.addEventListener('popstate', this.onPopState);
  }

  componentWillUnmount() {
    window.removeEventListener('popstate', this.onPopState);
  }

  render() {
    return (

        Modal is opened
        <button onClick={this.handleClick}>Close modal</button>

    );
  }

  handleClick() {
    this.props.onClose();
    this.props.history.goBack();
  }

  onPopState() {
    this.props.onClose();
  }
}

ReactDOM.render(<App />, document.getElementById('react-container'));


问:
ControlToValidate fires on all clicks: I only want it to fire when I click the "Submit" button
I have a textbox that is validated to make sure there is text content, for a file upload page.

My problem is that when the page has first loaded and you click anyway where on the page, the ControlToValidate fires immediately, this is an issue because I only want the page to validate the text box when you click the upload button.

You end up being trapped on the Upload File page until you type some random text into the textbox, even if you click a link to get somewhere else in the site (i.e the logo to get back to the mainpage).

Here is my relevant code snippet:

```<code> <asp:Label runat="server">Name</asp:Label>:
<br />
<asp:TextBox runat="server" ID="txtName"></asp:TextBox><asp:RequiredFieldValidator
    runat="server" ID="txtNameRequired" Display="Dynamic" ControlToValidate="txtName"
    Text="Name is required." CssClass="errorText" /><br />

<asp:Button runat="server" ID="btnUpload" Text="Upload" OnClick="btnUpload_Click" />
</asp:Panel>
</code>```

So I have a couple ideas but was not sure how to implement them :

1) find some property that will link the ControlToValidate solely to the clicking of the upload button.

or

2) Set up ControlToValidate so that it is only called on PostBacks

I am just not sure where to start and haven't been able to find any properties that specifically do this!

Thank you very much for your time !

答: Set the ValidationGroup property of the button and the controls to validate to the same value.</p>

Body:
I have a textbox that is validated to make sure there is text content, for a file upload page.

My problem is that when the page has first loaded and you click anyway where on the page, the ControlToValidate fires immediately, this is an issue because I only want the page to validate the text box when you click the upload button.

You end up being trapped on the Upload File page until you type some random text into the textbox, even if you click a link to get somewhere else in the site (i.e the logo to get back to the mainpage).

Here is my relevant code snippet:

 <asp:Label runat="server">Name</asp:Label>:

<asp:TextBox runat="server" ID="txtName"></asp:TextBox><asp:RequiredFieldValidator
    runat="server" ID="txtNameRequired" Display="Dynamic" ControlToValidate="txtName"
    Text="Name is required." CssClass="errorText" />

<asp:Button runat="server" ID="btnUpload" Text="Upload" OnClick="btnUpload_Click" />
</asp:Panel>

So I have a couple ideas but was not sure how to implement them :

1) find some property that will link the ControlToValidate solely to the clicking of the upload button.

or

2) Set up ControlToValidate so that it is only called on PostBacks

I am just not sure where to start and haven't been able to find any properties that specifically do this!

Thank you very much for your time !


问:
How to put header information in swagger json
I followed the following link from swagger documentation to create swagger json for my rest api.

https://swagger.io/docs/specification/2-0/describing-request-body/

In my rest api, I have request body and  http headers like Content-Type and Authorization that go along with the service request.

I was wondering if there is a way to include request body and http header information in the swagger json ? I don't see that information in the swagger docs.

答:
The Content-Type header of requests and responses is defined by the consumes and produces keywords, respectively. They can be specified on the operation level or on the root level of the spec.

The Authorization header is defined using the securityDefinitions and security keywords. OpenAPI/Swagger 2.0 supports Basic authentication, API keys and OAuth 2.

Other headers can be defined as in: header parameters.

For example, if an operation POSTs JSON and uses Basic auth, you can describe it as follows:

swagger: '2.0'
...

securityDefinitions:   # Authorization, part 1
  basicAuth:
    type: basic

paths:
  /something:
    post:
      summary: POST some JSON
      consumes:
        - application/json  # Request Content-Type
      produces:
        - application/json  # Response Content-Type
      security:
        - basicAuth: []     # Authorization, part 2
      parameters:
        - in: body
          name: body
          required: true
          schema:
            $ref: '#/definitions/Something'
      responses:
        200:
          description: OK
```

Relevant documentation:

MIME Types

Authentication

Describing Parameters

Body:
The Content-Type header of requests and responses is defined by the consumes and produces keywords, respectively. They can be specified on the operation level or on the root level of the spec.

The Authorization header is defined using the securityDefinitions and security keywords. OpenAPI/Swagger 2.0 supports Basic authentication, API keys and OAuth 2.

Other headers can be defined as in: header parameters.

For example, if an operation POSTs JSON and uses Basic auth, you can describe it as follows:

swagger: '2.0'
...

securityDefinitions:   # Authorization, part 1
  basicAuth:
    type: basic

paths:
  /something:
    post:
      summary: POST some JSON
      consumes:
        - application/json  # Request Content-Type
      produces:
        - application/json  # Response Content-Type
      security:
        - basicAuth: []     # Authorization, part 2
      parameters:
        - in: body
          name: body
          required: true
          schema:
            $ref: '#/definitions/Something'
      responses:
        200:
          description: OK

Relevant documentation:

MIME Types

Authentication

Describing Parameters


问:
Matlab unique cell combinations
I have a list as given below:

```<code>A= {[1 2], [2 1], [2 1 3],[3 4],[4 3]}
</code>```

I need to simplify the matrix. For example, [3 4] and [4 3] form the same combination, only one of them is enough. Also, [1 2] and [2 1] is the same combinations, so I should be left with

```<code>newA= {[1 2],[2 1 3],[3 4]}
</code>```

How do I do that?

答:
One approach is to sort the values and use unique:

```<code>A = {[1 2], [2 1], [2 1 3],[3 4],[4 3]};

tmp = cellfun(@sort, A, 'UniformOutput', false);
tmp = cellfun(@num2str, tmp, 'UniformOutput', false);
[~, idx] = unique(tmp);

newA = A(idx);
</code>```

Note 1 that I've had to make a dummy array of the string equivalent of A due to unique's handling of cell arrays. unique can only work on cell arrays of strings/character vectors so we have to do a little manipulation to get the desired output.

Note 2 that cellfun is almost always slower than the explicit loop, but I've used it here for brevity.

Title: Matlab unique cell combinations

Body:
I have a list as given below:

A= {[1 2], [2 1], [2 1 3],[3 4],[4 3]}

I need to simplify the matrix. For example, [3 4] and [4 3] form the same combination, only one of them is enough. Also, [1 2] and [2 1] is the same combinations, so I should be left with

newA= {[1 2],[2 1 3],[3 4]}

How do I do that?

Body:
One approach is to sort the values and use unique:

A = {[1 2], [2 1], [2 1 3],[3 4],[4 3]};

tmp = cellfun(@sort, A, 'UniformOutput', false);
tmp = cellfun(@num2str, tmp, 'UniformOutput', false);
[~, idx] = unique(tmp);

newA = A(idx);

Note 1 that I've had to make a dummy array of the string equivalent of A due to unique's handling of cell arrays. unique can only work on cell arrays of strings/character vectors so we have to do a little manipulation to get the desired output.

Note 2 that cellfun is almost always slower than the explicit loop, but I've used it here for brevity.


问:
Python Spark Dataframes : how to update column based on conditions from different column
I would like to do very simple thing, but cannot figure out how to do it in Python/Spark(1.5)/Dataframe (it's all new for me).

original dataset:

```<code>code| ISO | country
1   | AFG | Afghanistan state
2   | BOL | Bolivia Plurinational State
</code>```

new  dataset:

```<code>code| ISO | country
1   | AFG | Afghanistan
2   | BOL | Bolivia
</code>```

I would like to do something like this (in pseudo Python?):

```<code>iso_to_country_dict = {'AFG': 'Afghanistan', 'BOL': 'Bolivia'}

def mapCountry(iso,country):
    if(iso_to_country_dict[iso] is not empty):
        return iso_to_country_dict[iso]
    return country

dfg = df.select(mapCountry(df['ISO'],df['country']))
</code>```

Just for simplicity the mapCountry could look like this:

```<code>def mapCountry(iso,country):
    if(iso=='AFG'):
        return 'Afghanistan'
    return country
</code>```

but with this is there error: ValueError: Cannot convert column into bool:

答:
I would like to offer a different approach ; UDFs are always an option, but they are somewhat inefficient and cumbersome IMO.
The when and otherwise paradigm can solve this issue.
First, for efficiency - represent the dictionary by a DataFrame:

```<code>df_iso = spark.createDataFrame([('bol', 'Bolivia'),
                                ('hti', 'Cape-Verde'),
                                ('fra', 'France')], ['iso', 'country'])
</code>```

Then lets consider the following data:

```<code>df_data = spark.createDataFrame(
    map(lambda x: (x, ),
    ['fra', 'esp', 'eng', 'usa', 'bol']), ['data'])
</code>```

Then we make the ISO lookup by a join:

```<code>df_data = df_data.join(df_iso, F.col('data') == F.col('iso'),
                       'left_outer')
</code>```

And finally, we add the desired column (I named it result) based on the match:

```<code>df_data = df_data.select(
    F.col('data'),
    F.when(F.col('iso').isNull(), F.col('data'))
    .otherwise(F.col('country')).alias('result'))
</code>```

The result would then be:

```<code>+----+-------+
|data|    res|
+----+-------+
| esp|    esp|
| bol|Bolivia|
| eng|    eng|
| fra| France|
| usa|    usa|
+----+-------+
</code>```

Body:
I would like to do very simple thing, but cannot figure out how to do it in Python/Spark(1.5)/Dataframe (it's all new for me).

original dataset:

code| ISO | country
1   | AFG | Afghanistan state
2   | BOL | Bolivia Plurinational State

new  dataset:

code| ISO | country
1   | AFG | Afghanistan
2   | BOL | Bolivia

I would like to do something like this (in pseudo Python?):

iso_to_country_dict = {'AFG': 'Afghanistan', 'BOL': 'Bolivia'}

def mapCountry(iso,country):
    if(iso_to_country_dict[iso] is not empty):
        return iso_to_country_dict[iso]
    return country

dfg = df.select(mapCountry(df['ISO'],df['country']))

Just for simplicity the mapCountry could look like this:

def mapCountry(iso,country):
    if(iso=='AFG'):
        return 'Afghanistan'
    return country

but with this is there error: ValueError: Cannot convert column into bool:

Body:
I would like to offer a different approach ; UDFs are always an option, but they are somewhat inefficient and cumbersome IMO.
The when and otherwise paradigm can solve this issue.
First, for efficiency - represent the dictionary by a DataFrame:

df_iso = spark.createDataFrame([('bol', 'Bolivia'),
                                ('hti', 'Cape-Verde'),
                                ('fra', 'France')], ['iso', 'country'])

Then lets consider the following data:

df_data = spark.createDataFrame(
    map(lambda x: (x, ),
    ['fra', 'esp', 'eng', 'usa', 'bol']), ['data'])

Then we make the ISO lookup by a join:

df_data = df_data.join(df_iso, F.col('data') == F.col('iso'),
                       'left_outer')

And finally, we add the desired column (I named it result) based on the match:

df_data = df_data.select(
    F.col('data'),
    F.when(F.col('iso').isNull(), F.col('data'))
    .otherwise(F.col('country')).alias('result'))

The result would then be:

+----+-------+
|data|    res|
+----+-------+
| esp|    esp|
| bol|Bolivia|
| eng|    eng|
| fra| France|
| usa|    usa|
+----+-------+


问:
How can I filter on GA requests which contain "X-Purpose:preview" on the header?
Good morning and thanks in advance. My GA is going crazy because we are getting traffic from a source that "preloads" our pages for their users. This means that although not all of their users end up in our site, GA still counts each "prefetch" as a session of 1-2 seconds. I need to filter HTTP requests that contain "X-Purpose:preview" at the header but the current regular expression I am ussing is not working. As of now I put: Exclude Request URI and then this regex:

(X-Purpose:preview)

it is not working. Any help will be appreciated.

答: In case anyone out there is trying to solve this... I posted it on GA forum and seems there is no way to make this work. If anyone can think of a way to make it work I'd be immensely grateful: https://www.en.advertisercommunity.com/t5/Google-Analytics-Filters/How-can-I-filter-on-GA-requests-which-contain-X-Purpose-preview/m-p/1252519#</p>


答:
They do different things. Setting a variable to null does nothing to the object itself. It may mean that the object is now eligible for garbage collection, but it will make no difference if there are other "live" reference to the same object.

What should you do? Well, it entirely depends on your situation. If you have lots of different places with reference to the same object, and they should all see the "clearance", then modify the object. If you just need one variable to refer to a different object or no object at all, just change the value of the variable.

The important thing is to know the difference between the two - be very aware that the value of a variable is never an object... it's either a reference or a value type value.

Title: How to "clear" an object?

Body:
What's the better way to clear an object:

Write a method inside the class that clears all the members of the class: MyObject.Clear();

Inside my code, in the business logic, null the object: MyObject = null;


问:
Android studio 3.0 rendering "Exception raised during rendering" and "onMeasure error"
I got some rendering problem after I updated my Android studio to version 3.0.

I've tried to change the SDK version like this but still didn't work.

Picture here

My JDK version is 1.8 and here is some of my gradle information.

```<code>compileSdkVersion 26

defaultConfig {
    applicationId "com.example.wheathermaster"
    minSdkVersion 19
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    multiDexEnabled true
}
</code>```

I also tried "Clean project" and "Invalidate Cache/ Restart", but none of them works.

And here are my error messages:

Exception raised during rendering

```<code>java.lang.NullPointerException
at android.graphics.BidiRenderer.getScriptFont(BidiRenderer.java:290)
at android.graphics.BidiRenderer.getScriptRuns(BidiRenderer.java:280)
at android.graphics.BidiRenderer.renderText(BidiRenderer.java:133)
at android.graphics.BidiRenderer.renderText(BidiRenderer.java:108)
at android.graphics.Paint_Delegate.measureText(Paint_Delegate.java:1318)
at android.graphics.Paint_Delegate.nGetTextAdvances(Paint_Delegate.java:975)
at android.graphics.Paint_Delegate.nGetRunAdvance(Paint_Delegate.java:1154)
at android.graphics.Paint.nGetRunAdvance(Paint.java)
at android.graphics.Paint.getRunAdvance(Paint.java:2734)
at android.graphics.Paint.getRunAdvance(Paint.java:2766)
at android.text.TextLine.getRunAdvance(TextLine.java:732)
at android.text.TextLine.handleText(TextLine.java:778)
at android.text.TextLine.handleRun(TextLine.java:1018)
at android.text.TextLine.measureRun(TextLine.java:417)
at android.text.TextLine.measure(TextLine.java:307)
at android.text.TextLine.metrics(TextLine.java:281)
at android.text.BoringLayout.isBoring(BoringLayout.java:294)
at android.widget.TextView.makeSingleLayout(TextView.java:7960)
at android.widget.TextView.makeNewLayout(TextView.java:7853)
at android.widget.TextView.assumeLayout(TextView.java:7754)
at android.widget.TextView.onDraw(TextView.java:6807)
at android.view.View.draw(View.java:19192)
at android.view.View.draw(View.java:19062)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:4236)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:63)
at android.view.ViewGroup.drawChild(ViewGroup.java:4236)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4022)
at android.view.View.draw(View.java:19060)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:4236)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:63)
at android.view.ViewGroup.drawChild(ViewGroup.java:4236)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4022)
at android.view.View.draw(View.java:19195)
at android.view.View.draw(View.java:19062)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:4236)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:63)
at android.view.ViewGroup.drawChild(ViewGroup.java:4236)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4022)
at android.view.View.draw(View.java:19060)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:4236)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:63)
at android.view.ViewGroup.drawChild(ViewGroup.java:4236)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4022)
at android.view.View.draw(View.java:19060)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:4236)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:63)
at android.view.ViewGroup.drawChild(ViewGroup.java:4236)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4022)
at android.view.View.draw(View.java:19060)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:4236)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:63)
at android.view.ViewGroup.drawChild(ViewGroup.java:4236)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4022)
at android.view.View.draw(View.java:19195)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.renderAndBuildResult(RenderSessionImpl.java:403)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.renderAndBuildResult(RenderSessionImpl.java:541)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.render(RenderSessionImpl.java:424)
at com.android.layoutlib.bridge.BridgeRenderSession.render(BridgeRenderSession.java:108)
at com.android.ide.common.rendering.api.RenderSession.render(RenderSession.java:154)
at com.android.ide.common.rendering.api.RenderSession.render(RenderSession.java:136)
at com.android.tools.idea.rendering.RenderTask.lambda$renderInner$5(RenderTask.java:757)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>```

onMeasure :

```<code>java.lang.NullPointerException
at android.graphics.BidiRenderer.getScriptFont(BidiRenderer.java:290)
at android.graphics.BidiRenderer.getScriptRuns(BidiRenderer.java:280)
at android.graphics.BidiRenderer.renderText(BidiRenderer.java:133)
at android.graphics.BidiRenderer.renderText(BidiRenderer.java:108)
at android.graphics.Paint_Delegate.measureText(Paint_Delegate.java:1318)
at android.graphics.Paint_Delegate.nGetTextAdvances(Paint_Delegate.java:975)
at android.graphics.Paint_Delegate.nGetRunAdvance(Paint_Delegate.java:1154)
at android.graphics.Paint.nGetRunAdvance(Paint.java)
at android.graphics.Paint.getRunAdvance(Paint.java:2734)
at android.graphics.Paint.getRunAdvance(Paint.java:2766)
at android.text.TextLine.getRunAdvance(TextLine.java:732)
at android.text.TextLine.handleText(TextLine.java:778)
at android.text.TextLine.handleRun(TextLine.java:1018)
at android.text.TextLine.measureRun(TextLine.java:417)
at android.text.TextLine.measure(TextLine.java:307)
at android.text.TextLine.metrics(TextLine.java:281)
at android.text.BoringLayout.isBoring(BoringLayout.java:294)
at android.widget.TextView.onMeasure(TextView.java:8125)
at android.view.View.measure(View.java:22071)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:22071)
at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1148)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:687)
at android.view.View.measure(View.java:22071)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:958)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:22071)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.support.v7.widget.ContentFrameLayout.onMeasure_Original(ContentFrameLayout.java:139)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java)
at android.view.View.measure(View.java:22071)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.support.v7.widget.ActionBarOverlayLayout.onMeasure_Original(ActionBarOverlayLayout.java:400)
at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java)
at android.view.View.measure(View.java:22071)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:22071)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.measureView(RenderSessionImpl.java:590)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:343)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:384)
at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:193)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:544)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$3(RenderTask.java:678)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>```

答: Sorry for the late answer but updating your IDE AndroidS to 3.2 shoud solve your probleme. Cheers ! :)</p>

Body:
I got some rendering problem after I updated my Android studio to version 3.0.

I've tried to change the SDK version like this but still didn't work.

Picture here

My JDK version is 1.8 and here is some of my gradle information.

compileSdkVersion 26

defaultConfig {
    applicationId "com.example.wheathermaster"
    minSdkVersion 19
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    multiDexEnabled true
}

I also tried "Clean project" and "Invalidate Cache/ Restart", but none of them works.

And here are my error messages:

Exception raised during rendering

java.lang.NullPointerException
at android.graphics.BidiRenderer.getScriptFont(BidiRenderer.java:290)
at android.graphics.BidiRenderer.getScriptRuns(BidiRenderer.java:280)
at android.graphics.BidiRenderer.renderText(BidiRenderer.java:133)
at android.graphics.BidiRenderer.renderText(BidiRenderer.java:108)
at android.graphics.Paint_Delegate.measureText(Paint_Delegate.java:1318)
at android.graphics.Paint_Delegate.nGetTextAdvances(Paint_Delegate.java:975)
at android.graphics.Paint_Delegate.nGetRunAdvance(Paint_Delegate.java:1154)
at android.graphics.Paint.nGetRunAdvance(Paint.java)
at android.graphics.Paint.getRunAdvance(Paint.java:2734)
at android.graphics.Paint.getRunAdvance(Paint.java:2766)
at android.text.TextLine.getRunAdvance(TextLine.java:732)
at android.text.TextLine.handleText(TextLine.java:778)
at android.text.TextLine.handleRun(TextLine.java:1018)
at android.text.TextLine.measureRun(TextLine.java:417)
at android.text.TextLine.measure(TextLine.java:307)
at android.text.TextLine.metrics(TextLine.java:281)
at android.text.BoringLayout.isBoring(BoringLayout.java:294)
at android.widget.TextView.makeSingleLayout(TextView.java:7960)
at android.widget.TextView.makeNewLayout(TextView.java:7853)
at android.widget.TextView.assumeLayout(TextView.java:7754)
at android.widget.TextView.onDraw(TextView.java:6807)
at android.view.View.draw(View.java:19192)
at android.view.View.draw(View.java:19062)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:4236)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:63)
at android.view.ViewGroup.drawChild(ViewGroup.java:4236)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4022)
at android.view.View.draw(View.java:19060)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:4236)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:63)
at android.view.ViewGroup.drawChild(ViewGroup.java:4236)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4022)
at android.view.View.draw(View.java:19195)
at android.view.View.draw(View.java:19062)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:4236)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:63)
at android.view.ViewGroup.drawChild(ViewGroup.java:4236)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4022)
at android.view.View.draw(View.java:19060)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:4236)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:63)
at android.view.ViewGroup.drawChild(ViewGroup.java:4236)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4022)
at android.view.View.draw(View.java:19060)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:4236)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:63)
at android.view.ViewGroup.drawChild(ViewGroup.java:4236)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4022)
at android.view.View.draw(View.java:19060)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:4236)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:63)
at android.view.ViewGroup.drawChild(ViewGroup.java:4236)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4022)
at android.view.View.draw(View.java:19195)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.renderAndBuildResult(RenderSessionImpl.java:403)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.renderAndBuildResult(RenderSessionImpl.java:541)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.render(RenderSessionImpl.java:424)
at com.android.layoutlib.bridge.BridgeRenderSession.render(BridgeRenderSession.java:108)
at com.android.ide.common.rendering.api.RenderSession.render(RenderSession.java:154)
at com.android.ide.common.rendering.api.RenderSession.render(RenderSession.java:136)
at com.android.tools.idea.rendering.RenderTask.lambda$renderInner$5(RenderTask.java:757)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

onMeasure :

java.lang.NullPointerException
at android.graphics.BidiRenderer.getScriptFont(BidiRenderer.java:290)
at android.graphics.BidiRenderer.getScriptRuns(BidiRenderer.java:280)
at android.graphics.BidiRenderer.renderText(BidiRenderer.java:133)
at android.graphics.BidiRenderer.renderText(BidiRenderer.java:108)
at android.graphics.Paint_Delegate.measureText(Paint_Delegate.java:1318)
at android.graphics.Paint_Delegate.nGetTextAdvances(Paint_Delegate.java:975)
at android.graphics.Paint_Delegate.nGetRunAdvance(Paint_Delegate.java:1154)
at android.graphics.Paint.nGetRunAdvance(Paint.java)
at android.graphics.Paint.getRunAdvance(Paint.java:2734)
at android.graphics.Paint.getRunAdvance(Paint.java:2766)
at android.text.TextLine.getRunAdvance(TextLine.java:732)
at android.text.TextLine.handleText(TextLine.java:778)
at android.text.TextLine.handleRun(TextLine.java:1018)
at android.text.TextLine.measureRun(TextLine.java:417)
at android.text.TextLine.measure(TextLine.java:307)
at android.text.TextLine.metrics(TextLine.java:281)
at android.text.BoringLayout.isBoring(BoringLayout.java:294)
at android.widget.TextView.onMeasure(TextView.java:8125)
at android.view.View.measure(View.java:22071)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:22071)
at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1148)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:687)
at android.view.View.measure(View.java:22071)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:958)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:22071)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.support.v7.widget.ContentFrameLayout.onMeasure_Original(ContentFrameLayout.java:139)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java)
at android.view.View.measure(View.java:22071)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.support.v7.widget.ActionBarOverlayLayout.onMeasure_Original(ActionBarOverlayLayout.java:400)
at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java)
at android.view.View.measure(View.java:22071)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:22071)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.measureView(RenderSessionImpl.java:590)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:343)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:384)
at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:193)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:544)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$3(RenderTask.java:678)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)


问:
Is there a way to overline text in (GitHub flavoured) Markdown?
I would like to overline some text in a Markdown file. Is this possible?</p>

答:
There is no built-in overline function in GitHub flavored Markdown.

You can use the Combining Overline Unicode Character (U+0305) to simulate an overline, just paste this character after every character you want to overline:

̅

This produces the following result:

1̅

Alternatively, you can use a generator for this.


问:
AWS CodeDeploy deployment tracking
I would like to know if it's possible to track the deployment status of CodeDeploy by using CLI.
Currently, I'm using Bamboo to trigger the CodeDeploy deployment by CLI using: aws deploy create-deployment ... My Bamboo plan will show green the moment the deployment is triggered instead of checking if the actual deployment is succeeded. Is there a way to let Bamboo/command line verify if the actual deployment was successfully deployed?
Many thanks!</p>

答:
Suggest you use the AWS Code Deployment Task to manage these deployments. It will manage the entire process, and will report on actual deployment status.

With the AWS CodeDeploy task for Bamboo you can deploy applications to
  EC2 instances automatically, reliably, and rapidly. Additionally, AWS
  CodeDeploy keeps track of the whole deployment process.

See https://confluence.atlassian.com/bamboo/using-the-aws-codedeploy-task-750396059.html

Title: AWS CodeDeploy deployment tracking


问:
How to update center coordinates of Google map every X seconds in Unity C#?
I am making pokemon go-like game. I want to update my map wherever I go using my GPS. But for now, I want to update the coordinates. Shall I use for loop?

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GoogleMap : MonoBehaviour {
    public RawImage image;
    string url;

    public float lon, lat;

    LocationInfo locationInfo;

    public enum mapType {roadmap, satellite, hybrid, terrain}
    public mapType mapSelected;
    public int scale;

    IEnumerator Map(){
        //url = "https://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318&markers=color:red%7Clabel:C%7C40.718217,-73.998284&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc";
        //url = "https://maps.googleapis.com/maps/api/staticmap?center=14.679046,120.540874&zoom=19&size=640x640&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc&scale=2";
        url = "https://maps.googleapis.com/maps/api/staticmap?&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc&center=14.679155295230377,120.54045265601641&zoom=18&format=png&maptype=roadmap&style=element:geometry%7Ccolor:0x1d2c4d&style=element:labels.text.fill%7Ccolor:0x8ec3b9&style=element:labels.text.stroke%7Ccolor:0x1a3646&style=feature:administrative.country%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:administrative.land_parcel%7Celement:labels.text.fill%7Ccolor:0x64779e&style=feature:administrative.province%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:landscape.man_made%7Celement:geometry.stroke%7Ccolor:0x334e87&style=feature:landscape.natural%7Celement:geometry%7Ccolor:0x023e58&style=feature:poi%7Celement:geometry%7Ccolor:0x283d6a&style=feature:poi%7Celement:labels.text.fill%7Ccolor:0x6f9ba5&style=feature:poi%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:poi.business%7Cvisibility:off&style=feature:poi.park%7Celement:geometry.fill%7Ccolor:0x023e58&style=feature:poi.park%7Celement:labels.text%7Cvisibility:off&style=feature:poi.park%7Celement:labels.text.fill%7Ccolor:0x3C7680&style=feature:road%7Celement:geometry%7Ccolor:0x304a7d&style=feature:road%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:road%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:road.highway%7Celement:geometry%7Ccolor:0x2c6675&style=feature:road.highway%7Celement:geometry.stroke%7Ccolor:0x255763&style=feature:road.highway%7Celement:labels.text.fill%7Ccolor:0xb0d5ce&style=feature:road.highway%7Celement:labels.text.stroke%7Ccolor:0x023e58&style=feature:transit%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:transit%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:transit.line%7Celement:geometry.fill%7Ccolor:0x283d6a&style=feature:transit.station%7Celement:geometry%7Ccolor:0x3a4762&style=feature:water%7Celement:geometry%7Ccolor:0x0e1626&style=feature:water%7Celement:labels.text.fill%7Ccolor:0x4e6d70&size=640x640&scale=2";
        WWW www = new WWW (url);
        yield return www;
        image.texture = www.texture;
        image.SetNativeSize ();
    }

    // Use this for initialization
    void Start () {
        image = gameObject.GetComponent<RawImage> ();
        StartCoroutine (Map());
    }

    // Update is called once per frame
    void Update () {

    }
}
</code>```

答:
Just put the code in the Map() function inside a while loop and use WaitForSeconds to do the waiting.

```<code>//Every 2 seconds
float everyXtime = 2;

IEnumerator Map()
{
    while (true)
    {
        //url = "https://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318&markers=color:red%7Clabel:C%7C40.718217,-73.998284&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc";
        //url = "https://maps.googleapis.com/maps/api/staticmap?center=14.679046,120.540874&zoom=19&size=640x640&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc&scale=2";
        url = "https://maps.googleapis.com/maps/api/staticmap?&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc&center=14.679155295230377,120.54045265601641&zoom=18&format=png&maptype=roadmap&style=element:geometry%7Ccolor:0x1d2c4d&style=element:labels.text.fill%7Ccolor:0x8ec3b9&style=element:labels.text.stroke%7Ccolor:0x1a3646&style=feature:administrative.country%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:administrative.land_parcel%7Celement:labels.text.fill%7Ccolor:0x64779e&style=feature:administrative.province%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:landscape.man_made%7Celement:geometry.stroke%7Ccolor:0x334e87&style=feature:landscape.natural%7Celement:geometry%7Ccolor:0x023e58&style=feature:poi%7Celement:geometry%7Ccolor:0x283d6a&style=feature:poi%7Celement:labels.text.fill%7Ccolor:0x6f9ba5&style=feature:poi%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:poi.business%7Cvisibility:off&style=feature:poi.park%7Celement:geometry.fill%7Ccolor:0x023e58&style=feature:poi.park%7Celement:labels.text%7Cvisibility:off&style=feature:poi.park%7Celement:labels.text.fill%7Ccolor:0x3C7680&style=feature:road%7Celement:geometry%7Ccolor:0x304a7d&style=feature:road%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:road%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:road.highway%7Celement:geometry%7Ccolor:0x2c6675&style=feature:road.highway%7Celement:geometry.stroke%7Ccolor:0x255763&style=feature:road.highway%7Celement:labels.text.fill%7Ccolor:0xb0d5ce&style=feature:road.highway%7Celement:labels.text.stroke%7Ccolor:0x023e58&style=feature:transit%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:transit%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:transit.line%7Celement:geometry.fill%7Ccolor:0x283d6a&style=feature:transit.station%7Celement:geometry%7Ccolor:0x3a4762&style=feature:water%7Celement:geometry%7Ccolor:0x0e1626&style=feature:water%7Celement:labels.text.fill%7Ccolor:0x4e6d70&size=640x640&scale=2";
        WWW www = new WWW(url);
        yield return www;
        image.texture = www.texture;
        image.SetNativeSize();

        //Wait for that X time
        yield return new WaitForSeconds(everyXtime);
    }
}
</code>```

Body:
I am making pokemon go-like game. I want to update my map wherever I go using my GPS. But for now, I want to update the coordinates. Shall I use for loop?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GoogleMap : MonoBehaviour {
    public RawImage image;
    string url;

    public float lon, lat;

    LocationInfo locationInfo;

    public enum mapType {roadmap, satellite, hybrid, terrain}
    public mapType mapSelected;
    public int scale;

    IEnumerator Map(){
        //url = "https://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318&markers=color:red%7Clabel:C%7C40.718217,-73.998284&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc";
        //url = "https://maps.googleapis.com/maps/api/staticmap?center=14.679046,120.540874&zoom=19&size=640x640&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc&scale=2";
        url = "https://maps.googleapis.com/maps/api/staticmap?&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc&center=14.679155295230377,120.54045265601641&zoom=18&format=png&maptype=roadmap&style=element:geometry%7Ccolor:0x1d2c4d&style=element:labels.text.fill%7Ccolor:0x8ec3b9&style=element:labels.text.stroke%7Ccolor:0x1a3646&style=feature:administrative.country%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:administrative.land_parcel%7Celement:labels.text.fill%7Ccolor:0x64779e&style=feature:administrative.province%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:landscape.man_made%7Celement:geometry.stroke%7Ccolor:0x334e87&style=feature:landscape.natural%7Celement:geometry%7Ccolor:0x023e58&style=feature:poi%7Celement:geometry%7Ccolor:0x283d6a&style=feature:poi%7Celement:labels.text.fill%7Ccolor:0x6f9ba5&style=feature:poi%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:poi.business%7Cvisibility:off&style=feature:poi.park%7Celement:geometry.fill%7Ccolor:0x023e58&style=feature:poi.park%7Celement:labels.text%7Cvisibility:off&style=feature:poi.park%7Celement:labels.text.fill%7Ccolor:0x3C7680&style=feature:road%7Celement:geometry%7Ccolor:0x304a7d&style=feature:road%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:road%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:road.highway%7Celement:geometry%7Ccolor:0x2c6675&style=feature:road.highway%7Celement:geometry.stroke%7Ccolor:0x255763&style=feature:road.highway%7Celement:labels.text.fill%7Ccolor:0xb0d5ce&style=feature:road.highway%7Celement:labels.text.stroke%7Ccolor:0x023e58&style=feature:transit%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:transit%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:transit.line%7Celement:geometry.fill%7Ccolor:0x283d6a&style=feature:transit.station%7Celement:geometry%7Ccolor:0x3a4762&style=feature:water%7Celement:geometry%7Ccolor:0x0e1626&style=feature:water%7Celement:labels.text.fill%7Ccolor:0x4e6d70&size=640x640&scale=2";
        WWW www = new WWW (url);
        yield return www;
        image.texture = www.texture;
        image.SetNativeSize ();
    }

    // Use this for initialization
    void Start () {
        image = gameObject.GetComponent<RawImage> ();
        StartCoroutine (Map());
    }

    // Update is called once per frame
    void Update () {

    }
}

Body:
Just put the code in the Map() function inside a while loop and use WaitForSeconds to do the waiting.

//Every 2 seconds
float everyXtime = 2;

IEnumerator Map()
{
    while (true)
    {
        //url = "https://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318&markers=color:red%7Clabel:C%7C40.718217,-73.998284&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc";
        //url = "https://maps.googleapis.com/maps/api/staticmap?center=14.679046,120.540874&zoom=19&size=640x640&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc&scale=2";
        url = "https://maps.googleapis.com/maps/api/staticmap?&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc&center=14.679155295230377,120.54045265601641&zoom=18&format=png&maptype=roadmap&style=element:geometry%7Ccolor:0x1d2c4d&style=element:labels.text.fill%7Ccolor:0x8ec3b9&style=element:labels.text.stroke%7Ccolor:0x1a3646&style=feature:administrative.country%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:administrative.land_parcel%7Celement:labels.text.fill%7Ccolor:0x64779e&style=feature:administrative.province%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:landscape.man_made%7Celement:geometry.stroke%7Ccolor:0x334e87&style=feature:landscape.natural%7Celement:geometry%7Ccolor:0x023e58&style=feature:poi%7Celement:geometry%7Ccolor:0x283d6a&style=feature:poi%7Celement:labels.text.fill%7Ccolor:0x6f9ba5&style=feature:poi%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:poi.business%7Cvisibility:off&style=feature:poi.park%7Celement:geometry.fill%7Ccolor:0x023e58&style=feature:poi.park%7Celement:labels.text%7Cvisibility:off&style=feature:poi.park%7Celement:labels.text.fill%7Ccolor:0x3C7680&style=feature:road%7Celement:geometry%7Ccolor:0x304a7d&style=feature:road%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:road%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:road.highway%7Celement:geometry%7Ccolor:0x2c6675&style=feature:road.highway%7Celement:geometry.stroke%7Ccolor:0x255763&style=feature:road.highway%7Celement:labels.text.fill%7Ccolor:0xb0d5ce&style=feature:road.highway%7Celement:labels.text.stroke%7Ccolor:0x023e58&style=feature:transit%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:transit%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:transit.line%7Celement:geometry.fill%7Ccolor:0x283d6a&style=feature:transit.station%7Celement:geometry%7Ccolor:0x3a4762&style=feature:water%7Celement:geometry%7Ccolor:0x0e1626&style=feature:water%7Celement:labels.text.fill%7Ccolor:0x4e6d70&size=640x640&scale=2";
        WWW www = new WWW(url);
        yield return www;
        image.texture = www.texture;
        image.SetNativeSize();

        //Wait for that X time
        yield return new WaitForSeconds(everyXtime);
    }
}


问:
Converting a string to a date in a cell
I have 100.000 rows of data in Excel. Some of the fields are dates, but the fields in Excel are as text. I need these fields in number format including both dates AND time (e.g. 21.10.2011 13:10:50). Formatting the cells doesn't work because that doesn't change the datatype. I can pick out the date and time with formulas but not get them in the same cell.

So what I am looking for is the formula to calculate the number representation of a date (the one you see if you format a date as a number).

答: The best solution is using DATE() function and extracting yy, mm, and dd from the string with RIGHT(), MID() and LEFT() functions, the final will be some DATE(LEFT(),MID(),RIGHT()), details here </p>

Title: Converting a string to a date in a cell


问:
I want make Dynamic window content(img&font&frame) size in WPF at c#
enter image description here

enter image description here

I want to fill the monitor's full screen with 1024*768 ratio of window size& content size.

When use at wide monitor's Fill Blank Right Left Area fill black color whit use x:Name="wide_Out"
how can I make dynamic Full screan window & contents (keep main win size rate), regardless of monitor resolution and type.

mainwindow.xaml

```<code><Window x:Class="C.MainWindow"
        xmlns:local="clr-namespace:M_C"
        mc:Ignorable="d"
        Title="MainWindow" Height="768" Width="1024" WindowStyle="None">
     <Grid x:Name="wide_Out" Margin="0,0,0,0">
         <Grid Height="768" Width="1024">
             <DockPanel x:Name="L_black" HorizontalAlignment="Left" Height="737"
             LastChildFill="False" VerticalAlignment="Top" Width="62"
             Background="#FF242424">
                 <Button Margin="15,8,0,0" Height="40" VerticalAlignment="Top"
                  Width="30"/>
             </DockPanel>
             <DockPanel x:Name="T_blue" HorizontalAlignment="Left" Height="100"
              LastChildFill="False" Margin="62,0,0,0" VerticalAlignment="Top"
              Width="954" Background="#FF248BC7">
                 <TextBlock Margin="200,10,200,0" Height="80"
                 TextWrapping="Wrap"
                Text="TextBlock" VerticalAlignment="Top" Width="554"/>
            </DockPanel>
            <DockPanel x:Name="L_blue" HorizontalAlignment="Left" Height="637"
            LastChildFill="False" Margin="62,100,0,0" VerticalAlignment="Top"
            Width="82" Background="#FF248BC7"/>
            <DockPanel x:Name="R_blue" HorizontalAlignment="Left" Height="637"
            LastChildFill="False" Margin="934,100,0,0" Background="#FF248BC7"
            Width="82"/>
            <DockPanel x:Name="B_blue" HorizontalAlignment="Left" Height="100"
            LastChildFill="False" Margin="144,637,0,0" VerticalAlignment="Top"
            Width="790" Background="#FF248BC7">
                <Image Margin="250,15,250,15" Height="70"
                VerticalAlignment="Top" Width="290" />
            </DockPanel>
            <DockPanel x:Name="main_content_panel" HorizontalAlignment="Left"
            Height="537" LastChildFill="False" Margin="144,100,0,0"
            VerticalAlignment="Top" Width="790">
                <Grid Margin="0,0,0,0">
                </Grid>
            </DockPanel>
        </Grid>
      </Grid>
     </Window>
</code>```

答:
If I understand you correctly, what you need to do is wrap the content of your  Window element with a Viewbox. Here is sample code, from every element I have I have only written the parts that are important, other may be set as needed:

```<code><Window
    Height="{x:Static SystemParameters.PrimaryScreenHeight}"
    Width="{x:Static SystemParameters.PrimaryScreenWidth}" <!--To set your window size to the size of monitor-->
    WindowStyle="None" <!--To not display any controls-->
    >
    <Viewbox> <!--You can try using different 'Stretch' attribute values-->
        <Grid Width="768" Height="1024" x:Name="wide_Out"> <!--Or whatever dimensions you want your 'base' window to work with-->
            <DockPanel x:Name="L_black" HorizontalAlignment="Left" Height="737" LastChildFill="False" VerticalAlignment="Top" Width="62" Background="#FF242424">
                 <Button Margin="15,8,0,0" Height="40" VerticalAlignment="Top" Width="30"/>
             </DockPanel>
             <DockPanel x:Name="T_blue" HorizontalAlignment="Left" Height="100" LastChildFill="False" Margin="62,0,0,0" VerticalAlignment="Top" Width="954" Background="#FF248BC7">
                 <TextBlock Margin="200,10,200,0" Height="80" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="554"/>
            </DockPanel>
            <DockPanel x:Name="L_blue" HorizontalAlignment="Left" Height="637" LastChildFill="False" Margin="62,100,0,0" VerticalAlignment="Top" Width="82" Background="#FF248BC7"/>
            <DockPanel x:Name="R_blue" HorizontalAlignment="Left" Height="637" LastChildFill="False" Margin="934,100,0,0" Background="#FF248BC7" Width="82"/>
            <DockPanel x:Name="B_blue" HorizontalAlignment="Left" Height="100" LastChildFill="False" Margin="144,637,0,0" VerticalAlignment="Top" Width="790" Background="#FF248BC7">
                <Image Margin="250,15,250,15" Height="70" VerticalAlignment="Top" Width="290" />
            </DockPanel>
            <DockPanel x:Name="main_content_panel" HorizontalAlignment="Left" Height="537" LastChildFill="False" Margin="144,100,0,0" VerticalAlignment="Top" Width="790">
                <Grid Margin="0,0,0,0">
                </Grid>
            </DockPanel>
        </Grid>
    </Viewbox>
</Window>
</code>```

The important parts are the window width and height, the viewbox element and then the actual width and height of the wide_Out Grid, with which you will work when setting inner dimensions and margins.

If you want to, you can use BackgroundColorattribute of the window to set background color for the area that is not covered by your content when screen's aspect ratio is other than 4:3 (or whatever you set in `wide_Out Grid).

Body:
enter image description here

enter image description here

I want to fill the monitor's full screen with 1024*768 ratio of window size& content size.

When use at wide monitor's Fill Blank Right Left Area fill black color whit use x:Name="wide_Out"
how can I make dynamic Full screan window & contents (keep main win size rate), regardless of monitor resolution and type.

mainwindow.xaml

<Window x:Class="C.MainWindow"
        xmlns:local="clr-namespace:M_C"
        mc:Ignorable="d"
        Title="MainWindow" Height="768" Width="1024" WindowStyle="None">
     <Grid x:Name="wide_Out" Margin="0,0,0,0">
         <Grid Height="768" Width="1024">
             <DockPanel x:Name="L_black" HorizontalAlignment="Left" Height="737"
             LastChildFill="False" VerticalAlignment="Top" Width="62"
             Background="#FF242424">
                 <Button Margin="15,8,0,0" Height="40" VerticalAlignment="Top"
                  Width="30"/>
             </DockPanel>
             <DockPanel x:Name="T_blue" HorizontalAlignment="Left" Height="100"
              LastChildFill="False" Margin="62,0,0,0" VerticalAlignment="Top"
              Width="954" Background="#FF248BC7">
                 <TextBlock Margin="200,10,200,0" Height="80"
                 TextWrapping="Wrap"
                Text="TextBlock" VerticalAlignment="Top" Width="554"/>
            </DockPanel>
            <DockPanel x:Name="L_blue" HorizontalAlignment="Left" Height="637"
            LastChildFill="False" Margin="62,100,0,0" VerticalAlignment="Top"
            Width="82" Background="#FF248BC7"/>
            <DockPanel x:Name="R_blue" HorizontalAlignment="Left" Height="637"
            LastChildFill="False" Margin="934,100,0,0" Background="#FF248BC7"
            Width="82"/>
            <DockPanel x:Name="B_blue" HorizontalAlignment="Left" Height="100"
            LastChildFill="False" Margin="144,637,0,0" VerticalAlignment="Top"
            Width="790" Background="#FF248BC7">
                <Image Margin="250,15,250,15" Height="70"
                VerticalAlignment="Top" Width="290" />
            </DockPanel>
            <DockPanel x:Name="main_content_panel" HorizontalAlignment="Left"
            Height="537" LastChildFill="False" Margin="144,100,0,0"
            VerticalAlignment="Top" Width="790">
                <Grid Margin="0,0,0,0">
                </Grid>
            </DockPanel>
        </Grid>
      </Grid>
     </Window>

Body:
If I understand you correctly, what you need to do is wrap the content of your  Window element with a Viewbox. Here is sample code, from every element I have I have only written the parts that are important, other may be set as needed:

<Window
    Height="{x:Static SystemParameters.PrimaryScreenHeight}"
    Width="{x:Static SystemParameters.PrimaryScreenWidth}" <!--To set your window size to the size of monitor-->
    WindowStyle="None" <!--To not display any controls-->
    >
    <Viewbox> <!--You can try using different 'Stretch' attribute values-->
        <Grid Width="768" Height="1024" x:Name="wide_Out"> <!--Or whatever dimensions you want your 'base' window to work with-->
            <DockPanel x:Name="L_black" HorizontalAlignment="Left" Height="737" LastChildFill="False" VerticalAlignment="Top" Width="62" Background="#FF242424">
                 <Button Margin="15,8,0,0" Height="40" VerticalAlignment="Top" Width="30"/>
             </DockPanel>
             <DockPanel x:Name="T_blue" HorizontalAlignment="Left" Height="100" LastChildFill="False" Margin="62,0,0,0" VerticalAlignment="Top" Width="954" Background="#FF248BC7">
                 <TextBlock Margin="200,10,200,0" Height="80" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="554"/>
            </DockPanel>
            <DockPanel x:Name="L_blue" HorizontalAlignment="Left" Height="637" LastChildFill="False" Margin="62,100,0,0" VerticalAlignment="Top" Width="82" Background="#FF248BC7"/>
            <DockPanel x:Name="R_blue" HorizontalAlignment="Left" Height="637" LastChildFill="False" Margin="934,100,0,0" Background="#FF248BC7" Width="82"/>
            <DockPanel x:Name="B_blue" HorizontalAlignment="Left" Height="100" LastChildFill="False" Margin="144,637,0,0" VerticalAlignment="Top" Width="790" Background="#FF248BC7">
                <Image Margin="250,15,250,15" Height="70" VerticalAlignment="Top" Width="290" />
            </DockPanel>
            <DockPanel x:Name="main_content_panel" HorizontalAlignment="Left" Height="537" LastChildFill="False" Margin="144,100,0,0" VerticalAlignment="Top" Width="790">
                <Grid Margin="0,0,0,0">
                </Grid>
            </DockPanel>
        </Grid>
    </Viewbox>
</Window>

The important parts are the window width and height, the viewbox element and then the actual width and height of the wide_Out Grid, with which you will work when setting inner dimensions and margins.

If you want to, you can use BackgroundColorattribute of the window to set background color for the area that is not covered by your content when screen's aspect ratio is other than 4:3 (or whatever you set in `wide_Out Grid).


问:
Multiple triggers for a jquery-click-event
Sorry for that simple question, but how do I add multiple triggers to a jquery-click-event?

I tried that one here

```<code>$("#trigger1","#trigger2").click(function() {
    //something
});
</code>```

But that doesn't work. What is the correct syntax there?

答:
Or something like

```<code>$(document).on("click", "#trigger1, #trigger2, #trigger3", function () {
    //do stuff
});
</code>```

This will let you add as many listeners as you want on multiple DOM elements

Body:
Sorry for that simple question, but how do I add multiple triggers to a jquery-click-event?

I tried that one here

$("#trigger1","#trigger2").click(function() {
    //something
});

But that doesn't work. What is the correct syntax there?

Body:
Or something like

$(document).on("click", "#trigger1, #trigger2, #trigger3", function () {
    //do stuff
});

This will let you add as many listeners as you want on multiple DOM elements


问:
Parsing XML as PHP with web.config
I have an XML document where I need to place some information about IP. The problem is that making XML parse as PHP in Apache can be done with .htaccess, but when I moved to Azure, it became harder.
What I tried:

web.config

```<code><?xml version="1.0"?>

<configuration>
    <system.webServer>
        <staticContent>
            <mimeMap fileExtension=".xml" mimeType="text/php" />
     </staticContent>
    </system.webServer>
</configuration>
</code>```

applicationHost.config

```<code><system.webServer>
      <staticContent>
           <mimeMap fileExtension=".xml" mimeType="text/php" />
      </staticContent>
</system.webServer>
</code>```

.htaccess: AddType application/x-httpd-php .php .xml

But none of this works. I get error for not correct XML. Need help. The XML File:

```<code><config>
     <settings ip="<?php /*getting external IP...*/ ?>" port="1010"/>
</config>
</code>```

UPDATE
I took a look at the headers and it says that Content-Type is application/xml.

答:
The way I handle situations like this, when I either do not have the time to dig into the server configuration, or am not able to modify the server configuration is to create a directory with the name of the file I want to parse as PHP, and an index.php within that file that handles whatever needs to be done.  For example:

myxml.xml/index.php (which would be exactly like the index.php in this answer)
myxml.xml/myxml.xml (which can include php code)

In this configuration, client requests for myxml.xml get redirected to myxml.xml/index.php, which then serves myxml.xml/myxml.xml

Title: Parsing XML as PHP with web.config

Body:
I have an XML document where I need to place some information about IP. The problem is that making XML parse as PHP in Apache can be done with .htaccess, but when I moved to Azure, it became harder.
What I tried:

web.config

<?xml version="1.0"?>

<configuration>
    <system.webServer>
        <staticContent>
            <mimeMap fileExtension=".xml" mimeType="text/php" />
     </staticContent>
    </system.webServer>
</configuration>

applicationHost.config

<system.webServer>
      <staticContent>
           <mimeMap fileExtension=".xml" mimeType="text/php" />
      </staticContent>
</system.webServer>

.htaccess: AddType application/x-httpd-php .php .xml

But none of this works. I get error for not correct XML. Need help. The XML File:

<config>
     <settings ip="<?php /*getting external IP...*/ ?>" port="1010"/>
</config>

UPDATE
I took a look at the headers and it says that Content-Type is application/xml.


问:
How to create an attribute conditionally in AngularJS
I am trying to create aria-current attribute in an anchor only if the anchors href is equal to the current windows path. Basically, I want aria-current="page" IF the anchor in question has an href equal to the window in views path. And I do not want to create an aria-current attribute if the anchor in question does not have an href equal to the window in view path.

Is there a way to write an conditional statement inline that will create or not create an attribute in AngularJS (Angular1)?

答:
Solution: use ng-attr to conditionally create an attribute inline.

For example <div ng-attr-alt="{{<conditional statement> ? '<value to set attr to if true>' : undefined }}"

If the conditional statement does not evaluate to true then the attribute will not be created, the undefined value sets this.


问:
Spark Job fails connecting to oracle in first attempt
We are running spark job which connect to oracle and fetch some data. Always attempt 0 or 1 of JDBCRDD  task fails with below error. In subsequent attempt task get completed. As suggested in few portal we even tried with -Djava.security.egd=file:///dev/urandom java option but it didn't solved the problem. Can someone please help us in fixing this issue.</p>

```<code>ava.sql.SQLRecoverableException: IO Error: Connection reset by peer, Authentication lapse 59937 ms.
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:794)
    at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:688)
</code>```

答: Issue was with java.security.egd only. Setting it through command line i.e -Djava.security.egd=file:///dev/urandom was not working so I set it through system.setproperty with in job. After that job is no more giving SQLRecoverableException</p>

Body:
We are running spark job which connect to oracle and fetch some data. Always attempt 0 or 1 of JDBCRDD  task fails with below error. In subsequent attempt task get completed. As suggested in few portal we even tried with -Djava.security.egd=file:///dev/urandom java option but it didn't solved the problem. Can someone please help us in fixing this issue.

ava.sql.SQLRecoverableException: IO Error: Connection reset by peer, Authentication lapse 59937 ms.
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:794)
    at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:688)


问:
Fit flex parent cross-axis to items
Where the parent has display: flex; flex-direction: column, is it possible to make the parent's width expand to fit a flex item wider than the parent?

It's worth noting that the grandparent does not have display: flex nor a fixed width. It has a min-width: 100% though.

答:
Using inline-flex on the parent instead of flex and inline-block on the grandparent should do the trick.

Example B shows the modifications. If the img is wider than the viewport the parent and the grandparent will accommodate it (shrink your window down so img is wider than the viewport then scroll right).

html,body {
  width: auto;
}

.grandparent {
  width: 300px;
  background-color: blue;
  padding: 10px;
}

.parent {
  display: inline-flex;
  flex-direction: column;
  background-color: red;
  padding: 10px;
}

.exampleB .grandparent {
  min-width: 100%;
  width: auto;
  display: inline-block;
}

.exampleB .parent {
  width: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="exampleA">
  <div class="grandparent">
    <div class="parent">
      <div class="child">
        <img src="//placehold.it/500x100"/>
      </div>
    </div>
  </div>
</section>

<br/>

<section class="exampleB">
  <div class="grandparent">
    <div class="parent">
      <div class="child">
        <img src="//placehold.it/500x100"/>
      </div>
    </div>
  </div>
</section></code>```

Title: Fit flex parent cross-axis to items

Body:
Using inline-flex on the parent instead of flex and inline-block on the grandparent should do the trick.

Example B shows the modifications. If the img is wider than the viewport the parent and the grandparent will accommodate it (shrink your window down so img is wider than the viewport then scroll right).

html,body {
  width: auto;
}

.grandparent {
  width: 300px;
  background-color: blue;
  padding: 10px;
}

.parent {
  display: inline-flex;
  flex-direction: column;
  background-color: red;
  padding: 10px;
}

.exampleB .grandparent {
  min-width: 100%;
  width: auto;
  display: inline-block;
}

.exampleB .parent {
  width: auto;
}

<section class="exampleA">
  <div class="grandparent">
    <div class="parent">
      <div class="child">
        <img src="//placehold.it/500x100"/>
      </div>
    </div>
  </div>
</section>

<br/>

<section class="exampleB">
  <div class="grandparent">
    <div class="parent">
      <div class="child">
        <img src="//placehold.it/500x100"/>
      </div>
    </div>
  </div>
</section>