问:
Javascript - Array from JSON to object
I have the following react class PeopleSelector within I want to get an array of peoples from my people.json.

```<code>// @flow

import React from 'react'

type Props = {
  currentPeople: string,
  setPeopleFn: (string) => void
}

class PeopleSelector extends React.Component {
  render() {
    let peoples = require('../data/people.json');

    return <select value={this.props.currentPeople} onChange={e => this.props.setPeopleFn(e.target.value)}>
      <style jsx>{`
        select {
          font-size: 20px;
          line-height: 20px;
          margin-bottom: 20px;
          min-width: 300px;
        }
      `}</style>
      {peoples.map(name => (
        <option key={name}>
          {name}
        </option>
      ))}
    </select>
  }
}

export default PeopleSelector
</code>```

Sadly there occurs an error saying people.map is not a function. But why?

My JSON looks like

```<code>{
    "peoples": [
        {
            "focusedTrackId": "MOBILE",
            "milestoneByTrack": {
                "COMMUNICATION": 3,
                "CRAFT": 2,
                "DESKTOP": 0,
                "MENTORSHIP": 2,
                "MOBILE": 3,
                "PROJECT_MANAGEMENT": 3,
                "SERVER": 0
            },
            "name": "Bocksteger, Daniel",
            "title": "Entwickler I"
        }
    ]
}
</code>```

Is it not possible to render the JSON into an object of peoples?

Using peoples.peoples.map results in the following react-error:

```<code>Objects are not valid as a React child (found: object with keys
{focusedTrackId, milestoneByTrack, name, title}). If you meant to
render a collection of children, use an array instead.
</code>```

答:
Your peoples object has another peoples property in it.

So instead of peoples.map(...), use peoples.peoples.map(...)

Also, your are rendering each name wrongly inside the map loop:

```<code>{peoples.peoples.map(people => (
  <option key={people.name}>
    {people.name}
  </option>
))}
</code>```

option key={people.name}

I'd use some sort of id or unique identifier instead.

Title: Javascript - Array from JSON to object

Body:
I have the following react class PeopleSelector within I want to get an array of peoples from my people.json.

// @flow

import React from 'react'

type Props = {
  currentPeople: string,
  setPeopleFn: (string) => void
}

class PeopleSelector extends React.Component {
  render() {
    let peoples = require('../data/people.json');

    return <select value={this.props.currentPeople} onChange={e => this.props.setPeopleFn(e.target.value)}>

      {peoples.map(name => (
        <option key={name}>
          {name}
        </option>
      ))}
    </select>
  }
}

export default PeopleSelector

Sadly there occurs an error saying people.map is not a function. But why?

My JSON looks like

{
    "peoples": [
        {
            "focusedTrackId": "MOBILE",
            "milestoneByTrack": {
                "COMMUNICATION": 3,
                "CRAFT": 2,
                "DESKTOP": 0,
                "MENTORSHIP": 2,
                "MOBILE": 3,
                "PROJECT_MANAGEMENT": 3,
                "SERVER": 0
            },
            "name": "Bocksteger, Daniel",
            "title": "Entwickler I"
        }
    ]
}

Is it not possible to render the JSON into an object of peoples?

Using peoples.peoples.map results in the following react-error:

Objects are not valid as a React child (found: object with keys
{focusedTrackId, milestoneByTrack, name, title}). If you meant to
render a collection of children, use an array instead.

Body:
Your peoples object has another peoples property in it.

So instead of peoples.map(...), use peoples.peoples.map(...)

Also, your are rendering each name wrongly inside the map loop:

{peoples.peoples.map(people => (
  <option key={people.name}>
    {people.name}
  </option>
))}

option key={people.name}

I'd use some sort of id or unique identifier instead.


来源: stackexchange

问:
Regarding Comparing JSON in PHP
There was a question raised by Log1x about Comparing JSON after foreach loop for a Discord Channel Viewer

This is the link: Comparing JSON after foreach loop In his viewer he wanted to output something like:

```<code><ul>
  <li>Channel 1
    <ul>
      <li>User 1</li>
      <li>User 2</li>
    </ul>
  </li>
  <li>Channel 2</li>
  <li>Channel 3
    <ul>
      <li>User 3</li>
    </ul>
  </li>
</ul>
</code>```

There was an excellent answer on how to do this, from Mojtaba which was:

```<code>$discord = json_decode(file_get_contents('https://discordapp.com/api/servers/'.$id.'/widget.json'));
  if ($discord->channels) {
    usort($discord->channels, function($a, $b) {
      return $a->position > $b->position ? 1 : -1;
    });

    echo '<ul>';

    foreach ($discord->members as $member) {
        if (!empty($member->channel_id)) {
            $channel_members[$member->channel_id][] = $member->username;
        }
    }

    foreach ($discord->channels as $channel) {
      echo "<li>{$channel->name}";
      if (!empty($channel_members[$channel->id])) {
            echo '<ul>';
            foreach ($channel_members[$channel->id] as $username) {
              echo "<li>$username</li>";
            }
            echo '</ul>';
      }
      echo "</li>";
    }

    echo '</ul>';
  }
</code>```

I have already completed my viewer but you will be able to see from this screen-shot link that my available space is limited and taken up by too many empty channels. So I am interested to know if there is a way to hide channels that are empty i.e.

```<code><ul>
  <li>Channel 1
    <ul>
      <li>User 1</li>
      <li>User 2</li>
    </ul>
  </li>
  <li>Channel 3
    <ul>
      <li>User 3</li>
    </ul>
  </li>
</ul>
</code>```

As I have said, my interest is also for a Discord Channel Viewer , so the above information from both Mojtaba and the first link are directly relevant to my code too.

Thanks in advance.

答:
I think you should be able to just move your
 tag inside the if.

```<code>foreach ($discord->channels as $channel) {

    // outside the if, the channel shows even if it's empty

    if (!empty($channel_members[$channel->id])) {

        // inside the if, you'll only see the channel if it's not empty

        echo "<li>{$channel->name}<ul>";
        foreach ($channel_members[$channel->id] as $username) {
            echo "<li>$username</li>";
        }
        echo '</ul></li>';
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Regarding Comparing JSON in PHP

Body:
There was a question raised by Log1x about Comparing JSON after foreach loop for a Discord Channel Viewer

This is the link: Comparing JSON after foreach loop In his viewer he wanted to output something like:

Channel 1

User 1

User 2

Channel 2

Channel 3

User 3

There was an excellent answer on how to do this, from Mojtaba which was:

$discord = json_decode(file_get_contents('https://discordapp.com/api/servers/'.$id.'/widget.json'));
  if ($discord->channels) {
    usort($discord->channels, function($a, $b) {
      return $a->position > $b->position ? 1 : -1;
    });

    echo '
';

    foreach ($discord->members as $member) {
        if (!empty($member->channel_id)) {
            $channel_members[$member->channel_id][] = $member->username;
        }
    }

    foreach ($discord->channels as $channel) {
      echo "
{$channel->name}";
      if (!empty($channel_members[$channel->id])) {
            echo '
';
            foreach ($channel_members[$channel->id] as $username) {
              echo "
$username
";
            }
            echo '
';
      }
      echo "
";
    }

    echo '
';
  }

I have already completed my viewer but you will be able to see from this screen-shot link that my available space is limited and taken up by too many empty channels. So I am interested to know if there is a way to hide channels that are empty i.e.

Channel 1

User 1

User 2

Channel 3

User 3

As I have said, my interest is also for a Discord Channel Viewer , so the above information from both Mojtaba and the first link are directly relevant to my code too.

Thanks in advance.

Body:
I think you should be able to just move your <li> tag inside the if.

foreach ($discord->channels as $channel) {

    // outside the if, the channel shows even if it's empty

    if (!empty($channel_members[$channel->id])) {

        // inside the if, you'll only see the channel if it's not empty

        echo "<li>{$channel->name}<ul>";
        foreach ($channel_members[$channel->id] as $username) {
            echo "<li>$username</li>";
        }
        echo '</ul></li>';
    }
}


问:
Thymeleaf - Iterating over a model attribute inside Javascript code
I'm trying to write some Javascript code where I need to use a model attribute. Here is how I define the script tag:

```<code><script type="text/javascript" th:inline="javascript">
    /*<![CDATA[*/

    //need some loops

    /*]]>*/
</script>
</code>```

What I need to do is, using each iterations over model attributes inside the script. So far I couldn't manage to do this with th:each. Any help is appreciated.

答:
Thymeleaf 3 -> see yglodt answer

if you're stuck with Thymeleaf 2 and your model attribute is complex (like the case of Maxime Laval), I ended up looping over a script :

```<code><script th:inline="javascript">
  var dataLayer = [];
</script>
<script th:each="item:${items}" th:inline="javascript">
  dataLayer.push({'attr1':item.attr1, 'attr2':item.attr2, 'attr3':item.attr3});
</script>
<script th:inline="javascript">
  console.log(dataLayer); // do whatever you want with dataLayer...
</script>
</code>```

Not very nice but I couldn't find better for my Google analytics.

Body:
I'm trying to write some Javascript code where I need to use a model attribute. Here is how I define the script tag:

What I need to do is, using each iterations over model attributes inside the script. So far I couldn't manage to do this with th:each. Any help is appreciated.

Body:
Thymeleaf 3 -> see yglodt answer

if you're stuck with Thymeleaf 2 and your model attribute is complex (like the case of Maxime Laval), I ended up looping over a script :

<script th:inline="javascript">
  var dataLayer = [];
</script>
<script th:each="item:${items}" th:inline="javascript">
  dataLayer.push({'attr1':item.attr1, 'attr2':item.attr2, 'attr3':item.attr3});
</script>
<script th:inline="javascript">
  console.log(dataLayer); // do whatever you want with dataLayer...
</script>

Not very nice but I couldn't find better for my Google analytics.


问:
How to have an inset box-shadow start from the center rather than the border?
I currently have a box shadow stemming from the border of my  and I'm looking for a way to have the effect inversed, where the shadow starts from the center and fills out the rest of the background.
Pen

CODE:

var medalImg = document.getElementById("benefitsImgMed");
document.getElementById("benefitsImgMed").onclick = function() {
  imgClickFunction1()
};

function imgClickFunction1() {
  medalImg.style.boxShadow = "0px 0px 0px 100px white inset";
  setTimeout(doSomething, 1.6 /*Seconds*/ * 1000);

  function doSomething() {
    /*medalImg.style.borderStyle = "solid";*/
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
}

#benefitsImgMed,
#benefitsImgLig,
#benefitsImgArr,
#benefitsImgNig {
  transition: 2s;
  cursor: pointer;
  z-index: 1;
  position: absolute;
  padding: 10px;
  border-color: white;
  border-width: 5px;
  border-radius: 50%;
  border-style: dashed;
}

#benefitsImgMed:hover {
  box-shadow: inset 0 0 0 50px white;
}

#benefitsImgMed {
  margin-left: 8%;
  margin-top: 6%;
  width: 13%;
  height: 13%;
}</code>```

```

答:
Try this solution:

Note: I've dumbed it down substantially.

body{background-color:black;}

#benefitImgMed {
   transition: 2s;
    width: 200px;
    height: 200px;
   cursor:pointer;
   z-index:1;
   position: absolute;
    border-color: white;
    border-width: 5px;
    border-radius: 50%;
    border-style: dashed;
    overflow: hidden;
}

#benefitImgMed:after{
  content: "";
  position: absolute;
  height: 0%;
  width: 0%;
  background: white;
  opacity: 0;
  top: 50%;
  left: 50%;
  border-radius: 100%;
  transition: all 1s;
}

#benefitImgMed:hover::after{
  background: white;
  height: 100%;
  width: 100%;
  opacity: 1;
  top: 0px;
  left: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="benefitImgMed">

</div></code>```

Body:
I currently have a box shadow stemming from the border of my  and I'm looking for a way to have the effect inversed, where the shadow starts from the center and fills out the rest of the background.
Pen

CODE:

var medalImg = document.getElementById("benefitsImgMed");
document.getElementById("benefitsImgMed").onclick = function() {
  imgClickFunction1()
};

function imgClickFunction1() {
  medalImg.style.boxShadow = "0px 0px 0px 100px white inset";
  setTimeout(doSomething, 1.6 /*Seconds*/ * 1000);

  function doSomething() {
    /*medalImg.style.borderStyle = "solid";*/
  }
}

body {
  background-color: black;
}

#benefitsImgMed,
#benefitsImgLig,
#benefitsImgArr,
#benefitsImgNig {
  transition: 2s;
  cursor: pointer;
  z-index: 1;
  position: absolute;
  padding: 10px;
  border-color: white;
  border-width: 5px;
  border-radius: 50%;
  border-style: dashed;
}

#benefitsImgMed:hover {
  box-shadow: inset 0 0 0 50px white;
}

#benefitsImgMed {
  margin-left: 8%;
  margin-top: 6%;
  width: 13%;
  height: 13%;
}

Body:
Try this solution:

Note: I've dumbed it down substantially.

body{background-color:black;}

#benefitImgMed {
   transition: 2s;
    width: 200px;
    height: 200px;
   cursor:pointer;
   z-index:1;
   position: absolute;
    border-color: white;
    border-width: 5px;
    border-radius: 50%;
    border-style: dashed;
    overflow: hidden;
}

#benefitImgMed:after{
  content: "";
  position: absolute;
  height: 0%;
  width: 0%;
  background: white;
  opacity: 0;
  top: 50%;
  left: 50%;
  border-radius: 100%;
  transition: all 1s;
}

#benefitImgMed:hover::after{
  background: white;
  height: 100%;
  width: 100%;
  opacity: 1;
  top: 0px;
  left: 0px;
}

<div id="benefitImgMed">

</div>


问:
Simple UML tools
I am looking for a simple UML-tool that will let me do for example a sequence diagram quicker and better than Word from scratch (Without spending to much time on learning the tool, and with the tool more supporting me than constraining me)

Primary choice is Visio.

答: "Simple UML" is a contraction in terms :). But I like Enterprise Architect. It's not free, but it's not a hojillion dollars either. You might also take a look at the list here.</p>

ContentLicense: CC BY-SA 2.5

Title: Simple UML tools


问:
registerTempTable fails on DataFrame created from RDD
This is in Spark 1.6.x. I'm looking for a workaround.

I have a function that creates a DataFrame from a DataFrame's underlying RDD:

```<code>def rddAndBack(sc: SparkContext, df: DataFrame) : DataFrame = {
    val sqlContext = new org.apache.spark.sql.SQLContext(sc)
    sqlContext.createDataFrame(df.rdd, df.schema)
}
</code>```

Now I create a couple data frames and register them:

```<code>val df = sc.parallelize(Array(1, 2, 3)).toDF("foo")
val df2 = rddAndBack(sc, df)
df.registerTempTable("df")
df2.registerTempTable("df2")
</code>```

This works:

```<code>scala> sqlContext.sql("SELECT * FROM df")
res23: org.apache.spark.sql.DataFrame = [foo: int]
</code>```

But this does not:

```<code>scala> sqlContext.sql("SELECT * FROM df2")
org.apache.spark.sql.AnalysisException: Table not found: df2; line 1 pos 14
    at org.apache.spark.sql.catalyst.analysis.package$AnalysisErrorAt.failAnalysis(package.scala:42)
</code>```

This works fine in 2.x but I need to find a workaround in 1.6.

答:
This happens because you create a new SQLContext in your function. Since temporary tables are limited in scope to its parent context, there cannot be accessed from another one.

```<code>df2.sqlContext.sql("SELECT * FROM df2")
</code>```

To solve this, pass existing SQLContext in place of SparkContext:

```<code>def rddAndBack(sqlContext: org.apache.spark.sql.SQLContext, df: DataFrame) = {
  sqlContext.createDataFrame(df.rdd, df.schema)
}
</code>```

or use getOrCreate factory method:

```<code>def rddAndBack(sc: SparkContext, df: DataFrame) : DataFrame = {
  val sqlContext = org.apache.spark.sql.SQLContext.getOrCreate(sc)
  sqlContext.createDataFrame(df.rdd, df.schema)
}
</code>```

or use SQLContext instance bound to the input df:

```<code>def rddAndBack(sc: SparkContext, df: DataFrame) : DataFrame = {
  val sqlContext = df.sqlContext
  sqlContext.createDataFrame(df.rdd, df.schema)
}
</code>```

Body:
This is in Spark 1.6.x. I'm looking for a workaround.

I have a function that creates a DataFrame from a DataFrame's underlying RDD:

def rddAndBack(sc: SparkContext, df: DataFrame) : DataFrame = {
    val sqlContext = new org.apache.spark.sql.SQLContext(sc)
    sqlContext.createDataFrame(df.rdd, df.schema)
}

Now I create a couple data frames and register them:

val df = sc.parallelize(Array(1, 2, 3)).toDF("foo")
val df2 = rddAndBack(sc, df)
df.registerTempTable("df")
df2.registerTempTable("df2")

This works:

scala> sqlContext.sql("SELECT * FROM df")
res23: org.apache.spark.sql.DataFrame = [foo: int]

But this does not:

scala> sqlContext.sql("SELECT * FROM df2")
org.apache.spark.sql.AnalysisException: Table not found: df2; line 1 pos 14
    at org.apache.spark.sql.catalyst.analysis.package$AnalysisErrorAt.failAnalysis(package.scala:42)

This works fine in 2.x but I need to find a workaround in 1.6.

Body:
This happens because you create a new SQLContext in your function. Since temporary tables are limited in scope to its parent context, there cannot be accessed from another one.

df2.sqlContext.sql("SELECT * FROM df2")

To solve this, pass existing SQLContext in place of SparkContext:

def rddAndBack(sqlContext: org.apache.spark.sql.SQLContext, df: DataFrame) = {
  sqlContext.createDataFrame(df.rdd, df.schema)
}

or use getOrCreate factory method:

def rddAndBack(sc: SparkContext, df: DataFrame) : DataFrame = {
  val sqlContext = org.apache.spark.sql.SQLContext.getOrCreate(sc)
  sqlContext.createDataFrame(df.rdd, df.schema)
}

or use SQLContext instance bound to the input df:

def rddAndBack(sc: SparkContext, df: DataFrame) : DataFrame = {
  val sqlContext = df.sqlContext
  sqlContext.createDataFrame(df.rdd, df.schema)
}


问:
Android - Can't connect to database from click listener
I have an AlertDialog that shows, prompts the user to enter text, and if the "Ok" button is pressed, I want it to call a method that connects to a database.

The database methods work because I tried connecting to the database outside the click listener and it works fine.

This is the exception I get:

```<code>com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
</code>```

And this is the method that shows the dialog:

```<code>RetrieveFolder() {
        AlertDialog.Builder inputBox = new AlertDialog.Builder(activity);
        inputBox.setTitle(getResources().getString(R.string.enter_share_code));
        EditText etInput = new EditText(activity);
        etInput.setMaxLines(1);
        inputBox.setView(etInput);

        inputBox.setPositiveButton("Ok", (dialog, whichButton) -> {
            input = etInput.getText().toString();
            if (folderExistsAndIsValid(input) && !alreadyShared(input)) {
                StudE.sendToDatabase("INSERT INTO tblSHARED VALUES(?, ?);", username, input);
                StudE.toast(getResources().getString(R.string.folder_retrieved_successfully), activity);

                finish();
                startActivity(getIntent());
            }
        });

        inputBox.setNegativeButton("Cancel", (dialog, whichButton) -> {});
        inputBox.show();
}
</code>```

Full Stack Trace:

```<code>W/System.err: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
W/System.err:     at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err:     at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
W/System.err:     at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err:     at com.mysql.jdbc.Util.getInstance(Util.java:408)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2275)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2024)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:779)
W/System.err:     at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
W/System.err:     at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err:     at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
W/System.err:     at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
W/System.err:     at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:569)
W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:219)
W/System.err:     at woodward.stude.StudE.makeConnection(StudE.java:91)
W/System.err:     at woodward.stude.StudE.queryDatabase(StudE.java:145)
W/System.err:     at woodward.stude.FlashcardFoldersActivity$RetrieveFolder.folderExistsAndIsValid(FlashcardFoldersActivity.java:305)
W/System.err:     at woodward.stude.FlashcardFoldersActivity$RetrieveFolder.lambda$new$0$FlashcardFoldersActivity$RetrieveFolder(FlashcardFoldersActivity.java:291)
W/System.err:     at woodward.stude.FlashcardFoldersActivity$RetrieveFolder$$Lambda$0.onClick(Unknown Source:0)
W/System.err:     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:106)
W/System.err:     at android.os.Looper.loop(Looper.java:164)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6494)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
W/System.err: Caused by: android.os.NetworkOnMainThreadException
W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)
W/System.err:     at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
W/System.err:     at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:787)
W/System.err:     at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:188)
W/System.err:     at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2196)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2229)
W/System.err:   ... 22 more
</code>```

答:
You should try to connect on the background thread. Connecting to network on main thread : NetworkOnMainThreadException

you can find the answer to your problem here :
ANSWER

Body:
I have an AlertDialog that shows, prompts the user to enter text, and if the "Ok" button is pressed, I want it to call a method that connects to a database.

The database methods work because I tried connecting to the database outside the click listener and it works fine.

This is the exception I get:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.

And this is the method that shows the dialog:

RetrieveFolder() {
        AlertDialog.Builder inputBox = new AlertDialog.Builder(activity);
        inputBox.setTitle(getResources().getString(R.string.enter_share_code));
        EditText etInput = new EditText(activity);
        etInput.setMaxLines(1);
        inputBox.setView(etInput);

        inputBox.setPositiveButton("Ok", (dialog, whichButton) -> {
            input = etInput.getText().toString();
            if (folderExistsAndIsValid(input) && !alreadyShared(input)) {
                StudE.sendToDatabase("INSERT INTO tblSHARED VALUES(?, ?);", username, input);
                StudE.toast(getResources().getString(R.string.folder_retrieved_successfully), activity);

                finish();
                startActivity(getIntent());
            }
        });

        inputBox.setNegativeButton("Cancel", (dialog, whichButton) -> {});
        inputBox.show();
}

Full Stack Trace:

W/System.err: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
W/System.err:     at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err:     at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
W/System.err:     at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err:     at com.mysql.jdbc.Util.getInstance(Util.java:408)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2275)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2024)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:779)
W/System.err:     at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
W/System.err:     at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err:     at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
W/System.err:     at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
W/System.err:     at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:569)
W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:219)
W/System.err:     at woodward.stude.StudE.makeConnection(StudE.java:91)
W/System.err:     at woodward.stude.StudE.queryDatabase(StudE.java:145)
W/System.err:     at woodward.stude.FlashcardFoldersActivity$RetrieveFolder.folderExistsAndIsValid(FlashcardFoldersActivity.java:305)
W/System.err:     at woodward.stude.FlashcardFoldersActivity$RetrieveFolder.lambda$new$0$FlashcardFoldersActivity$RetrieveFolder(FlashcardFoldersActivity.java:291)
W/System.err:     at woodward.stude.FlashcardFoldersActivity$RetrieveFolder$$Lambda$0.onClick(Unknown Source:0)
W/System.err:     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:106)
W/System.err:     at android.os.Looper.loop(Looper.java:164)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6494)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
W/System.err: Caused by: android.os.NetworkOnMainThreadException
W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)
W/System.err:     at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
W/System.err:     at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:787)
W/System.err:     at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:188)
W/System.err:     at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2196)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2229)
W/System.err:   ... 22 more


问:
Phaser - how to select a Tiled map layer and set it as collision layer
I'm quite new to using Phaser and the Tiled map editor and I'm currently making a platformer game using a Tiled map I made. I haven't been able to find any information in the Tiled or Phaser documentation, or in tutorials or forums on how to select a layer in my Tiled map to be a collision layer. In some tutorials I've seen people set a Tiled layer property to collision:true but I think they were using a different Tiled version and I can't see any information on this in the Tiled documentation.

I have 3 layers plus one layer for objects. I've put all the collision tiles in one layer that includes things like the ground and platforms. I've read answers saying that you need to include the index of the collision tiles but I don't want to include individual tiles as there a lot of tiles used. I've included a screenshot of my Tiled map JSON file, the layer I want to make a collision layer is called "Tile Layer 2". I'm not sure if I need to mention this layer name in my Phaser code to make it a collision layer or if I need to set the layer to collision: true in Tiled. I'd really appreciate any suggestions on how to make this a collision layer either using Tiled or Phaser. Thanks.

Tiled map JSON file

答:
Another possibility is to use this Phaser plugin: https://www.npmjs.com/package/phaser-tilemap-plus

You can set up an object layer with polygonal and recyangular shapes and use that as a collision layer. The polygons can be any shape, allowing you to use sloped and curved tiles. You can also have one way shapes for jump through platforms or one way doors. It is also possible to set a rebound value for bouncy surfaces or springs a la Sonic.

Aside from advanced tile collision, you also get tile animations that you define in the Tiled map editor, collision and region event handling and access to meta data in the form of custom properties.


问:
Replace and append part of a String - MySQL
In my table I have a field "youtube" where the user can add a Youtube or Vimeo link. The Youtube links can be played directly, the Vimeo links which looks like:

```<code>https://vimeo.com/22614651XX
</code>```

needs to be replaced by:

```<code>https://player.vimeo.com/video/22614651XX
</code>```

Can this be done with SQL or should it be done in PHP? In PHP I found the substr() Function where I can split a string, but I have no clue how to deal with the numbers as they can vary in length...

答:
thank you for your assistance :-)

```<code>UPDATE wp_awa_upload
SET youtube = REPLACE(youtube, 'https://vimeo.com/', 'https://player.vimeo.com/video/')
WHERE youtube like "%vimeo%"
</code>```

does the trick :-)

Kind Regards,

Stefan

Body:
In my table I have a field "youtube" where the user can add a Youtube or Vimeo link. The Youtube links can be played directly, the Vimeo links which looks like:

https://vimeo.com/22614651XX

needs to be replaced by:

https://player.vimeo.com/video/22614651XX

Can this be done with SQL or should it be done in PHP? In PHP I found the substr() Function where I can split a string, but I have no clue how to deal with the numbers as they can vary in length...

Body:
thank you for your assistance :-)

UPDATE wp_awa_upload
SET youtube = REPLACE(youtube, 'https://vimeo.com/', 'https://player.vimeo.com/video/')
WHERE youtube like "%vimeo%"

does the trick :-)

Kind Regards,

Stefan


问:
theme font doesn't apply to paragraph
Okay, so I am just a beginner in HTML and CSS. I tried to apply wordpress themes font to everything else on the site. The font is "Roboto Condensed", sans-serif; . I even created a custom menu which works perfectly with this font, but when I try to apply it to paragraphs, like product descriptions, it just doesn't work. I tried to edit the style.css file with

* {
font-family: "Roboto Condensed", sans-serif;
}

or

```<code>body {font-family: "Roboto Condensed", sans-serif;}
</code>```

Can some one please tell me maybe I am doing something wrong?

答:
If you have integrated properly the Google Font try with !important:

```<code>* {font-family: "Roboto Condensed", sans-serif !important;}
</code>```

or

```<code>body {font-family: "Roboto Condensed", sans-serif !important;}
</code>```

The CSS assigns a weight to each rule depending on the specificity of its selector and its position in the source. This determines which style is applied to an HTML element.

If 2 rules conflict on a single element then the following principles will be applied:

Origin of rules - If a rule between an author and a user stylesheet conflicts, the user's rules will win over the author's rules.

Specificity - When 2 or more declarations that apply to the same element set the same property and have the same importance and origin, the declaration with the most specific selector will be applied.

Source order - When 2 rules have the same weight, the last rule declared in the stylesheet will be applied.

There might be times when it would be useful to change the order of sequence. It's possible to break that cascading chain by using the !important CSS declaration. When the !important declaration is used on a property/value, that value becomes the most important for that property and overrides any other.

Source: https://www.webcredible.com/blog/importance-important-css-declaration/

Title: theme font doesn't apply to paragraph

Body:
Okay, so I am just a beginner in HTML and CSS. I tried to apply wordpress themes font to everything else on the site. The font is "Roboto Condensed", sans-serif; . I even created a custom menu which works perfectly with this font, but when I try to apply it to paragraphs, like product descriptions, it just doesn't work. I tried to edit the style.css file with

* {
font-family: "Roboto Condensed", sans-serif;
}

or

body {font-family: "Roboto Condensed", sans-serif;}

Can some one please tell me maybe I am doing something wrong?

Body:
If you have integrated properly the Google Font try with !important:

* {font-family: "Roboto Condensed", sans-serif !important;}

or

body {font-family: "Roboto Condensed", sans-serif !important;}

The CSS assigns a weight to each rule depending on the specificity of its selector and its position in the source. This determines which style is applied to an HTML element.

If 2 rules conflict on a single element then the following principles will be applied:

Origin of rules - If a rule between an author and a user stylesheet conflicts, the user's rules will win over the author's rules.

Specificity - When 2 or more declarations that apply to the same element set the same property and have the same importance and origin, the declaration with the most specific selector will be applied.

Source order - When 2 rules have the same weight, the last rule declared in the stylesheet will be applied.

There might be times when it would be useful to change the order of sequence. It's possible to break that cascading chain by using the !important CSS declaration. When the !important declaration is used on a property/value, that value becomes the most important for that property and overrides any other.

Source: https://www.webcredible.com/blog/importance-important-css-declaration/


问:
Python version? Returns below. Why? Fix?
Played with Python a lot some time ago. Had a major crash on MacBook (thought all was corrected) but now, checking version gives me the output below.  Also, pip not working.
Surely someone knows how or why this is the result on the version call.
And perhaps there's a pointer in the direction of how to clean up my system.

Thanks

```<code>d$ python -v
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py
import site # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py
import os # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc
import errno # builtin
import posix # builtin
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py
import posixpath # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.py
import stat # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py
import genericpath # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/warnings.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/warnings.py
import warnings # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/warnings.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/linecache.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/linecache.py
import linecache # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/linecache.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/types.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/types.py
import types # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/types.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.py
import UserDict # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_abcoll.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_abcoll.py
import _abcoll # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_abcoll.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/abc.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/abc.py
import abc # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/abc.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_weakrefset.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_weakrefset.py
import _weakrefset # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_weakrefset.pyc
import _weakref # builtin
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.py
import copy_reg # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/traceback.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/traceback.py
import traceback # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/traceback.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py
import sysconfig # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py
import re # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_compile.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_compile.py
import sre_compile # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_compile.pyc
import _sre # builtin
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_parse.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_parse.py
import sre_parse # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_parse.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_constants.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_constants.py
import sre_constants # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_constants.pyc
dlopen("/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_locale.so", 2);
import _locale # dynamically loaded from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_locale.so
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.py
import _sysconfigdata # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_osx_support.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_osx_support.py
import _osx_support # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_osx_support.pyc
import encodings # directory /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/__init__.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/__init__.py
import encodings # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/__init__.pyc
# /System/Library/Frameworks/P
</code>```

答: --version or capital -V prints the version. Lowercase -v turns on verbose import logging. You want --version or -V.

Body:
Played with Python a lot some time ago. Had a major crash on MacBook (thought all was corrected) but now, checking version gives me the output below.  Also, pip not working.
Surely someone knows how or why this is the result on the version call.
And perhaps there's a pointer in the direction of how to clean up my system.

Thanks

d$ python -v
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py
import site # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py
import os # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc
import errno # builtin
import posix # builtin
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py
import posixpath # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.py
import stat # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py
import genericpath # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/warnings.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/warnings.py
import warnings # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/warnings.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/linecache.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/linecache.py
import linecache # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/linecache.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/types.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/types.py
import types # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/types.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.py
import UserDict # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_abcoll.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_abcoll.py
import _abcoll # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_abcoll.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/abc.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/abc.py
import abc # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/abc.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_weakrefset.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_weakrefset.py
import _weakrefset # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_weakrefset.pyc
import _weakref # builtin
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.py
import copy_reg # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/traceback.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/traceback.py
import traceback # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/traceback.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py
import sysconfig # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py
import re # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_compile.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_compile.py
import sre_compile # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_compile.pyc
import _sre # builtin
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_parse.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_parse.py
import sre_parse # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_parse.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_constants.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_constants.py
import sre_constants # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_constants.pyc
dlopen("/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_locale.so", 2);
import _locale # dynamically loaded from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_locale.so
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.py
import _sysconfigdata # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_osx_support.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_osx_support.py
import _osx_support # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_osx_support.pyc
import encodings # directory /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/__init__.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/__init__.py
import encodings # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/__init__.pyc
# /System/Library/Frameworks/P


问:
troubles with powershell where clause
i am trying to parse a website for specific data.

```<code>$strings = $body.split(";")
$strings2 = $strings.Where({$_ -like ("*recordData[`"key`"]*")})
</code>```

i figured out that the square brackets are to blame, i use

```<code>$strings2 = $strings.Where({$_ -like ("*recordData*")})
</code>```

and it works fine, albeit returning way more results then i need.
is there a way i can just search for "recordData[key]"

$body is just the entirety of a returned webpage

thanks.

EDIT:
as requested the input data is like this

```<code>rs.currentColumn = 0;
recordData["dataGridExtraRow"] = 0;
recordData["rownum"] = "0";

recordData["key"] = '3354087';

recordData["factory"] = "cr";
</code>```

in the end i need the 3354087 number, but just picking out the lines i needed was the issue, after that i can pick apart the string fine.

however, i ended up using the .contains, thanks for the suggestion.
sort of facepalmed after i saw it though.

答:
Try using single quotes and escaping with backticks.

You can also simplify using PowerShell syntax:

$strings = $body -split ';' -like '*recordData`[key`]*'

Title: troubles with powershell where clause

Body:
i am trying to parse a website for specific data.

$strings = $body.split(";")
$strings2 = $strings.Where({$_ -like ("*recordData[`"key`"]*")})

i figured out that the square brackets are to blame, i use

$strings2 = $strings.Where({$_ -like ("*recordData*")})

and it works fine, albeit returning way more results then i need.
is there a way i can just search for "recordData[key]"

$body is just the entirety of a returned webpage

thanks.

EDIT:
as requested the input data is like this

rs.currentColumn = 0;
recordData["dataGridExtraRow"] = 0;
recordData["rownum"] = "0";

recordData["key"] = '3354087';

recordData["factory"] = "cr";

in the end i need the 3354087 number, but just picking out the lines i needed was the issue, after that i can pick apart the string fine.

however, i ended up using the .contains, thanks for the suggestion.
sort of facepalmed after i saw it though.


问:
Can you navigate the contents of a Vector's index via a String?
Is it possible to do something similar to this in Haxe?

```<code>private var _bindingsFiltered:Vector<String>;
_bindingsFiltered = new Vector<String>();

_controller_touched_binding.action = "meta_start";
</code>```

What I would like to be able to do:

```<code>_bindingsFiltered[_controller_touched_binding.action] = "BUTTON_13";
trace(_bindingsFiltered["meta_start"]); //result: "BUTTON_13"
</code>```

I want to be able to override a specific index too (still accessed via a string), with a new value, rather than keep pushing new content to the end of the vector. I have been using 'openfl.utils.Object' to cheat for now but I am looking for a more reliable approach for the long run.

Is there a way to do this in Haxe?

If not, what are my options?

I would also be interested in a solution for this in AS3, if there is one (avoiding the Array class).

My goal is to find a method that I can use in both languages seamlessly (next-to-none, differences).

答:
First, do you really want an array / vector / list, or do you really want a hashmap of key / value pairs? How are you using the collection? Why do you want String keys? And related, is this mostly about access symantics (you want to type it this way), or are the runtime reasons you'd want to use strings (serialization / etc)?

From what you've described, it sounds like what you really want is an Object like the ones in AS3/JS/ECMAScript, with square-bracket access symantics -- obj[key]

Yes, you can do that in Haxe. The openfl.utils.Object class is a helper to do exactly this, using Dynamic objects and reflection. It should compile to exactly what you want on all Haxe targets.

In any case, if you'd like to feel like you're not bound to OpenFL, no problem. Copy the openfl/utils/Object.hx file and place it anywhere you like in your project's class path (and update the package statement).

There's nothing particularly OpenFL-ish about that code. It's pure Haxe code with no dependencies. It provides array access with String keys, as well as toString, toLocaleString, propertyIsEnumerable, iterator, isPrototypeOf, and hasOwnProperty functions (which ECMA-folk are used to.)

The transition from AS3/JS to Haxe is a little weird, especially when it comes to dynamic objects, and I've been meaning to blog more about it. ;) Good luck!

ETA: In truth, you probably want to get away from Dynamic/Reflection, and embrace a more type-strict approach. AS3/JS devs don't understand this at first, but it is where the benefits of Haxe come from. If you don't then your Haxe experience is likely to be unplesant.

Body:
Is it possible to do something similar to this in Haxe?

private var _bindingsFiltered:Vector<String>;
_bindingsFiltered = new Vector<String>();

_controller_touched_binding.action = "meta_start";

What I would like to be able to do:

_bindingsFiltered[_controller_touched_binding.action] = "BUTTON_13";
trace(_bindingsFiltered["meta_start"]); //result: "BUTTON_13"

I want to be able to override a specific index too (still accessed via a string), with a new value, rather than keep pushing new content to the end of the vector. I have been using 'openfl.utils.Object' to cheat for now but I am looking for a more reliable approach for the long run.

Is there a way to do this in Haxe?

If not, what are my options?

I would also be interested in a solution for this in AS3, if there is one (avoiding the Array class).

My goal is to find a method that I can use in both languages seamlessly (next-to-none, differences).


问:
TVML catlog using TVML Templet Server installation
To make a TVML App I got TVML Sample Catlog from Apple https://developer.apple.com/library/tvos/samplecode/TVMLCatalog/Introduction/Intro.html#//apple_ref/doc/uid/TP40016505-Intro-DontLinkElementID_2
Integrate this Catgol need Server installation by this commang
(command specify in Readme.txt file)
$ python -m SimpleHTTPServer 9001

This command in not respnding anything.

答:
It's possible there's something wrong with your python installation.
You can also try: </p>

```<code> ruby -run -ehttpd . -p9001
</code>```

Body:
It's possible there's something wrong with your python installation.
You can also try:

 ruby -run -ehttpd . -p9001


问:
RxJava2 form validation
I have a form with 4 possible options that need to be checked (could be less as well depending on circumstances). There are 2 editexts, one for email and one for a reference field when creating an order.

The email and reference fields may or may not be left empty based on conditions (which are available when the form is created). Additionally we may need to show an alert dialog to tell the user that it may not be possible to show the reference value (to the recipient of the order) and they may also need to agree to a terms and condition alert dialog.

Currently the onConfirm checks is something like this,

```<code>void onCreateOrderConfirmed(@Nullable final String receiverEmail,
                            @Nullable final String reference,
                            @Nullable final Boolean noRefAgreed,
                            @Nullable final Boolean termsAndConditionsAgreed) {

    if (!reviewCompletionState.emailRequirementSatisfied()) {
        if (!isValidEmail(receiverEmail)) {
            view.showEmailError();
            return;
        }

        reviewCompletionState = reviewCompletionState.newBuilder()
                .receiverEmail(receiverEmail)
                .emailRequirementSatisfied(true)
                .build();
    }

    if (!reviewCompletionState.referenceRequirementSatisfied()) {
        if (isEmpty(reference)) {
            view.showReferenceError();
            return;
        }

        reviewCompletionState = reviewCompletionState.newBuilder()
                .reference(reference)
                .referenceRequirementSatisfied(true)
                .build();
    }

    if (!reviewCompletionState.noRefAgreed()) {
        if (noRefAgreed == null || !noRefAgreed) {
            view.showNoReferenceAlert();
            return;
        }

        reviewCompletionState = reviewCompletionState.newBuilder()
                .noRefAgreed(true)
                .build();
    }

    if (!reviewCompletionState.termsAndConditionsAgreed()) {
        if (termsAndConditionsAgreed == null || !termsAndConditionsAgreed) {
            view.showTermsDisclaimerAlert();
            return;
        }

        reviewCompletionState = reviewCompletionState.newBuilder()
                .termsAndConditionsAgreed(true)
                .build();
    }

    createOrder();
}
</code>```

I would love to know if there is a way to make this validation simpler with RxJava2? (but don't currently know enough to be able to do this)

TIA

答:
This can be a simple. There will be a lot of code, I'll show the result first.

```<code>    private ReviewValidator reviewValidator = new ReviewValidator();

    void onCreateOrderConfirmed(@Nullable final String receiverEmail,
                                @Nullable final String reference,
                                @Nullable final Boolean noRefAgreed,
                                @Nullable final Boolean termsAndConditionsAgreed) {
        ReviewState reviewState = new ReviewState(receiverEmail,
                reference,
                noRefAgreed,
                termsAndConditionsAgreed);//another model for simplicity

        reviewValidator.validate(reviewState)
                .flatMap(reviewState -> /* create order */)
                .subscribe(this::onOrderCreated, this::onOrderCreatingError);

    }

    void onOrderCreated(Object order) {//or what you need here
        //handle positive result
    }

    void onOrderCreatingError(Throwable throwable) {
        if (throwable instanceof ValidateException) {
            List<ValidateError> errors = ((ValidateException) throwable).getValidateErrors();
            for (ValidateError error: errors) {
                switch (error.getField()) {
                    case EMAIL: {
                        view.showEmailError();
                        return;//or break if you want show all errors
                    }
                    case REFERENCE: {
                        view.showReferenceError();
                        return;
                    }
                    //handle another errors....
                }
            }
        //handle another error cases...
    }
</code>```

First, create model for reviewState:

```<code>public class ReviewState {

    private String receiverEmail;
    private String reference;
    private Boolean noRefAgreed;
    private Boolean termsAndConditionsAgree;

    public ReviewState(String receiverEmail,
                       String reference,
                       Boolean noRefAgreed,
                       Boolean termsAndConditionsAgree) {
        this.receiverEmail = receiverEmail;
        this.reference = reference;
        this.noRefAgreed = noRefAgreed;
        this.termsAndConditionsAgree = termsAndConditionsAgree;
    }

    public String getReceiverEmail() {
        return receiverEmail;
    }

    public String getReference() {
        return reference;
    }

    public Boolean getNoRefAgreed() {
        return noRefAgreed;
    }

    public Boolean getTermsAndConditionsAgree() {
        return termsAndConditionsAgree;
    }
}
</code>```

Then create you own validator. It is not necessary to create a whole model, you can create validator for every field and and link them with flatMap(), your choice.

```<code>public class ReviewValidator extends Validator<ReviewState> {

    @Override
    protected List<ValidateFunction> getValidateFunctions(ReviewState reviewState) {
        List<ValidateFunction> validateFunctions = new LinkedList<>();
        validateFunctions.add(() -> validateEmail(reviewState.getReceiverEmail()));
        validateFunctions.add(() -> validateReference(reviewState.getReference()));
        //another validation methods
        return validateFunctions;
    }

    private ValidateError validateEmail(String email) {
        if (TextUtils.isEmpty(email)) {
            return new ValidateError(Field.EMAIL);//Field.EMAIL - just enum
        }
        return null;
    }

    private ValidateError validateReference(String reference) {
        if (TextUtils.isEmpty(reference)) {
            return new ValidateError(Field.REFERENCE);
        }
        return null;
    }
    //....
    //another validation methods
}
</code>```

Abstract class for validator:

```<code>public abstract class Validator<Model> {

    public Single<Model> validate(Model model) {
        return Single.just(model)
                .map(this::validateModel)
                .flatMap(this::processResult);
    }

    private Single<Model> processResult(ValidateResultModel<Model> validateResultModel) {
        return Single.create(subscriber -> {
            List<ValidateError> validateErrors = validateResultModel.getValidateErrors();
            if (validateErrors.isEmpty()) {
                subscriber.onSuccess(validateResultModel.getModel());
            } else {
                subscriber.onError(new ValidateException(validateErrors));
            }
        });
    }

    private ValidateResultModel<Model> validateModel(Model model) {
        List<ValidateError> errors = new LinkedList<>();
        for (ValidateFunction validateFunctions : getValidateFunctions(model)) {
            ValidateError error = validateFunctions.validate();
            if (error != null) {
                errors.add(error);
            }
        }
        return new ValidateResultModel<>(model, errors);
    }

    protected abstract List<ValidateFunction> getValidateFunctions(Model model);

    protected interface ValidateFunction {

        @Nullable
        ValidateError validate();
    }
}
</code>```

Helper classes for validator...

```<code>public class ValidateError {

    private Field field;

    public ValidateError(Field field) {
        this.field = field;
    }

    public Field getField() {
        return field;
    }
}

class ValidateResultModel<T> {

    private T model;
    private List<ValidateError> validateErrors;

    ValidateResultModel(T model, List<ValidateError> validateErrors) {
        this.model = model;
        this.validateErrors = validateErrors;
    }

    T getModel() {
        return model;
    }

    List<ValidateError> getValidateErrors() {
        return validateErrors;
    }
}

public class ValidateException extends RuntimeException {

    private List<ValidateError> validateErrors;

    ValidateException(List<ValidateError> validateErrors) {
        this.validateErrors = validateErrors;
    }

    public List<ValidateError> getValidateErrors() {
        return validateErrors;
    }
}
</code>```

Initially, I took the idea from here: https://github.com/matzuk/TestableCodeMobius/tree/master/app/src/main/java/com/matsyuk/testablecodemobius/business/transfer/validation

Title: RxJava2 form validation

Body:
I have a form with 4 possible options that need to be checked (could be less as well depending on circumstances). There are 2 editexts, one for email and one for a reference field when creating an order.

The email and reference fields may or may not be left empty based on conditions (which are available when the form is created). Additionally we may need to show an alert dialog to tell the user that it may not be possible to show the reference value (to the recipient of the order) and they may also need to agree to a terms and condition alert dialog.

Currently the onConfirm checks is something like this,

void onCreateOrderConfirmed(@Nullable final String receiverEmail,
                            @Nullable final String reference,
                            @Nullable final Boolean noRefAgreed,
                            @Nullable final Boolean termsAndConditionsAgreed) {

    if (!reviewCompletionState.emailRequirementSatisfied()) {
        if (!isValidEmail(receiverEmail)) {
            view.showEmailError();
            return;
        }

        reviewCompletionState = reviewCompletionState.newBuilder()
                .receiverEmail(receiverEmail)
                .emailRequirementSatisfied(true)
                .build();
    }

    if (!reviewCompletionState.referenceRequirementSatisfied()) {
        if (isEmpty(reference)) {
            view.showReferenceError();
            return;
        }

        reviewCompletionState = reviewCompletionState.newBuilder()
                .reference(reference)
                .referenceRequirementSatisfied(true)
                .build();
    }

    if (!reviewCompletionState.noRefAgreed()) {
        if (noRefAgreed == null || !noRefAgreed) {
            view.showNoReferenceAlert();
            return;
        }

        reviewCompletionState = reviewCompletionState.newBuilder()
                .noRefAgreed(true)
                .build();
    }

    if (!reviewCompletionState.termsAndConditionsAgreed()) {
        if (termsAndConditionsAgreed == null || !termsAndConditionsAgreed) {
            view.showTermsDisclaimerAlert();
            return;
        }

        reviewCompletionState = reviewCompletionState.newBuilder()
                .termsAndConditionsAgreed(true)
                .build();
    }

    createOrder();
}

I would love to know if there is a way to make this validation simpler with RxJava2? (but don't currently know enough to be able to do this)

TIA

Body:
This can be a simple. There will be a lot of code, I'll show the result first.

    private ReviewValidator reviewValidator = new ReviewValidator();

    void onCreateOrderConfirmed(@Nullable final String receiverEmail,
                                @Nullable final String reference,
                                @Nullable final Boolean noRefAgreed,
                                @Nullable final Boolean termsAndConditionsAgreed) {
        ReviewState reviewState = new ReviewState(receiverEmail,
                reference,
                noRefAgreed,
                termsAndConditionsAgreed);//another model for simplicity

        reviewValidator.validate(reviewState)
                .flatMap(reviewState -> /* create order */)
                .subscribe(this::onOrderCreated, this::onOrderCreatingError);

    }

    void onOrderCreated(Object order) {//or what you need here
        //handle positive result
    }

    void onOrderCreatingError(Throwable throwable) {
        if (throwable instanceof ValidateException) {
            List<ValidateError> errors = ((ValidateException) throwable).getValidateErrors();
            for (ValidateError error: errors) {
                switch (error.getField()) {
                    case EMAIL: {
                        view.showEmailError();
                        return;//or break if you want show all errors
                    }
                    case REFERENCE: {
                        view.showReferenceError();
                        return;
                    }
                    //handle another errors....
                }
            }
        //handle another error cases...
    }

First, create model for reviewState:

public class ReviewState {

    private String receiverEmail;
    private String reference;
    private Boolean noRefAgreed;
    private Boolean termsAndConditionsAgree;

    public ReviewState(String receiverEmail,
                       String reference,
                       Boolean noRefAgreed,
                       Boolean termsAndConditionsAgree) {
        this.receiverEmail = receiverEmail;
        this.reference = reference;
        this.noRefAgreed = noRefAgreed;
        this.termsAndConditionsAgree = termsAndConditionsAgree;
    }

    public String getReceiverEmail() {
        return receiverEmail;
    }

    public String getReference() {
        return reference;
    }

    public Boolean getNoRefAgreed() {
        return noRefAgreed;
    }

    public Boolean getTermsAndConditionsAgree() {
        return termsAndConditionsAgree;
    }
}

Then create you own validator. It is not necessary to create a whole model, you can create validator for every field and and link them with flatMap(), your choice.

public class ReviewValidator extends Validator<ReviewState> {

    @Override
    protected List<ValidateFunction> getValidateFunctions(ReviewState reviewState) {
        List<ValidateFunction> validateFunctions = new LinkedList<>();
        validateFunctions.add(() -> validateEmail(reviewState.getReceiverEmail()));
        validateFunctions.add(() -> validateReference(reviewState.getReference()));
        //another validation methods
        return validateFunctions;
    }

    private ValidateError validateEmail(String email) {
        if (TextUtils.isEmpty(email)) {
            return new ValidateError(Field.EMAIL);//Field.EMAIL - just enum
        }
        return null;
    }

    private ValidateError validateReference(String reference) {
        if (TextUtils.isEmpty(reference)) {
            return new ValidateError(Field.REFERENCE);
        }
        return null;
    }
    //....
    //another validation methods
}

Abstract class for validator:

public abstract class Validator<Model> {

    public Single<Model> validate(Model model) {
        return Single.just(model)
                .map(this::validateModel)
                .flatMap(this::processResult);
    }

    private Single<Model> processResult(ValidateResultModel<Model> validateResultModel) {
        return Single.create(subscriber -> {
            List<ValidateError> validateErrors = validateResultModel.getValidateErrors();
            if (validateErrors.isEmpty()) {
                subscriber.onSuccess(validateResultModel.getModel());
            } else {
                subscriber.onError(new ValidateException(validateErrors));
            }
        });
    }

    private ValidateResultModel<Model> validateModel(Model model) {
        List<ValidateError> errors = new LinkedList<>();
        for (ValidateFunction validateFunctions : getValidateFunctions(model)) {
            ValidateError error = validateFunctions.validate();
            if (error != null) {
                errors.add(error);
            }
        }
        return new ValidateResultModel<>(model, errors);
    }

    protected abstract List<ValidateFunction> getValidateFunctions(Model model);

    protected interface ValidateFunction {

        @Nullable
        ValidateError validate();
    }
}

Helper classes for validator...

public class ValidateError {

    private Field field;

    public ValidateError(Field field) {
        this.field = field;
    }

    public Field getField() {
        return field;
    }
}

class ValidateResultModel<T> {

    private T model;
    private List<ValidateError> validateErrors;

    ValidateResultModel(T model, List<ValidateError> validateErrors) {
        this.model = model;
        this.validateErrors = validateErrors;
    }

    T getModel() {
        return model;
    }

    List<ValidateError> getValidateErrors() {
        return validateErrors;
    }
}

public class ValidateException extends RuntimeException {

    private List<ValidateError> validateErrors;

    ValidateException(List<ValidateError> validateErrors) {
        this.validateErrors = validateErrors;
    }

    public List<ValidateError> getValidateErrors() {
        return validateErrors;
    }
}

Initially, I took the idea from here: https://github.com/matzuk/TestableCodeMobius/tree/master/app/src/main/java/com/matsyuk/testablecodemobius/business/transfer/validation


问:
C# Target="_blank" in a LinkButton
is it possible to have a target="_blank" in LinkButton...mine doesnt seem to be working

```<code><asp:LinkButton runat="server" ID="g31" Text="PDF"
    CommandArgument='<%# DataBinder.Eval(Container.DataItem,"productID") %>'
    CommandName='<%# DataBinder.Eval(Container.DataItem,"documentID") %>'
    OnCommand="linkbutton_showpdf" target="_blank">
</asp:LinkButton>
</code>```

Or would I have to use a different button format?

答:
Adding to @Devsainii answer above.

Add the attribute OnClientClick="window.document.forms[0].target='_blank';" to your LinkButton and then in the code behind, just use Response.Redirect("~/AnotherPage.aspx") to navigate to another page.

ContentLicense: CC BY-SA 4.0

Title: C# Target="_blank" in a LinkButton

Body:
is it possible to have a target="_blank" in LinkButton...mine doesnt seem to be working

<asp:LinkButton runat="server" ID="g31" Text="PDF"
    CommandArgument='<%# DataBinder.Eval(Container.DataItem,"productID") %>'
    CommandName='<%# DataBinder.Eval(Container.DataItem,"documentID") %>'
    OnCommand="linkbutton_showpdf" target="_blank">
</asp:LinkButton>

Or would I have to use a different button format?


问:
Closing Smart App Banner in iOS Appium test
I'm testing a website using Appium for iOS.  The site has an associated app and uses Apple's Smart App Banners to promote the app.  I'd like to test for the presence of the banner and close it at the beginning of my Appium test, but the banner doesn't appear to exist in the DOM.  Is there any way to do this, short of mousing around with a pixel location?</p>

答:
Try to switch to native context:

```<code>driver.context("NATIVE_APP");
</code>```

and check if it contains banner, for quick investigation you can print to console result of driver.getPageSource()

Body:
Try to switch to native context:

driver.context("NATIVE_APP");

and check if it contains banner, for quick investigation you can print to console result of driver.getPageSource()


问:
Can't connect to MongoDB remote server
I have setup mongodb on a Google cloud compute instance and am trying to connect to it remotely. My mongod.conf file looks like this:

```<code># mongod.conf
# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:
# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log
# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0
#processManagement:
security:
  authorization: 'enabled'
</code>```

I have setup a firewall rule in my Google Cloud console that tags the instance and opens tcp:27017 for ip ranges 0.0.0.0/0.

Checking on the port 27017 it looks like mongo is listening:

```<code>sudo netstat -tulpn | grep 27017
tcp        0      0 0.0.0.0:27017           0.0.0.0:*               LISTEN      3781/mongod
</code>```

Overall it also seems like port 27017 is open:

```<code>netstat --listen
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 *:27017                 *:*                     LISTEN
...
</code>```

On the instance I setup an admin database with admin user:

```<code>>use admin
>db.createUser(
  {
    user: 'admin',
    pwd: 'somepass',
    roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
  }
)
</code>```

I also setup a user for a test database:

```<code>>use test
>db.createUser(
  {
    user: 'tester',
    pwd: 'apassword',
    roles: [{ role: "readWrite", db: "test" },
            { role: "read", db: "reporting" }]
  }
)
</code>```

This user works locally:

```<code>>use test
>db.auth('tester', 'apassword')
1
</code>```

However when I try to connect remotely it fails:

```<code>$ mongo -u tester -p apassword 12.345.67.890/test
MongoDB shell version v3.4.1
connecting to: mongodb://12.345.67.890/test
2017-11-14T12:47:07.369-0700 W NETWORK  [main] Failed to connect to 12.345.67.890:27017 after 5000ms milliseconds, giving up.
2017-11-14T12:47:07.370-0700 E QUERY    [main] Error: couldn't connect to server 12.345.67.890:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:234:13
@(connect):1:6
exception: connect failed
</code>```

I'm not a networking expert so I've pretty much exhausted my knowledge at this point and don't know how to proceed.

Am I missing something in mongod.conf? Did i setup the firewall incorrectly? Any help is appreciated.

答:
I came up with a solution for this, but I'm unclear why it works and not my original approach.

My instance has http/https enabled. This uses the firewall rules default-allow-http and default-allow-https. These rules enable connections from anywhere (0.0.0.0/0) through tcp ports 80 and 443 respectively. I edited the http rule and added tcp port 27017.

Now I can connect to the server.

As a test, I reset the http rule and added another rule applied to all instances opening up tcp:27017 to 0.0.0.0/0. Essentially everything is the same as the http rule save for the name and the target tags. With this change I cannot connect to the server.

It seems rather strange and it doesn't feel like an intended behavior, unless my understanding of the firewall rules in incomplete.

In the end it looks like either setting up mongo to use one of the http/https ports or adding port 27017 to those rules is the way to go.

Title: Can't connect to MongoDB remote server

Body:
I have setup mongodb on a Google cloud compute instance and am trying to connect to it remotely. My mongod.conf file looks like this:

# mongod.conf
# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:
# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log
# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0
#processManagement:
security:
  authorization: 'enabled'

I have setup a firewall rule in my Google Cloud console that tags the instance and opens tcp:27017 for ip ranges 0.0.0.0/0.

Checking on the port 27017 it looks like mongo is listening:

sudo netstat -tulpn | grep 27017
tcp        0      0 0.0.0.0:27017           0.0.0.0:*               LISTEN      3781/mongod

Overall it also seems like port 27017 is open:

netstat --listen
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 *:27017                 *:*                     LISTEN
...

On the instance I setup an admin database with admin user:

>use admin
>db.createUser(
  {
    user: 'admin',
    pwd: 'somepass',
    roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
  }
)

I also setup a user for a test database:

>use test
>db.createUser(
  {
    user: 'tester',
    pwd: 'apassword',
    roles: [{ role: "readWrite", db: "test" },
            { role: "read", db: "reporting" }]
  }
)

This user works locally:

>use test
>db.auth('tester', 'apassword')
1

However when I try to connect remotely it fails:

$ mongo -u tester -p apassword 12.345.67.890/test
MongoDB shell version v3.4.1
connecting to: mongodb://12.345.67.890/test
2017-11-14T12:47:07.369-0700 W NETWORK  [main] Failed to connect to 12.345.67.890:27017 after 5000ms milliseconds, giving up.
2017-11-14T12:47:07.370-0700 E QUERY    [main] Error: couldn't connect to server 12.345.67.890:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:234:13
@(connect):1:6
exception: connect failed

I'm not a networking expert so I've pretty much exhausted my knowledge at this point and don't know how to proceed.

Am I missing something in mongod.conf? Did i setup the firewall incorrectly? Any help is appreciated.


问:
Function call interpreted as declaration
The function call below generates compiler error:

```<code>void myfun() {}

myfun(); // error:
         // gcc -- error: expected constructor, destructor, or type conversion before ';' token
         // clang -- error: C++ requires a type specifier for all declarations

int main()
{
  // ...
}
</code>```

Can somebody explain it? How is the function call confused with a declaration? Why does the error go away if the function call is moved inside main()?

答:
You cannot execute function calls outside of functions unless you use them for variable initialization. So you should write ...

```<code>void myfun() {}

int main()
{
  myfun();
}
</code>```

or

```<code>int myfun() { return 1; }

int dummy = myfun();

int main()    {
}
</code>```

Body:
The function call below generates compiler error:

void myfun() {}

myfun(); // error:
         // gcc -- error: expected constructor, destructor, or type conversion before ';' token
         // clang -- error: C++ requires a type specifier for all declarations

int main()
{
  // ...
}

Can somebody explain it? How is the function call confused with a declaration? Why does the error go away if the function call is moved inside main()?

Body:
You cannot execute function calls outside of functions unless you use them for variable initialization. So you should write ...

void myfun() {}

int main()
{
  myfun();
}

or

int myfun() { return 1; }

int dummy = myfun();

int main()    {
}


问:
Javascript - Array from JSON to object
I have the following react class PeopleSelector within I want to get an array of peoples from my people.json.

```<code>// @flow

import React from 'react'

type Props = {
  currentPeople: string,
  setPeopleFn: (string) => void
}

class PeopleSelector extends React.Component {
  render() {
    let peoples = require('../data/people.json');

    return <select value={this.props.currentPeople} onChange={e => this.props.setPeopleFn(e.target.value)}>
      <style jsx>{`
        select {
          font-size: 20px;
          line-height: 20px;
          margin-bottom: 20px;
          min-width: 300px;
        }
      `}</style>
      {peoples.map(name => (
        <option key={name}>
          {name}
        </option>
      ))}
    </select>
  }
}

export default PeopleSelector
</code>```

Sadly there occurs an error saying people.map is not a function. But why?

My JSON looks like

```<code>{
    "peoples": [
        {
            "focusedTrackId": "MOBILE",
            "milestoneByTrack": {
                "COMMUNICATION": 3,
                "CRAFT": 2,
                "DESKTOP": 0,
                "MENTORSHIP": 2,
                "MOBILE": 3,
                "PROJECT_MANAGEMENT": 3,
                "SERVER": 0
            },
            "name": "Bocksteger, Daniel",
            "title": "Entwickler I"
        }
    ]
}
</code>```

Is it not possible to render the JSON into an object of peoples?

Using peoples.peoples.map results in the following react-error:

```<code>Objects are not valid as a React child (found: object with keys
{focusedTrackId, milestoneByTrack, name, title}). If you meant to
render a collection of children, use an array instead.
</code>```

答:
I think you intent to do peoples.peoples.map(name => {});

When you require the json file you are importing it as a root object. The peoples array will then be (imported as).peoples. i.e peoples.peoples.map();

Title: Javascript - Array from JSON to object

Body:
I have the following react class PeopleSelector within I want to get an array of peoples from my people.json.

// @flow

import React from 'react'

type Props = {
  currentPeople: string,
  setPeopleFn: (string) => void
}

class PeopleSelector extends React.Component {
  render() {
    let peoples = require('../data/people.json');

    return <select value={this.props.currentPeople} onChange={e => this.props.setPeopleFn(e.target.value)}>

      {peoples.map(name => (
        <option key={name}>
          {name}
        </option>
      ))}
    </select>
  }
}

export default PeopleSelector

Sadly there occurs an error saying people.map is not a function. But why?

My JSON looks like

{
    "peoples": [
        {
            "focusedTrackId": "MOBILE",
            "milestoneByTrack": {
                "COMMUNICATION": 3,
                "CRAFT": 2,
                "DESKTOP": 0,
                "MENTORSHIP": 2,
                "MOBILE": 3,
                "PROJECT_MANAGEMENT": 3,
                "SERVER": 0
            },
            "name": "Bocksteger, Daniel",
            "title": "Entwickler I"
        }
    ]
}

Is it not possible to render the JSON into an object of peoples?

Using peoples.peoples.map results in the following react-error:

Objects are not valid as a React child (found: object with keys
{focusedTrackId, milestoneByTrack, name, title}). If you meant to
render a collection of children, use an array instead.


问:
In jQuery is there way for slideDown() method to scroll the page down too?
The slideDown() applied to a div element does the slide down, but doesn't scroll the page down and the div slided down div remains hidden from view.

Is there a way to scroll the page down as well so the user can view the div?

答:
Quick demo here

Basically all you need is

```<code> $('html, body').animate({
      scrollTop: $('#yourDiv').offset().top
  }, 3000);
</code>```

OwnerDisplayName: Xardas

LastEditorDisplayName: Rob

Body:
Quick demo here

Basically all you need is

 $('html, body').animate({
      scrollTop: $('#yourDiv').offset().top
  }, 3000);

OwnerDisplayName: redsquare


问:
bufferReader or InputStreamReader always throws exception
I created a java program that would just read a webpages code... google's for example and it works fine.  However I have tried to implement the same code in an android application both in the emulator and on the actual device-Droid X.

I've tried two separate ways and have found either way it is the same line that throws the IOException.  It is the line that creates the new bufferReader.  I don't know if it is the bufferReader or the InputStreamReader.  Also I don't really know how to get anymore information out of the exceptions other than to print out IOException.  Here is the important code stripped down. Thanks.

```
try
        {
//method 1
         URL page = new URL("http://192.168.1.108/score.php");
         URLConnection pageconnection = page.openConnection();
         BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    pageconnection.getInputStream()));

//method 2
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            BufferedReader rd  = new BufferedReader(new InputStreamReader(conn.getInputStream()));

while ((inputLine = rd.readLine()) != null)
            System.out.println(inputLine);

          in.close();
          rd.close();
            HscoreText.setText("It Worked!");
        }
        catch(MalformedURLException e)
        {
         HscoreText.setText("MalformedURL");
        }
        catch (IOException e)
        {
         HscoreText.setText("IOException");
        }
```

答: It's worth noting that your code (both versions) assumes that the HTML returned has the same character encoding as your platform default encoding. This may not be true even if the server is running on the same machine.</p>

Body:
I created a java program that would just read a webpages code... google's for example and it works fine.  However I have tried to implement the same code in an android application both in the emulator and on the actual device-Droid X.

I've tried two separate ways and have found either way it is the same line that throws the IOException.  It is the line that creates the new bufferReader.  I don't know if it is the bufferReader or the InputStreamReader.  Also I don't really know how to get anymore information out of the exceptions other than to print out IOException.  Here is the important code stripped down. Thanks.

try
        {
//method 1
         URL page = new URL("http://192.168.1.108/score.php");
         URLConnection pageconnection = page.openConnection();
         BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    pageconnection.getInputStream()));

//method 2
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            BufferedReader rd  = new BufferedReader(new InputStreamReader(conn.getInputStream()));

while ((inputLine = rd.readLine()) != null)
            System.out.println(inputLine);

          in.close();
          rd.close();
            HscoreText.setText("It Worked!");
        }
        catch(MalformedURLException e)
        {
         HscoreText.setText("MalformedURL");
        }
        catch (IOException e)
        {
         HscoreText.setText("IOException");
        }


问:
Get String in YYYYMMDD format from JS date object?
I'm trying to use JS to turn a date object into a string in YYYYMMDD format.  Is there an easier way than concatenating Date.getYear(), Date.getMonth(), and Date.getDay()?

答:
Native Javascript:</p>

```<code>new Date().toLocaleString('zu-ZA').slice(0,10).replace(/-/g,'');
</code>```

Body:
Native Javascript:

new Date().toLocaleString('zu-ZA').slice(0,10).replace(/-/g,'');


答:
You can cleanly extract (destructure) the part you really need like this:

let { peoples } = require('../data/people.json');

Title: Javascript - Array from JSON to object


问:
Logstash not reading file input
I have a strange problem with Logstash. I am providing a log file as input to logstash. The configuration is as follows:

```<code>input {
  file {
    type => "apache-access"
    path => ["C:\Users\spanguluri\Downloads\logstash\bin\test.log"]
  }
}
output {
  elasticsearch {
    protocol => "http"
    host => "10.35.143.93"
    port => "9200"
    index => "latestindex"
  }
}
</code>```

I am running elasticsearch server already and verifying if the data is being received with
curl queries. The problem is, no data is being received when the input is a file. However, if I change input to stdin { } as follows, it sends all input data smoothly:

```<code>input {
  stdin{ }
}
output {
  elasticsearch {
    protocol => "http"
    host => "10.35.143.93"
    port => "9200"
    index => "latestindex"
  }
}
</code>```

I don't get where I am going wrong. Can someone please take a look at this?

答: In addition to the provided answer, I had to change the path from c:\my\path to c:/my/path in order for it to read the files.</p>

Title: Logstash not reading file input

Body:
I have a strange problem with Logstash. I am providing a log file as input to logstash. The configuration is as follows:

input {
  file {
    type => "apache-access"
    path => ["C:\Users\spanguluri\Downloads\logstash\bin\test.log"]
  }
}
output {
  elasticsearch {
    protocol => "http"
    host => "10.35.143.93"
    port => "9200"
    index => "latestindex"
  }
}

I am running elasticsearch server already and verifying if the data is being received with
curl queries. The problem is, no data is being received when the input is a file. However, if I change input to stdin { } as follows, it sends all input data smoothly:

input {
  stdin{ }
}
output {
  elasticsearch {
    protocol => "http"
    host => "10.35.143.93"
    port => "9200"
    index => "latestindex"
  }
}

I don't get where I am going wrong. Can someone please take a look at this?


问:
Js compress by uglify-js give error Unexpected token: name ($)
I am compress my js files by uglify-js
   I want to compress Bootstrap 4 js file but it give me Error like this.
   Can I compress all js files by only uglify-js Or how can i do it.

```<code>    Parse error at src\bootstrap\alert.js:1,7
    import $ from 'jquery'
           ^
    ERROR: Unexpected token: name ($)
</code>```

my package.json

```<code>"devDependencies": {
    "node-sass": "^4.6.1",
    "nodemon": "^1.12.1"
  },
  "dependencies": {
    "autoprefixer": "^7.1.6",
    "jquery": "^3.2.1",
    "postcss-cli": "^4.1.1",
    "uglify-js": "^3.1.9"
  }
</code>```

答:
uglify-js does not support ES2015 syntax like import statements or arrow functions. Instead, use the uglify-es module:

-    "uglify-js": "^3.1.9"
+    "uglify-es": "^3.1.9"
```

Body:
I am compress my js files by uglify-js
   I want to compress Bootstrap 4 js file but it give me Error like this.
   Can I compress all js files by only uglify-js Or how can i do it.

    Parse error at src\bootstrap\alert.js:1,7
    import $ from 'jquery'
           ^
    ERROR: Unexpected token: name ($)

my package.json

"devDependencies": {
    "node-sass": "^4.6.1",
    "nodemon": "^1.12.1"
  },
  "dependencies": {
    "autoprefixer": "^7.1.6",
    "jquery": "^3.2.1",
    "postcss-cli": "^4.1.1",
    "uglify-js": "^3.1.9"
  }


问:
Python Multidimensional Array as a single List
Sure, you can have nested lists to represent multidimensional arrays, but that seems costly...

```<code>[[0, 1], [2, 3]]
</code>```

Is there some way to "encode" and "decode" the coordinate into a single number, and use that number to lookup the corresponding element?

```<code>[0, 1, 2, 3]
</code>```

This needs to work with n-dimensions, not just two, and the best I could come up with for encoding is:

```<code>def getcellindex(self, location):
  cindex = 0
  cdrop = self.gridsize # where self.gridsize is the number of cells
  for index in xrange(self.numdimensions): # where self.numdimensions is the number of dimensions
    # where self.dimensions is a tuple of the different sizes of the corresponding dimension
    cdrop /= self.dimensions[index]
    cindex += cdrop * location[index]
  return cindex
</code>```

There're probably ways to optimize this, but more importantly, how do I reverse the process?  And, does this function work?

答: If you want fast arrays you may want to see numpy arrays which are pretty fast. Otherwise if you have dimensions n1, n2, n3, ...,nm, then you can encode a[i][j][k]...[r]: i * (product of (n2, n3...)) + j * (product of (n3, n4...)) + r. The reverse operation you have to get module of nm and that will be r, then you have to substract r and find module of nm*n(m-1) and so on.</p>

Body:
Sure, you can have nested lists to represent multidimensional arrays, but that seems costly...

[[0, 1], [2, 3]]

Is there some way to "encode" and "decode" the coordinate into a single number, and use that number to lookup the corresponding element?

[0, 1, 2, 3]

This needs to work with n-dimensions, not just two, and the best I could come up with for encoding is:

def getcellindex(self, location):
  cindex = 0
  cdrop = self.gridsize # where self.gridsize is the number of cells
  for index in xrange(self.numdimensions): # where self.numdimensions is the number of dimensions
    # where self.dimensions is a tuple of the different sizes of the corresponding dimension
    cdrop /= self.dimensions[index]
    cindex += cdrop * location[index]
  return cindex

There're probably ways to optimize this, but more importantly, how do I reverse the process?  And, does this function work?