问:
No such file or directory mysql
Hello I am getting the following error while trying to connect to a database with mysql with php:

```<code>Warning: mysqli_connect(): (HY000/2002): No such file or directory in /Users/minimoe/db.php on line 5
</code>```

Here is the code that I ran:

```<code>$db = mysqli_connect('localhost','','','scheduler');
echo $db;
</code>```

(I've also attempted to replace the second parameter with 'root' as well but this changes nothing)
Edit:
I've also tried: mysqli_connect('localhost','minimoe','','scheduler'); but this hasn't worked

I've also tried: mysqli_connect('localhost','root','','scheduler'); but this hasn't worked
 / end of edit

So my question is: How can I connect to my database using mysql and php and fix this error?

Some info:

1. I am using php built in web server by running php -S localhost:3306

2. php version 5.6.30

3. Server version: 5.7.18 Homebrew

Extra info:

However I ran the following code using postgresql (I created a test db in psql) and it worked fine:

```<code> $db = pg_connect("host=localhost dbname=scheduler user=minimoe password=''");
</code>```

 Because I am fairly certain this question will be flagged as a duplicate, even though I haven't found an answer that will work for me, yet (although I have not googled the entirety of the vast web

I have tested several other similar questions answers in stack overflow to no avail, yet.

Some answers in other stack overflows that hasn't worked for me after trying them:

1. replacing mysql_connect with mysqli_connect (because I'm already using this)

2. replacing localhost with http://127.0.0.1/, this doesn't work for me either

3. replacing mysqli_connect with mysql() function

I hope I've provided enough info, comment if you need anything else to solve this. Thank you

答:
In a previous comment you stated you used root as the username have you tried that?

mysqli_connect('localhost','root','','scheduler');

Title: No such file or directory mysql

Body:
Hello I am getting the following error while trying to connect to a database with mysql with php:

Warning: mysqli_connect(): (HY000/2002): No such file or directory in /Users/minimoe/db.php on line 5

Here is the code that I ran:

$db = mysqli_connect('localhost','','','scheduler');
echo $db;

(I've also attempted to replace the second parameter with 'root' as well but this changes nothing)
Edit:
I've also tried: mysqli_connect('localhost','minimoe','','scheduler'); but this hasn't worked

I've also tried: mysqli_connect('localhost','root','','scheduler'); but this hasn't worked
 / end of edit

So my question is: How can I connect to my database using mysql and php and fix this error?

Some info:

1. I am using php built in web server by running php -S localhost:3306

2. php version 5.6.30

3. Server version: 5.7.18 Homebrew

Extra info:

However I ran the following code using postgresql (I created a test db in psql) and it worked fine:

 $db = pg_connect("host=localhost dbname=scheduler user=minimoe password=''");

 Because I am fairly certain this question will be flagged as a duplicate, even though I haven't found an answer that will work for me, yet (although I have not googled the entirety of the vast web

I have tested several other similar questions answers in stack overflow to no avail, yet.

Some answers in other stack overflows that hasn't worked for me after trying them:

1. replacing mysql_connect with mysqli_connect (because I'm already using this)

2. replacing localhost with http://127.0.0.1/, this doesn't work for me either

3. replacing mysqli_connect with mysql() function

I hope I've provided enough info, comment if you need anything else to solve this. Thank you


来源: stackexchange

问:
find image src that :contains?
Morning all,

I have a list of images like so:

```<code><ul id="preload" style="display:none;">
<li><img src="afx4000z-navy-icon-1_thumb.jpg"/></li>
<li><img src="afx4000z-green-icon-1_thumb.jpg"/></li>
</ul>
</code>```

Using jQuery how find all image src's within ul#preload that contain a specific string eg."green"

something like...

```<code>var new_src = jQuery('#preload img').attr('src')*** that contains green ***;
</code>```

答:
You can use an attribute-contains selector ([attr*=value]), like this:

```<code>jQuery('#preload img[src*=green]')
</code>```

ContentLicense: CC BY-SA 2.5

Title: find image src that :contains?

Body:
Morning all,

I have a list of images like so:

Using jQuery how find all image src's within ul#preload that contain a specific string eg."green"

something like...

var new_src = jQuery('#preload img').attr('src')*** that contains green ***;

Body:
You can use an attribute-contains selector ([attr*=value]), like this:

jQuery('#preload img[src*=green]')


问:
How to change href url upon change of a dropdown?
This is my code

```<code><tbody>
<tr>
  <td>$id</td>
  <td>
    <div class='form-group'>
    <div class='col-sm-10'>
      <select id='form-control' class='form-control' onchange='leaveChange()'>
        <option value='$prices'>price</option>
        <option value='$Sale'>Sale</option>
        <option value='$payment'>payment</option>
      </select>";
      ?>
      <script>
      function leaveChange() {
        if (document.getElementById("form-control").value == ""){
          document.getElementById("enableordisable").innerHTML = "Enable";
          document.getElementById("status").innerHTML = "Disabled";
        }
        if(document.getElementById("form-control").value == 1){
          document.getElementById("enableordisable").innerHTML = "Disable";
          document.getElementById("status").innerHTML = "Enabled";
        }
      }
      </script>
  <?php echo "</div></td>
  <td><p id='status'>---</p></td>
  <td> <a id='enableordisable' type='addToTable' class='btn waves- effect waves-light btn-custom' href='function/enabledisable.php?stuff=$id&price=$price'>price</a></td>
</code>```

What I want to do is when a value is selected from the dropdown, I want this href URL in the button

```<code>href='function/enabledisable.php?stuff=$id&price=$price&item'
</code>```

to be updated so that item will point to the option chosen from the dropdown.

How can I do this?

Any help will be appreciated!

note: I cannot use the value inside of the options

答:
Here is what I think you wish...

It get the text of the selected option as the data to be added after &item=.

Notice that I fixed your HTML a little to make it work.

See comments in code.

// Pass the base href to JS
var baseHref = "function/enabledisable.php?stuff=$id&price=$price";

// On change event function
function leaveChange(el) {
  if (document.getElementById("form-control").value == ""){
    document.getElementById("enableordisable").innerHTML = "Enable";
    document.getElementById("status").innerHTML = "Disabled";
  }
  if(document.getElementById("form-control").value == 1){
    document.getElementById("enableordisable").innerHTML = "Disable";
    document.getElementById("status").innerHTML = "Enabled";
  }

  // Set the additional GET data to the URL
  var index = el.selectedIndex;
  var newHref = baseHref+"&item="+el.getElementsByTagName("option")[index].text
  console.log(newHref);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tbody>
    <tr>
      <td>$id</td>
      <td>
        <div class='form-group'>
          <div class='col-sm-10'>
            <select id='form-control' class='form-control' onchange='leaveChange(this)'>
              <option value='$prices'>price</option>
              <option value='$Sale'>Sale</option>
              <option value='$payment'>payment</option>
            </select>
          </div>
        </div>
      </td>
      <td><p id='status'>---</p></td>
      <td> price</td>
    </tr>
  </tbody>
</table></code>```

I assume that $id and $price are PHP variables.

ContentLicense: CC BY-SA 3.0

Body:
This is my code

  $id

      <select id='form-control' class='form-control' onchange='leaveChange()'>
        <option value='$prices'>price</option>
        <option value='$Sale'>Sale</option>
        <option value='$payment'>payment</option>
      </select>";
      ?>

  <?php echo "

---

   price

What I want to do is when a value is selected from the dropdown, I want this href URL in the button

href='function/enabledisable.php?stuff=$id&price=$price&item'

to be updated so that item will point to the option chosen from the dropdown.

How can I do this?

Any help will be appreciated!

note: I cannot use the value inside of the options

Body:
Here is what I think you wish...

It get the text of the selected option as the data to be added after &item=.

Notice that I fixed your HTML a little to make it work.

See comments in code.

// Pass the base href to JS
var baseHref = "function/enabledisable.php?stuff=$id&price=$price";

// On change event function
function leaveChange(el) {
  if (document.getElementById("form-control").value == ""){
    document.getElementById("enableordisable").innerHTML = "Enable";
    document.getElementById("status").innerHTML = "Disabled";
  }
  if(document.getElementById("form-control").value == 1){
    document.getElementById("enableordisable").innerHTML = "Disable";
    document.getElementById("status").innerHTML = "Enabled";
  }

  // Set the additional GET data to the URL
  var index = el.selectedIndex;
  var newHref = baseHref+"&item="+el.getElementsByTagName("option")[index].text
  console.log(newHref);
}

<table>
  <tbody>
    <tr>
      <td>$id</td>
      <td>
        <div class='form-group'>
          <div class='col-sm-10'>
            <select id='form-control' class='form-control' onchange='leaveChange(this)'>
              <option value='$prices'>price</option>
              <option value='$Sale'>Sale</option>
              <option value='$payment'>payment</option>
            </select>
          </div>
        </div>
      </td>
      <td><p id='status'>---</p></td>
      <td> <a id='enableordisable' type='addToTable' class='btn waves- effect waves-light btn-custom' href='function/enabledisable.php?stuff=$id&price=$price'>price</a></td>
    </tr>
  </tbody>
</table>

I assume that $id and $price are PHP variables.


问:
PHP set value of text box equal to form variable
I am simply trying to enter a word or number into the first text box and upon clicking submit have that word stored in a variable and then echoed into the second text box. This is the code I have but it is not working.</p>

```<code><html>
<head>
    <?php
        $one = "";
        if (isset($_POST["Submit"])){
            $one = $_POST["inputOne"];
        }
    ?>
</head>

<body>
    <form method="post" action="index.php">
        <input type="text" name="inputOne">
        <input type="submit" name="Submit">
        <input type="text" name="output" value="<?php echo $one; ?>">
    </form>
</body>
</html>
</code>```

答:
Have you tried removing index.php from the action, to just blank? At first it didn't work, but then I removed the index.php:

```<code><html>
<head>
    <?php
        $one = "";
        if (isset($_POST["Submit"])){
            $one = $_POST["inputOne"];
        }
    ?>
</head>
<body>
    <form method="post" action="">
        <input type="text" name="inputOne">
        <input type="submit" name="Submit">
        <input type="text" name="output" value="<?php echo $one; ?>">
    </form>
</body>
</html>
</code>```

Body:
I am simply trying to enter a word or number into the first text box and upon clicking submit have that word stored in a variable and then echoed into the second text box. This is the code I have but it is not working.

    <?php
        $one = "";
        if (isset($_POST["Submit"])){
            $one = $_POST["inputOne"];
        }
    ?>

    <form method="post" action="index.php">
        <input type="text" name="inputOne">
        <input type="submit" name="Submit">
        <input type="text" name="output" value="<?php echo $one; ?>">
    </form>

Body:
Have you tried removing index.php from the action, to just blank? At first it didn't work, but then I removed the index.php:

<html>
<head>
    <?php
        $one = "";
        if (isset($_POST["Submit"])){
            $one = $_POST["inputOne"];
        }
    ?>
</head>
<body>
    <form method="post" action="">
        <input type="text" name="inputOne">
        <input type="submit" name="Submit">
        <input type="text" name="output" value="<?php echo $one; ?>">
    </form>
</body>
</html>


问:
Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/spark/Logging
I'm new to Spark. I attempted to run a Spark app (.jar) on CDH 5.8.0-0 on Oracle VirtualBox 5.1.4r110228 which leveraged Spark Steaming to perform sentiment analysis on twitter. I have my twitter account created and all required (4) tokens were generated. I was blocked by the NoClassDefFoundError exception.

I've been googling around for a couple of days. The best advice I found so far was in the URL below but apparently my environment is still missing something.

http://javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html#ixzz4Ia99dsp0

What does it mean by a library showed up in Compile by was missing at RunTime? How can we fix this?

What is the library of Logging? I came across an article stating this Logging is subject to be deprecated. Besides that, I do see log4j in my environment.

In my CDH 5.8, I'm running these versions of software:
 Spark-2.0.0-bin-hadoop2.7 / spark-core_2.10-2.0.0
 jdk-8u101-linux-x64 / jre-bu101-linux-x64

I appended the detail of the exception at the end. Here is the procedure I performed to execute the app and some verification I did after hitting the exception:

Unzip twitter-streaming.zip  (the Spark app)

cd twitter-streaming

run ./sbt/sbt assembly

Update env.sh with your Twitter account

$ cat env.sh

```<code>export SPARK_HOME=/home/cloudera/spark-2.0.0-bin-hadoop2.7
export CONSUMER_KEY=<my_consumer_key>
export CONSUMER_SECRET=<my_consumer_secret>
export ACCESS_TOKEN=<my_twitterapp_access_token>
export ACCESS_TOKEN_SECRET=<my_twitterapp_access_token>
</code>```

The submit.sh script wrapped up the spark-submit command with required credential info in env.sh:

$ cat submit.sh

```<code>source ./env.sh
$SPARK_HOME/bin/spark-submit --class "TwitterStreamingApp" --master local[*] ./target/scala-2.10/twitter-streaming-assembly-1.0.jar $CONSUMER_KEY $CONSUMER_SECRET $ACCESS_TOKEN $ACCESS_TOKEN_SECRET
</code>```

The log of the assembly process:
[cloudera@quickstart twitter-streaming]$ ./sbt/sbt assembly

```<code>Launching sbt from sbt/sbt-launch-0.13.7.jar
[info] Loading project definition from /home/cloudera/workspace/twitter-streaming/project
[info] Set current project to twitter-streaming (in build file:/home/cloudera/workspace/twitter-streaming/)
[info] Including: twitter4j-stream-3.0.3.jar
[info] Including: twitter4j-core-3.0.3.jar
[info] Including: scala-library.jar
[info] Including: unused-1.0.0.jar
[info] Including: spark-streaming-twitter_2.10-1.4.1.jar
[info] Checking every *.class/*.jar file's SHA-1.
[info] Merging files...
[warn] Merging 'META-INF/LICENSE.txt' with strategy 'first'
[warn] Merging 'META-INF/MANIFEST.MF' with strategy 'discard'
[warn] Merging 'META-INF/maven/org.spark-project.spark/unused/pom.properties' with strategy 'first'
[warn] Merging 'META-INF/maven/org.spark-project.spark/unused/pom.xml' with strategy 'first'
[warn] Merging 'log4j.properties' with strategy 'discard'
[warn] Merging 'org/apache/spark/unused/UnusedStubClass.class' with strategy 'first'
[warn] Strategy 'discard' was applied to 2 files
[warn] Strategy 'first' was applied to 4 files
[info] SHA-1: 69146d6fdecc2a97e346d36fafc86c2819d5bd8f
[info] Packaging /home/cloudera/workspace/twitter-streaming/target/scala-2.10/twitter-streaming-assembly-1.0.jar ...
[info] Done packaging.
[success] Total time: 6 s, completed Aug 27, 2016 11:58:03 AM
</code>```

Not sure exactly what it means but everything looked good when I ran Hadoop NativeCheck:

$ hadoop checknative -a

```<code>16/08/27 13:27:22 INFO bzip2.Bzip2Factory: Successfully loaded & initialized native-bzip2 library system-native
16/08/27 13:27:22 INFO zlib.ZlibFactory: Successfully loaded & initialized native-zlib library
Native library checking:
hadoop:  true /usr/lib/hadoop/lib/native/libhadoop.so.1.0.0
zlib:    true /lib64/libz.so.1
snappy:  true /usr/lib/hadoop/lib/native/libsnappy.so.1
lz4:     true revision:10301
bzip2:   true /lib64/libbz2.so.1
openssl: true /usr/lib64/libcrypto.so
</code>```

Here is the console log of my exception:
$ ./submit.sh

```<code>Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
16/08/28 20:13:23 INFO SparkContext: Running Spark version 2.0.0
16/08/28 20:13:24 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
16/08/28 20:13:24 WARN Utils: Your hostname, quickstart.cloudera resolves to a loopback address: 127.0.0.1; using 10.0.2.15 instead (on interface eth0)
16/08/28 20:13:24 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
16/08/28 20:13:24 INFO SecurityManager: Changing view acls to: cloudera
16/08/28 20:13:24 INFO SecurityManager: Changing modify acls to: cloudera
16/08/28 20:13:24 INFO SecurityManager: Changing view acls groups to:
16/08/28 20:13:24 INFO SecurityManager: Changing modify acls groups to:
16/08/28 20:13:24 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(cloudera); groups with view permissions: Set(); users  with modify permissions: Set(cloudera); groups with modify permissions: Set()
16/08/28 20:13:25 INFO Utils: Successfully started service 'sparkDriver' on port 37550.
16/08/28 20:13:25 INFO SparkEnv: Registering MapOutputTracker
16/08/28 20:13:25 INFO SparkEnv: Registering BlockManagerMaster
16/08/28 20:13:25 INFO DiskBlockManager: Created local directory at /tmp/blockmgr-37a0492e-67e3-4ad5-ac38-40448c25d523
16/08/28 20:13:25 INFO MemoryStore: MemoryStore started with capacity 366.3 MB
16/08/28 20:13:25 INFO SparkEnv: Registering OutputCommitCoordinator
16/08/28 20:13:25 INFO Utils: Successfully started service 'SparkUI' on port 4040.
16/08/28 20:13:25 INFO SparkUI: Bound SparkUI to 0.0.0.0, and started at http://10.0.2.15:4040
16/08/28 20:13:25 INFO SparkContext: Added JAR file:/home/cloudera/workspace/twitter-streaming/target/scala-2.10/twitter-streaming-assembly-1.1.jar at spark://10.0.2.15:37550/jars/twitter-streaming-assembly-1.1.jar with timestamp 1472440405882
16/08/28 20:13:26 INFO Executor: Starting executor ID driver on host localhost
16/08/28 20:13:26 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 41264.
16/08/28 20:13:26 INFO NettyBlockTransferService: Server created on 10.0.2.15:41264
16/08/28 20:13:26 INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, 10.0.2.15, 41264)
16/08/28 20:13:26 INFO BlockManagerMasterEndpoint: Registering block manager 10.0.2.15:41264 with 366.3 MB RAM, BlockManagerId(driver, 10.0.2.15, 41264)
16/08/28 20:13:26 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, 10.0.2.15, 41264)
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/spark/Logging
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
    at java.security.AccessController.doPrivileged(Native Method)I
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.apache.spark.streaming.twitter.TwitterUtils$.createStream(TwitterUtils.scala:44)
    at TwitterStreamingApp$.main(TwitterStreamingApp.scala:42)
    at TwitterStreamingApp.main(TwitterStreamingApp.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:729)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:185)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:210)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:124)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.ClassNotFoundException: org.apache.spark.Logging
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 23 more
16/08/28 20:13:26 INFO SparkContext: Invoking stop() from shutdown hook
16/08/28 20:13:26 INFO SparkUI: Stopped Spark web UI at http://10.0.2.15:4040
16/08/28 20:13:26 INFO MapOutputTrackerMasterEndpoint: MapOutputTrackerMasterEndpoint stopped!
16/08/28 20:13:26 INFO MemoryStore: MemoryStore cleared
16/08/28 20:13:26 INFO BlockManager: BlockManager stopped
16/08/28 20:13:26 INFO BlockManagerMaster: BlockManagerMaster stopped
16/08/28 20:13:26 INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped!
16/08/28 20:13:26 INFO SparkContext: Successfully stopped SparkContext
16/08/28 20:13:26 INFO ShutdownHookManager: Shutdown hook called
16/08/28 20:13:26 INFO ShutdownHookManager: Deleting directory /tmp/spark-5e29c3b2-74c2-4d89-970f-5be89d176b26
</code>```

I understand my post was lengthy. Your advice or insights are highly appreciated!!

-jsung8

答:
Use: spark-core_2.11-1.5.2.jar

I had the same problem described by @jsung8 and tried to find the .jar suggested by @youngstephen but could not. However linking in spark-core_2.11-1.5.2.jar instead of spark-core_2.11-1.5.2.logging.jar resolved the exception in the way @youngstephen suggested.

Body:
I'm new to Spark. I attempted to run a Spark app (.jar) on CDH 5.8.0-0 on Oracle VirtualBox 5.1.4r110228 which leveraged Spark Steaming to perform sentiment analysis on twitter. I have my twitter account created and all required (4) tokens were generated. I was blocked by the NoClassDefFoundError exception.

I've been googling around for a couple of days. The best advice I found so far was in the URL below but apparently my environment is still missing something.

http://javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html#ixzz4Ia99dsp0

What does it mean by a library showed up in Compile by was missing at RunTime? How can we fix this?

What is the library of Logging? I came across an article stating this Logging is subject to be deprecated. Besides that, I do see log4j in my environment.

In my CDH 5.8, I'm running these versions of software:
 Spark-2.0.0-bin-hadoop2.7 / spark-core_2.10-2.0.0
 jdk-8u101-linux-x64 / jre-bu101-linux-x64

I appended the detail of the exception at the end. Here is the procedure I performed to execute the app and some verification I did after hitting the exception:

Unzip twitter-streaming.zip  (the Spark app)

cd twitter-streaming

run ./sbt/sbt assembly

Update env.sh with your Twitter account

$ cat env.sh

export SPARK_HOME=/home/cloudera/spark-2.0.0-bin-hadoop2.7
export CONSUMER_KEY=<my_consumer_key>
export CONSUMER_SECRET=<my_consumer_secret>
export ACCESS_TOKEN=<my_twitterapp_access_token>
export ACCESS_TOKEN_SECRET=<my_twitterapp_access_token>

The submit.sh script wrapped up the spark-submit command with required credential info in env.sh:

$ cat submit.sh

source ./env.sh
$SPARK_HOME/bin/spark-submit --class "TwitterStreamingApp" --master local[*] ./target/scala-2.10/twitter-streaming-assembly-1.0.jar $CONSUMER_KEY $CONSUMER_SECRET $ACCESS_TOKEN $ACCESS_TOKEN_SECRET

The log of the assembly process:
[cloudera@quickstart twitter-streaming]$ ./sbt/sbt assembly

Launching sbt from sbt/sbt-launch-0.13.7.jar
[info] Loading project definition from /home/cloudera/workspace/twitter-streaming/project
[info] Set current project to twitter-streaming (in build file:/home/cloudera/workspace/twitter-streaming/)
[info] Including: twitter4j-stream-3.0.3.jar
[info] Including: twitter4j-core-3.0.3.jar
[info] Including: scala-library.jar
[info] Including: unused-1.0.0.jar
[info] Including: spark-streaming-twitter_2.10-1.4.1.jar
[info] Checking every *.class/*.jar file's SHA-1.
[info] Merging files...
[warn] Merging 'META-INF/LICENSE.txt' with strategy 'first'
[warn] Merging 'META-INF/MANIFEST.MF' with strategy 'discard'
[warn] Merging 'META-INF/maven/org.spark-project.spark/unused/pom.properties' with strategy 'first'
[warn] Merging 'META-INF/maven/org.spark-project.spark/unused/pom.xml' with strategy 'first'
[warn] Merging 'log4j.properties' with strategy 'discard'
[warn] Merging 'org/apache/spark/unused/UnusedStubClass.class' with strategy 'first'
[warn] Strategy 'discard' was applied to 2 files
[warn] Strategy 'first' was applied to 4 files
[info] SHA-1: 69146d6fdecc2a97e346d36fafc86c2819d5bd8f
[info] Packaging /home/cloudera/workspace/twitter-streaming/target/scala-2.10/twitter-streaming-assembly-1.0.jar ...
[info] Done packaging.
[success] Total time: 6 s, completed Aug 27, 2016 11:58:03 AM

Not sure exactly what it means but everything looked good when I ran Hadoop NativeCheck:

$ hadoop checknative -a

16/08/27 13:27:22 INFO bzip2.Bzip2Factory: Successfully loaded & initialized native-bzip2 library system-native
16/08/27 13:27:22 INFO zlib.ZlibFactory: Successfully loaded & initialized native-zlib library
Native library checking:
hadoop:  true /usr/lib/hadoop/lib/native/libhadoop.so.1.0.0
zlib:    true /lib64/libz.so.1
snappy:  true /usr/lib/hadoop/lib/native/libsnappy.so.1
lz4:     true revision:10301
bzip2:   true /lib64/libbz2.so.1
openssl: true /usr/lib64/libcrypto.so

Here is the console log of my exception:
$ ./submit.sh

Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
16/08/28 20:13:23 INFO SparkContext: Running Spark version 2.0.0
16/08/28 20:13:24 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
16/08/28 20:13:24 WARN Utils: Your hostname, quickstart.cloudera resolves to a loopback address: 127.0.0.1; using 10.0.2.15 instead (on interface eth0)
16/08/28 20:13:24 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
16/08/28 20:13:24 INFO SecurityManager: Changing view acls to: cloudera
16/08/28 20:13:24 INFO SecurityManager: Changing modify acls to: cloudera
16/08/28 20:13:24 INFO SecurityManager: Changing view acls groups to:
16/08/28 20:13:24 INFO SecurityManager: Changing modify acls groups to:
16/08/28 20:13:24 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(cloudera); groups with view permissions: Set(); users  with modify permissions: Set(cloudera); groups with modify permissions: Set()
16/08/28 20:13:25 INFO Utils: Successfully started service 'sparkDriver' on port 37550.
16/08/28 20:13:25 INFO SparkEnv: Registering MapOutputTracker
16/08/28 20:13:25 INFO SparkEnv: Registering BlockManagerMaster
16/08/28 20:13:25 INFO DiskBlockManager: Created local directory at /tmp/blockmgr-37a0492e-67e3-4ad5-ac38-40448c25d523
16/08/28 20:13:25 INFO MemoryStore: MemoryStore started with capacity 366.3 MB
16/08/28 20:13:25 INFO SparkEnv: Registering OutputCommitCoordinator
16/08/28 20:13:25 INFO Utils: Successfully started service 'SparkUI' on port 4040.
16/08/28 20:13:25 INFO SparkUI: Bound SparkUI to 0.0.0.0, and started at http://10.0.2.15:4040
16/08/28 20:13:25 INFO SparkContext: Added JAR file:/home/cloudera/workspace/twitter-streaming/target/scala-2.10/twitter-streaming-assembly-1.1.jar at spark://10.0.2.15:37550/jars/twitter-streaming-assembly-1.1.jar with timestamp 1472440405882
16/08/28 20:13:26 INFO Executor: Starting executor ID driver on host localhost
16/08/28 20:13:26 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 41264.
16/08/28 20:13:26 INFO NettyBlockTransferService: Server created on 10.0.2.15:41264
16/08/28 20:13:26 INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, 10.0.2.15, 41264)
16/08/28 20:13:26 INFO BlockManagerMasterEndpoint: Registering block manager 10.0.2.15:41264 with 366.3 MB RAM, BlockManagerId(driver, 10.0.2.15, 41264)
16/08/28 20:13:26 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, 10.0.2.15, 41264)
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/spark/Logging
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
    at java.security.AccessController.doPrivileged(Native Method)I
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.apache.spark.streaming.twitter.TwitterUtils$.createStream(TwitterUtils.scala:44)
    at TwitterStreamingApp$.main(TwitterStreamingApp.scala:42)
    at TwitterStreamingApp.main(TwitterStreamingApp.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:729)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:185)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:210)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:124)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.ClassNotFoundException: org.apache.spark.Logging
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 23 more
16/08/28 20:13:26 INFO SparkContext: Invoking stop() from shutdown hook
16/08/28 20:13:26 INFO SparkUI: Stopped Spark web UI at http://10.0.2.15:4040
16/08/28 20:13:26 INFO MapOutputTrackerMasterEndpoint: MapOutputTrackerMasterEndpoint stopped!
16/08/28 20:13:26 INFO MemoryStore: MemoryStore cleared
16/08/28 20:13:26 INFO BlockManager: BlockManager stopped
16/08/28 20:13:26 INFO BlockManagerMaster: BlockManagerMaster stopped
16/08/28 20:13:26 INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped!
16/08/28 20:13:26 INFO SparkContext: Successfully stopped SparkContext
16/08/28 20:13:26 INFO ShutdownHookManager: Shutdown hook called
16/08/28 20:13:26 INFO ShutdownHookManager: Deleting directory /tmp/spark-5e29c3b2-74c2-4d89-970f-5be89d176b26

I understand my post was lengthy. Your advice or insights are highly appreciated!!

-jsung8


问:
Thread Stack Size Not Matching Native Memory Tracking Thread Stack Size
I'm currently doing some testing of memory settings on a Maven Tomcat7 plugin.  I'm setting the Thread Stack Size to 128k with the following:

```<code>set MAVEN_OPTS=-XX:NativeMemoryTracking=summary -Xss128k
</code>```

After that, I run jcmd with Native Memory Tracking Option  I get the following output.

```<code>C:\Users\gdrocell>jcmd 8672 VM.native_memory summary
8672:

Native Memory Tracking:

Total: reserved=9995213KB, committed=1283517KB
-                 Java Heap (reserved=8282112KB, committed=868864KB)
                            (mmap: reserved=8282112KB, committed=868864KB)

-                     Class (reserved=1103777KB, committed=59857KB)
                            (classes #9079)
                            (malloc=10145KB #11226)
                            (mmap: reserved=1093632KB, committed=49712KB)

-                    Thread (reserved=15844KB, committed=15844KB)
                            (thread #25)
                            (stack: reserved=15616KB, committed=15616KB)
                            (malloc=72KB #132)
                            (arena=156KB #48)

-                      Code (reserved=253665KB, committed=23761KB)
                            (malloc=4065KB #6562)
                            (mmap: reserved=249600KB, committed=19696KB)

-                        GC (reserved=313042KB, committed=288418KB)
                            (malloc=10386KB #203)
                            (mmap: reserved=302656KB, committed=278032KB)

-                  Compiler (reserved=152KB, committed=152KB)
                            (malloc=21KB #204)
                            (arena=131KB #3)

-                  Internal (reserved=10653KB, committed=10653KB)
                            (malloc=10589KB #10938)
                            (mmap: reserved=64KB, committed=64KB)

-                    Symbol (reserved=13705KB, committed=13705KB)
                            (malloc=10756KB #102196)
                            (arena=2949KB #1)

-    Native Memory Tracking (reserved=2065KB, committed=2065KB)
                            (malloc=7KB #85)
                            (tracking overhead=2058KB)

-               Arena Chunk (reserved=197KB, committed=197KB)
                            (malloc=197KB)
</code>```

As you can see, the thread stack size seems to be 15.25mb.  Does anyone know why this is?

答:
According to this blog (https://blogs.oracle.com/saas-fusion-app-performance/how-to-set-stack-size-to-overcome-javalangstackoverflowerror)

If it is not possible to change the stack requirements of the
  application, you can change the thread stack size by using the -Xss
  command-line option.

This is an stack size per thread. The figure you mention will vary with the number of threads.

EDIT

That is a lot of threads around 120. I would use -XX:NativeMemoryTracking=detail. To see if the info makes more sense

Body:
I'm currently doing some testing of memory settings on a Maven Tomcat7 plugin.  I'm setting the Thread Stack Size to 128k with the following:

set MAVEN_OPTS=-XX:NativeMemoryTracking=summary -Xss128k

After that, I run jcmd with Native Memory Tracking Option  I get the following output.

C:\Users\gdrocell>jcmd 8672 VM.native_memory summary
8672:

Native Memory Tracking:

Total: reserved=9995213KB, committed=1283517KB
-                 Java Heap (reserved=8282112KB, committed=868864KB)
                            (mmap: reserved=8282112KB, committed=868864KB)

-                     Class (reserved=1103777KB, committed=59857KB)
                            (classes #9079)
                            (malloc=10145KB #11226)
                            (mmap: reserved=1093632KB, committed=49712KB)

-                    Thread (reserved=15844KB, committed=15844KB)
                            (thread #25)
                            (stack: reserved=15616KB, committed=15616KB)
                            (malloc=72KB #132)
                            (arena=156KB #48)

-                      Code (reserved=253665KB, committed=23761KB)
                            (malloc=4065KB #6562)
                            (mmap: reserved=249600KB, committed=19696KB)

-                        GC (reserved=313042KB, committed=288418KB)
                            (malloc=10386KB #203)
                            (mmap: reserved=302656KB, committed=278032KB)

-                  Compiler (reserved=152KB, committed=152KB)
                            (malloc=21KB #204)
                            (arena=131KB #3)

-                  Internal (reserved=10653KB, committed=10653KB)
                            (malloc=10589KB #10938)
                            (mmap: reserved=64KB, committed=64KB)

-                    Symbol (reserved=13705KB, committed=13705KB)
                            (malloc=10756KB #102196)
                            (arena=2949KB #1)

-    Native Memory Tracking (reserved=2065KB, committed=2065KB)
                            (malloc=7KB #85)
                            (tracking overhead=2058KB)

-               Arena Chunk (reserved=197KB, committed=197KB)
                            (malloc=197KB)

As you can see, the thread stack size seems to be 15.25mb.  Does anyone know why this is?


问:
Is it possible to use Vue components in .vue formats vs commonJS formats interchangeably?
This is commonJS format

```<code>Vue.Component('custom-component',{
       template : '<p>Some template</p>',
       data : {}
       methods : {}
});
</code>```

This is .vue format

```<code><template>
    <p>Some template</p>
</template>

<script>
    export default {
        data() {
           return {};
        },
        methods : {}
    }

</script>
<style>
</style>
</code>```

My question is, can you have a project with some components written in commonJS format and some components written in .vue format? If so, how do you import one kind of component in the other?

答:
Yes, you can.

.vue files will be packed into common js and common js format will be left as is by webpack.

Body:
This is commonJS format

Vue.Component('custom-component',{
       template : '
Some template
',
       data : {}
       methods : {}
});

This is .vue format

<template>

Some template

</template>

My question is, can you have a project with some components written in commonJS format and some components written in .vue format? If so, how do you import one kind of component in the other?


问:
How to select t.test() type in R?
In t.test(), there's parameter var.equal, which means we need to check variance homogeneity before t.test.

Which one should be used?

答:
You do not need to do homogeneity of variance (HOV) test before doing the t-test. By default, R does Welch's test which accounts for absence of HOV. The papers below come to this conclusion.

Welch's test is more powerful than the regular t-test when there is no HOV, and almost as powerful under HOV. Additionally, the formal tests for HOV can be very problematic: low power with small sample sizes (n), too powerful with large n, no effect sizes, problematic under non-normality, ... Finally, Zimmerman (2004) showed that when you choose which test to conduct based on the result of the most commonly performed HOV test (Levene's test), the result from your subsequent analysis is unreliable.

So simply run the t-test in R without worrying about HOV. R by default does Welch's test which adjusts for lacking HOV.

Zimmerman, D. W. (2004). A note on preliminary tests of equality of variances. British Journal of Mathematical and Statistical Psychology, 57(1), 173–181. https://doi.org/10.1348/000711004849222

Delacre, M., Lakens, D., & Leys, C. (2017). Why Psychologists Should by Default Use Welch’s t-test Instead of Student’s t-test. International Review of Social Psychology, 30(1), 92–101. https://doi.org/10.5334/irsp.82

Title: How to select t.test() type in R?


问:
Where did Python borrow the concept of descriptor from?
Where did Python borrow the concept of descriptor from?

Did Python borrow it from some other programming languages? In C#, I only see property, but not descriptor.

Will I  benefit on not just descriptors but other concepts by learning that other language first, instead of learning Python directly?

答:
From Python itself. To quote Guido Van Rossum 1, descriptors were introduced in Python 2.2 as a generalization of the concept of bound methods, which was central to the implementation of classic classes in previous versions.

There are two common approaches for a language to support both functional and object oriented programming. Every callable is a method and functions are just methods of a hidden class, which is the approach adopted by Ruby; or every callable is a function and object methods are just functions with an implicit or explicit parameter that receives the object the method was called from, which is the approach adopted by Python.

In Python 2.1 and before, when an instance attribute lookup fails at the instance dictionary, the interpreter looks at the class and the base classes, recursively. If the attribute is found at a class dictionary and it's a function, the interpreter wraps it in a callable object that inserts the instance itself as the first parameter when it gets called. The wrapper binds the instance to the function, hence the name bound methods.

Descriptors are a generalization of that behavior. In Python 2.2 and later, the interpreter performs the attribute lookup in the same way, and when the attribute is found at a class dictionary and it has a __get__ method, this method gets called with the class and instance as arguments, and whatever is returned is used as the result of the attribute search. Instead of being a special object, the bound method wrapper is now just an ordinary object implementing a __get__ method, allowing us to customize it and implement special methods like classmethod and staticmethod. On top of that, we have the complementary methods __set__ and __delete__, generalizing the same behavior for assignment and deletion, allowing us to implement things like property and managed attributes of all kinds.


问:
how to read a text file stored in mobile using j2me midp2.0?
HI ALL,

I am working in j2me midp2.0 environment.My application wants to read a text file which is stored in mobile device.How to read the text file programatically using j2me.Please give me idea to get this.What is the root folder in mobile to place the text file for accessible from j2me Application environment.

Saravanan.P

答:
You need javax.microedition.io.file.FileConnection

Get root folder:

```<code>  try {
        Enumeration roots = FileSystemRegistry.listRoots();
        while(roots.hasMoreElements()) {
            System.out.println("Root: file:///"+(String)roots.nextElement());
        }
    } catch(Exception e) {
    }
</code>```

write to file

```<code>        public void write(String root) {
        FileConnection fc = null;
        String fName = "test.txt";
        try {
            fc = (FileConnection) Connector.open(root + fName, Connector.READ_WRITE);
            if(!fc.exists()) {
                fc.create();
            }

            DataOutputStream dos = fc.openDataOutputStream();
            dos.writeUTF("test-test");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fc.close();
            } catch (IOException e) { }
        }
}
</code>```

read from file

```<code>public void read(String root) {
        FileConnection fc = null;
        try {
             fc= (FileConnection) Connector.open(root + "test.txt", Connector.READ);
             DataInputStream dis = fc.openDataInputStream();
             String data = dis.readUTF();
             System.out.println(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fc.close();
            } catch (IOException e) { }
    }
    }
</code>```

Body:
You need javax.microedition.io.file.FileConnection

Get root folder:

  try {
        Enumeration roots = FileSystemRegistry.listRoots();
        while(roots.hasMoreElements()) {
            System.out.println("Root: file:///"+(String)roots.nextElement());
        }
    } catch(Exception e) {
    }

write to file

        public void write(String root) {
        FileConnection fc = null;
        String fName = "test.txt";
        try {
            fc = (FileConnection) Connector.open(root + fName, Connector.READ_WRITE);
            if(!fc.exists()) {
                fc.create();
            }

            DataOutputStream dos = fc.openDataOutputStream();
            dos.writeUTF("test-test");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fc.close();
            } catch (IOException e) { }
        }
}

read from file

public void read(String root) {
        FileConnection fc = null;
        try {
             fc= (FileConnection) Connector.open(root + "test.txt", Connector.READ);
             DataInputStream dis = fc.openDataInputStream();
             String data = dis.readUTF();
             System.out.println(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fc.close();
            } catch (IOException e) { }
    }
    }


问:
Node js (Express js) Mysql read ECONNRESET error
```<code>var express = require('express');
var mysql = require('mysql');
var connection = module.exports = mysql.createConnection({
  host: 'myhost.com',
  port:'3307',
  user: 'username',
  password: 'password',
  database: 'mydatabase'
});

connection.connect(function(err) {
  if (err){
    throw err;
  }
  else
  console.log('You are now connected...');
});
</code>```

<p>Sometimes when I try to connect to the database I get read ECONNRESET error. Please help. I tried many things, but nothing seems to work. </p>

答:
You can find the solution in this answer: https://stackoverflow.com/a/22906189/1790397

MySQL does indeed prune idle connections. There's a MySQL variable "wait_timeout" that sets the number of second before timeout and the default is 8 hours. We can set the default to be much larger than that. Use show variables like 'wait_timeout'; to view your timeout setting and set wait_timeout=28800; to change it.

According to this issue, node-mysql doesn't prune pool connections after these sorts of disconnections. The module developers recommended using a heartbeat to keep the connection alive such as calling SELECT 1; on an interval. They also recommended using the node-pool module and its idleTimeoutMillis option to automatically prune idle connections.

Body:
var express = require('express');
var mysql = require('mysql');
var connection = module.exports = mysql.createConnection({
  host: 'myhost.com',
  port:'3307',
  user: 'username',
  password: 'password',
  database: 'mydatabase'
});

connection.connect(function(err) {
  if (err){
    throw err;
  }
  else
  console.log('You are now connected...');
});

Sometimes when I try to connect to the database I get read ECONNRESET error. Please help. I tried many things, but nothing seems to work.


问:
return stops a function and returns a value. But why use it over a variable?
return stops a function and returns a value.  For example this simple function returns 2 words.

```<code>function returnValue(name) {
    return "Hello " + name;
}

document.getElementById("box-1").innerHTML = returnValue("Freddy");
</code>```

However I can accomplish the same thing with a variable.  For example this function creates the same output without return.

```<code>var testVar;

function returnValue(name) {
    testVar = "Hello " + name;
}

returnValue("Freddy");
document.getElementById("box-1").innerHTML = testVar;
</code>```

As a noob, at least on the surface I don't see a significant benefit to return compared to a variable.  Am I missing something that is uniquely good about return?  Or alternately do most people simply use variables?

答:
The return statement can be used to accomplish many different things, here are a few examples...

Example 1:

In this example we have a very large loop with a condition, if we don't use the return statement in our condition it will continue to loop through every other number ultimately slowing down our code.

```<code>function aLargeLoop() {
  for (i = 0; i < 600; i++) {
    alert(i)
    if (i == 10) {
      return i;
    }
  }
}

aLargeLoop()
</code>```

Example 2:

Instead of doing this which wastes an unnecessary amount of time to type...

```<code>var testVar;

function returnValue(name) {
  testVar = "Hello " + name;
}
returnValue("Freddy")
alert(testVar)
</code>```

We can accomplish the same thing by just doing...

```<code>function sayhello(name) {
  return "Hello " + name;
}

var greeting = sayhello("John")
alert(greeting)
</code>```

Example 3:

If we try to prototype a method like so...

```<code>var x;
Array.prototype.methodExample = function() {
    x = this;
  }
  [1, 2, 3, 4].methodExample()
alert(x)
</code>```

it isn't going to work, we need to return it like so...

```<code>Array.prototype.methodExample = function() {
    return this;
}

alert([1,2,3,4].methodExample())
</code>```

I hope this helps anyone else with a similar query.

Body:
return stops a function and returns a value.  For example this simple function returns 2 words.

function returnValue(name) {
    return "Hello " + name;
}

document.getElementById("box-1").innerHTML = returnValue("Freddy");

However I can accomplish the same thing with a variable.  For example this function creates the same output without return.

var testVar;

function returnValue(name) {
    testVar = "Hello " + name;
}

returnValue("Freddy");
document.getElementById("box-1").innerHTML = testVar;

As a noob, at least on the surface I don't see a significant benefit to return compared to a variable.  Am I missing something that is uniquely good about return?  Or alternately do most people simply use variables?

Body:
The return statement can be used to accomplish many different things, here are a few examples...

Example 1:

In this example we have a very large loop with a condition, if we don't use the return statement in our condition it will continue to loop through every other number ultimately slowing down our code.

function aLargeLoop() {
  for (i = 0; i < 600; i++) {
    alert(i)
    if (i == 10) {
      return i;
    }
  }
}

aLargeLoop()

Example 2:

Instead of doing this which wastes an unnecessary amount of time to type...

var testVar;

function returnValue(name) {
  testVar = "Hello " + name;
}
returnValue("Freddy")
alert(testVar)

We can accomplish the same thing by just doing...

function sayhello(name) {
  return "Hello " + name;
}

var greeting = sayhello("John")
alert(greeting)

Example 3:

If we try to prototype a method like so...

var x;
Array.prototype.methodExample = function() {
    x = this;
  }
  [1, 2, 3, 4].methodExample()
alert(x)

it isn't going to work, we need to return it like so...

Array.prototype.methodExample = function() {
    return this;
}

alert([1,2,3,4].methodExample())

I hope this helps anyone else with a similar query.


问:
How to push child arrays into items in an array to local React state, via a Firebase snapshot
The state in this little app is set by looping over the items in a Firebase snapshot (array). I can't figure out how to output a nested (child) array in this way. My gut says it's a regular JS function that I'm not thinking of like map and that I'm confused based on learning the syntax for state. I'd love some help in figuring out how to push the sessions arrays into state with each exercise.

Screenshot of the data structure in Firebase: [http://i.imgur.com/FlS054T.png]

```<code>componentDidMount () {
const exercisesRef = firebase.database().ref('exercises')
exercisesRef.on('value', snapshot => {
  let exercises = snapshot.val()
  let newState = []
  for (let exercise in exercises) {
    newState.push({
      id: exercise,
      title: exercises[exercise].title,
      setting: exercises[exercise].setting,
      settingType: exercises[exercise].settingType,
      reps: exercises[exercise].reps,
      raiseAfter: exercises[exercise].raiseAfter,
      raiseBy: exercises[exercise].raiseBy
    })
  }
  this.setState({
    exercises: newState
  })
})
</code>```

}

Thank you in advance for any help you can give!

答:
In case anyone else runs into this issue, @Claysmile was right. Pushing the whole object into state and it seems that using Lodash's map function is the best for outputting data.

```<code>exercisesRef.on("value", snapshot => {
  this.setState({ exercises: snapshot.val() });
});
</code>```

For outputting the data, in this specific example I'm using:

```<code><ul>
  {sessions &&
    map(sessions, (session, key) =>
      <li key={key}>
        <p>
          {session.completed}
        </p>
        <p>
          {session.completedDate}
        </p>
        <p>
          {session.setting}
        </p>
      </li>
    )}
  </ul>
</code>```

For my fellow front-enders, the
s are just placeholders, don't worry. :)

Body:
The state in this little app is set by looping over the items in a Firebase snapshot (array). I can't figure out how to output a nested (child) array in this way. My gut says it's a regular JS function that I'm not thinking of like map and that I'm confused based on learning the syntax for state. I'd love some help in figuring out how to push the sessions arrays into state with each exercise.

Screenshot of the data structure in Firebase: [http://i.imgur.com/FlS054T.png]

componentDidMount () {
const exercisesRef = firebase.database().ref('exercises')
exercisesRef.on('value', snapshot => {
  let exercises = snapshot.val()
  let newState = []
  for (let exercise in exercises) {
    newState.push({
      id: exercise,
      title: exercises[exercise].title,
      setting: exercises[exercise].setting,
      settingType: exercises[exercise].settingType,
      reps: exercises[exercise].reps,
      raiseAfter: exercises[exercise].raiseAfter,
      raiseBy: exercises[exercise].raiseBy
    })
  }
  this.setState({
    exercises: newState
  })
})

}

Thank you in advance for any help you can give!

Body:
In case anyone else runs into this issue, @Claysmile was right. Pushing the whole object into state and it seems that using Lodash's map function is the best for outputting data.

exercisesRef.on("value", snapshot => {
  this.setState({ exercises: snapshot.val() });
});

For outputting the data, in this specific example I'm using:

<ul>
  {sessions &&
    map(sessions, (session, key) =>
      <li key={key}>
        <p>
          {session.completed}
        </p>
        <p>
          {session.completedDate}
        </p>
        <p>
          {session.setting}
        </p>
      </li>
    )}
  </ul>

For my fellow front-enders, the <p>s are just placeholders, don't worry. :)


问:
Self-Sizing Table View Cell in Xcode 9
I have a UITableViewController where the cell's self sized correctly using Xcode 8 and Swift 3.  Now that I'm using Xcode 9 and Swift 4, they aren't expanding and are just using the default height of 44.

(I have about a sentence or two in each UITableViewCell)

I was using this before:

```<code>// MARK: - Table view delegate

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
</code>```

... but was able to comment it out because per Updating Your App for iOS 11 said that the default would be self-sizing now:

I've tried playing around with changing the deployment target to iOS 11, playing around in Storyboard (but I'm using a Table View Cell style Basic so there is not much AutoLayout to be done), and I can't figure out what is going on.

I have the UILabel title set to 0 Lines, and have Line Break Word Wrap, but still not getting anywhere close to getting the cell to expand based on the text content inside of it in Xcode 9.  Any ideas?

Thanks!

Edit:

Here's the options (that I don't have) for pinning since it is a Basic cell:

答:
In addition to

```<code>tableView.estimatedRowHeight = UITableViewAutomaticDimension
tableView.rowHeight = UITableViewAutomaticDimension
</code>```

you should set a height constraint for the contentView of the tabeleViewCell.

```<code>class CustomTableViewCell: UITableViewCell {
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        let height: CGFloat = 200
        heightAnchor.constraint(equalToConstant: height).isActive = true
    }
}
</code>```

Title: Self-Sizing Table View Cell in Xcode 9

Body:
I have a UITableViewController where the cell's self sized correctly using Xcode 8 and Swift 3.  Now that I'm using Xcode 9 and Swift 4, they aren't expanding and are just using the default height of 44.

(I have about a sentence or two in each UITableViewCell)

I was using this before:

// MARK: - Table view delegate

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

... but was able to comment it out because per Updating Your App for iOS 11 said that the default would be self-sizing now:

I've tried playing around with changing the deployment target to iOS 11, playing around in Storyboard (but I'm using a Table View Cell style Basic so there is not much AutoLayout to be done), and I can't figure out what is going on.

I have the UILabel title set to 0 Lines, and have Line Break Word Wrap, but still not getting anywhere close to getting the cell to expand based on the text content inside of it in Xcode 9.  Any ideas?

Thanks!

Edit:

Here's the options (that I don't have) for pinning since it is a Basic cell:

Body:
In addition to

tableView.estimatedRowHeight = UITableViewAutomaticDimension
tableView.rowHeight = UITableViewAutomaticDimension

you should set a height constraint for the contentView of the tabeleViewCell.

class CustomTableViewCell: UITableViewCell {
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        let height: CGFloat = 200
        heightAnchor.constraint(equalToConstant: height).isActive = true
    }
}


答:
Your variable is a global variable so it can be accessed or set from anywhere in your code. In a web browser there are many global variables which are objects with functions. These are good mainly for storing data.

A function on the other hand can be used to execute a block of code or return an object.

For example, you can define a function to extract text from a string. This function will parse the R(red)G(green)B(blue) parts from a string representing a color in either Hexadecimal, RGB or RGBA format.

```<code>function getRGB(color) {
                var Rhex, Ghex, Bhex;
                var R8bit = null;
                var G8bit = null;
                var B8bit = null;
                var IsHex = false;
                if (color.match(/rgba?\((\d{1,3}),\s(\d{1,3}),\s(\d{1,3})/)) {
                    Rhex = RegExp.$1;
                    Ghex = RegExp.$2;
                    Bhex = RegExp.$3;
                }
                else if (color.match(/^\s*#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\s*$/i)) {
                    Rhex = RegExp.$1;
                    Ghex = RegExp.$2;
                    Bhex = RegExp.$3;
                    IsHex = true;
                }
                else if (color.match(/^\s*#?([0-9a-f])([0-9a-f])([0-9a-f])\s*$/i)) {
                    Rhex = RegExp.$1 + RegExp.$1;
                    Ghex = RegExp.$2 + RegExp.$2;
                    Bhex = RegExp.$3 + RegExp.$3;
                    IsHex = true;
                }
                else {
                    return (NaN);
                }
                if (IsHex) {
                    R8bit = parseInt(Rhex, 16);
                    G8bit = parseInt(Ghex, 16);
                    B8bit = parseInt(Bhex, 16);
                } else {
                    R8bit = parseInt(Rhex);
                    G8bit = parseInt(Ghex);
                    B8bit = parseInt(Bhex);
                }
                return [R8bit, G8bit, B8bit];
            }
</code>```

Now I can use that function from another function, for example to darken or lighten the color by increasing or decreasing the RGB components of the color:

```<code>function darken(color)  {
    var rgb = getRGB(Color);
    return [Math.Max(rgb[0]-1,0), Math.Max(rgb[1]-1,0), Math.Max(rgb[2]-1,0)];
}
</code>```

Or to lighten a color:

```<code>function lighten(color)  {
    var rgb = getRGB(Color);
    return [Math.Min(rgb[0]+1,255), Math.Min(rgb[1]+1,255), Math.Min(rgb[2]+255,0)];
}
</code>```

I can also declare variables and functions inside of a function:

```<code>function myColorHelper(e)
{
    var el = $(e);
    var myColor= function() { return el.css("color"); };
    var myrgb = function() { return getRGB(mycolor);};
    var makeDarker = function() {
       var darker = darken(myrgb());
       el.css("color", "rgb(" + darker[0] + ", " + darker[1] + ", " + darker[2]);
      };
    var makeLighter = function() {
       var lighter = lighten(myrgb());
       el.css("color", "rgb(" + lighten[0] + ", " + lighten[1] + ", " + lighten[2]);
      };

}
</code>```

Plugins and frameworks are full of functions which allow us to use functionality in our code. For example, I could use jQuery with these functions to darken or lighten the color of an element on a webpage.

```<code>var helper = myColorHelper($('#myElement'));
helper.makeLighter();
helper.makeDarker();
</code>```

Title: return stops a function and returns a value. But why use it over a variable?

Body:
Your variable is a global variable so it can be accessed or set from anywhere in your code. In a web browser there are many global variables which are objects with functions. These are good mainly for storing data.

A function on the other hand can be used to execute a block of code or return an object.

For example, you can define a function to extract text from a string. This function will parse the R(red)G(green)B(blue) parts from a string representing a color in either Hexadecimal, RGB or RGBA format.

function getRGB(color) {
                var Rhex, Ghex, Bhex;
                var R8bit = null;
                var G8bit = null;
                var B8bit = null;
                var IsHex = false;
                if (color.match(/rgba?\((\d{1,3}),\s(\d{1,3}),\s(\d{1,3})/)) {
                    Rhex = RegExp.$1;
                    Ghex = RegExp.$2;
                    Bhex = RegExp.$3;
                }
                else if (color.match(/^\s*#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\s*$/i)) {
                    Rhex = RegExp.$1;
                    Ghex = RegExp.$2;
                    Bhex = RegExp.$3;
                    IsHex = true;
                }
                else if (color.match(/^\s*#?([0-9a-f])([0-9a-f])([0-9a-f])\s*$/i)) {
                    Rhex = RegExp.$1 + RegExp.$1;
                    Ghex = RegExp.$2 + RegExp.$2;
                    Bhex = RegExp.$3 + RegExp.$3;
                    IsHex = true;
                }
                else {
                    return (NaN);
                }
                if (IsHex) {
                    R8bit = parseInt(Rhex, 16);
                    G8bit = parseInt(Ghex, 16);
                    B8bit = parseInt(Bhex, 16);
                } else {
                    R8bit = parseInt(Rhex);
                    G8bit = parseInt(Ghex);
                    B8bit = parseInt(Bhex);
                }
                return [R8bit, G8bit, B8bit];
            }

Now I can use that function from another function, for example to darken or lighten the color by increasing or decreasing the RGB components of the color:

function darken(color)  {
    var rgb = getRGB(Color);
    return [Math.Max(rgb[0]-1,0), Math.Max(rgb[1]-1,0), Math.Max(rgb[2]-1,0)];
}

Or to lighten a color:

function lighten(color)  {
    var rgb = getRGB(Color);
    return [Math.Min(rgb[0]+1,255), Math.Min(rgb[1]+1,255), Math.Min(rgb[2]+255,0)];
}

I can also declare variables and functions inside of a function:

function myColorHelper(e)
{
    var el = $(e);
    var myColor= function() { return el.css("color"); };
    var myrgb = function() { return getRGB(mycolor);};
    var makeDarker = function() {
       var darker = darken(myrgb());
       el.css("color", "rgb(" + darker[0] + ", " + darker[1] + ", " + darker[2]);
      };
    var makeLighter = function() {
       var lighter = lighten(myrgb());
       el.css("color", "rgb(" + lighten[0] + ", " + lighten[1] + ", " + lighten[2]);
      };

}

Plugins and frameworks are full of functions which allow us to use functionality in our code. For example, I could use jQuery with these functions to darken or lighten the color of an element on a webpage.

var helper = myColorHelper($('#myElement'));
helper.makeLighter();
helper.makeDarker();


问:
Create a Map out of a List of String(s) with streams
I have a List of String(s), but I want to convert it into a Map<String, Boolean> from the List<String>, making all of the boolean mappings set to true. I have the following code.

```<code>import java.lang.*;
import java.util.*;
class Main {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("ab");
    list.add("bc");
    list.add("cd");
    Map<String, Boolean> alphaToBoolMap = new HashMap<>();
    for (String item: list) {
      alphaToBoolMap.put(item, true);
    }
    //System.out.println(list); [ab, bc, cd]
    //System.out.println(alphaToBoolMap);  {ab=true, bc=true, cd=true}
  }
}
</code>```

Is there a way to reduce this using streams?

答:
Yes. You can also use Arrays.asList(T...) to create your List. Then use a Stream to collect this with Boolean.TRUE like

```<code>List<String> list = Arrays.asList("ab", "bc", "cd");
Map<String, Boolean> alphaToBoolMap = list.stream()
        .collect(Collectors.toMap(Function.identity(), (a) -> Boolean.TRUE));
System.out.println(alphaToBoolMap);
</code>```

Outputs

```<code>{cd=true, bc=true, ab=true}
</code>```

For the sake of completeness, we should also consider an example where some values should be false. Maybe an empty key like

```<code>List<String> list = Arrays.asList("ab", "bc", "cd", "");

Map<String, Boolean> alphaToBoolMap = list.stream().collect(Collectors //
        .toMap(Function.identity(), (a) -> {
            return !(a == null || a.isEmpty());
        }));
System.out.println(alphaToBoolMap);
</code>```

Which outputs

```<code>{=false, cd=true, bc=true, ab=true}
</code>```

Body:
I have a List of String(s), but I want to convert it into a Map<String, Boolean> from the List<String>, making all of the boolean mappings set to true. I have the following code.

import java.lang.*;
import java.util.*;
class Main {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("ab");
    list.add("bc");
    list.add("cd");
    Map<String, Boolean> alphaToBoolMap = new HashMap<>();
    for (String item: list) {
      alphaToBoolMap.put(item, true);
    }
    //System.out.println(list); [ab, bc, cd]
    //System.out.println(alphaToBoolMap);  {ab=true, bc=true, cd=true}
  }
}

Is there a way to reduce this using streams?

Body:
Yes. You can also use Arrays.asList(T...) to create your List. Then use a Stream to collect this with Boolean.TRUE like

List<String> list = Arrays.asList("ab", "bc", "cd");
Map<String, Boolean> alphaToBoolMap = list.stream()
        .collect(Collectors.toMap(Function.identity(), (a) -> Boolean.TRUE));
System.out.println(alphaToBoolMap);

Outputs

{cd=true, bc=true, ab=true}

For the sake of completeness, we should also consider an example where some values should be false. Maybe an empty key like

List<String> list = Arrays.asList("ab", "bc", "cd", "");

Map<String, Boolean> alphaToBoolMap = list.stream().collect(Collectors //
        .toMap(Function.identity(), (a) -> {
            return !(a == null || a.isEmpty());
        }));
System.out.println(alphaToBoolMap);

Which outputs

{=false, cd=true, bc=true, ab=true}


问:
I want to sum together values in ASP.NET MVC and display them in razor
I have several costs/fees to display for a tenant and now I want to sum up all the values. Here is my code.

```<code>@foreach (var item in Model.Contracts)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Apartment.MonthParkfee)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Apartment.MonthUtilityFee)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.MonthlyRent)
                    </td>
                    <td>
                        @Html.DisplayFor(sumOfAllFees => MonthParkFee + MonthUtilityFee + MonthlyRent)
                    </td>
                </tr>
            }
</code>```

The MonthParkFee and MonthUtilityFee are both in the Apartment table while the MonthlyRent is in the contract table but the contract table contains the foreign key for the Apartment table. How would I be able to add those values together in razor and render them?

答:
Define a variable to hold the sum as below:

```<code>@foreach (var item in Model.Contracts)
{
    var sum = item.Apartment.MonthParkfee + item.Apartment.MonthUtilityFee +item.MonthlyRent;
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Apartment.MonthParkfee)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Apartment.MonthUtilityFee)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.MonthlyRent)
        </td>
        <td>
            @Html.Display("sumOfAllFees" => sum)
        </td>
    </tr>
}
</code>```

Or add a Sum property to view model you are sending and send Sum from controller itself to show in the view.

Body:
I have several costs/fees to display for a tenant and now I want to sum up all the values. Here is my code.

@foreach (var item in Model.Contracts)
            {

                        @Html.DisplayFor(modelItem => item.Apartment.MonthParkfee)

                        @Html.DisplayFor(modelItem => item.Apartment.MonthUtilityFee)

                        @Html.DisplayFor(modelItem => item.MonthlyRent)

                        @Html.DisplayFor(sumOfAllFees => MonthParkFee + MonthUtilityFee + MonthlyRent)

            }

The MonthParkFee and MonthUtilityFee are both in the Apartment table while the MonthlyRent is in the contract table but the contract table contains the foreign key for the Apartment table. How would I be able to add those values together in razor and render them?

Body:
Define a variable to hold the sum as below:

@foreach (var item in Model.Contracts)
{
    var sum = item.Apartment.MonthParkfee + item.Apartment.MonthUtilityFee +item.MonthlyRent;
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Apartment.MonthParkfee)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Apartment.MonthUtilityFee)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.MonthlyRent)
        </td>
        <td>
            @Html.Display("sumOfAllFees" => sum)
        </td>
    </tr>
}

Or add a Sum property to view model you are sending and send Sum from controller itself to show in the view.


问:
use autodesk forge api to get "mass properties" but got nothing
Using the autodesk forge api , first I got a access_token and create a bucketkey and then upload a stl file and then verify the job is complete and then got the guid. use the access_token, urn , guid I post a call :

curl -X 'GET' -H 'Authorization: Bearer
  eyJhbGciOiJIUzI1NiIsImtpZCI6Imp3dF9zeW1tZXRyaWNfa2V5In0.eyJjbGllbnRfaWQiOiJTRmxONGFFOTMzZ0dkU1FzbFZzbXk0TlZZTFNsSnc1dyIsImV4cCI6MTQ5OTQ3OTg4NCwic2NvcGUiOlsiZGF0YTpyZWFkIiwiZGF0YTp3cml0ZSIsImJ1Y2tldDpjcmVhdGUiLCJidWNrZXQ6cmVhZCJdLCJhdWQiOiJodHRwczovL2F1dG9kZXNrLmNvbS9hdWQvand0ZXhwNjAiLCJqdGkiOiJiWUE0TWRSc3VlazVnQlZsV3lwMmwydDN6SllvOXVnMjR4VEI2TmtZUld5YTdPT0NVOWU2c3JGcEk0UWRTWHFJIn0.ckLsWxfaUUa_zY2UDumUApxcDZR6xfCRE18GCHvIpPc'
  -v 'https://developer.api.autodesk.com/modelderivative/v2/designdata/dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6Zm9yZ2UtamF2YS1zYW1wbGUtYXBwLXNmbG40YWU5MzNnZ2RzcXNsdnNteTRudnlsc2xqdzV3LzIwMTcwNzA4MDkxMTU2NTkwMjgzMC5zdGw/metadata/a1f8def6-4c68-4bac-8c88-d14353252d67/properties'

As describe in the tutorials of autodesk: I should got the "mass properties" like volume and area, but I got neither of the two:

< HTTP/1.1 200 OK < Access-Control-Allow-Credentials: true <
  Access-Control-Allow-Origin: * < Content-Type: application/json;
  charset=utf-8 < Date: Sat, 08 Jul 2017 01:15:18 GMT < Server: Apigee
  Router < x-ads-app-identifier:
  platform-viewing-2017.03.08.15.bf43c23-production < x-ads-duration:
  181 ms < x-ads-startup-time: Wed Jun 21 05:40:27 UTC 2017 <
  Content-Length: 387 < Connection: keep-alive <
  * Connection #0 to host developer.api.autodesk.com left intact {"data":{"type":"properties",  "collection":[
    {"objectid":1,"name":"201707080911565902830",
        "properties":{"Name":"201707080911565902830"}},
    {"objectid":2,"name":"201707080911565902830",
        "properties":{"Component
  Name":"201707080911565902830","Name":"201707080911565902830"}},
    {"objectid":3,"name":"mesh_name_undefined",
        "properties":{"Appearance":"191, 191,
  191","Name":"mesh_name_undefined"}}]}}

Any help is appreciate, tks to stackoverflow.com.

答:
This endpoint simply returns the properties that are extracted from the native seed file, it doesn't compute for you mass, volume and so on. I don't think those physical properties are part of the STL file, so you won't see them either with /properties endpoint.

If you upload for example an Inventor or dwf file, you will see properties that are attached to that file. To do a simple test upload your file to our viewer https://a360.autodesk.com/viewer and look at what properties are available using the properties panel, that the same you will get from the endpoint.

Hope that helps


问:
Factory Pattern implementation in C#
I'm implementing a factory pattern that looks as follows.

```<code>public class FeedFactory
{
    #region Singleton Pattern
    //..
    #endregion

    private static Feed[] _factory = new Feed[(int)FeedType.Total];

    public void RegisterFeed(FeedType feedType,Feed feed)
    {
        if (_factory[(int)feedType] == null)
        {
            _factory[(int)feedType] = feed;
        }
        else
        {
            // already registered
        }
    }

    public Feed GetFeed(FeedType feedType)
    {
        return _factory[(int)feedType];
    }
}
</code>```

Here, Feed is an abstract class from which the different classes inherit. How can I register the different classes? Is it possible to do it from their constructor?

答:
```<code>class FeedFactory {

    public IFeedFactory GetFeedFactory(string type) {
       switch(type) {
          case "1": return new Feed1(); break;
          case "2": return new Feed2(); break;
       }

    }

}
</code>```

Note all Feeds Must implement an IFeedFactory interface and implement the method necessary.

//From the client

```<code>FeedFactory ff1 = new FeedFactory();
IFeedFactory obj = ff1.GetFeedFactory("1");
obj.ExecuteMethod();
</code>```

Title: Factory Pattern implementation in C#

Body:
I'm implementing a factory pattern that looks as follows.

public class FeedFactory
{
    #region Singleton Pattern
    //..
    #endregion

    private static Feed[] _factory = new Feed[(int)FeedType.Total];

    public void RegisterFeed(FeedType feedType,Feed feed)
    {
        if (_factory[(int)feedType] == null)
        {
            _factory[(int)feedType] = feed;
        }
        else
        {
            // already registered
        }
    }

    public Feed GetFeed(FeedType feedType)
    {
        return _factory[(int)feedType];
    }
}

Here, Feed is an abstract class from which the different classes inherit. How can I register the different classes? Is it possible to do it from their constructor?

Body:
class FeedFactory {

    public IFeedFactory GetFeedFactory(string type) {
       switch(type) {
          case "1": return new Feed1(); break;
          case "2": return new Feed2(); break;
       }

    }

}

Note all Feeds Must implement an IFeedFactory interface and implement the method necessary.

//From the client

FeedFactory ff1 = new FeedFactory();
IFeedFactory obj = ff1.GetFeedFactory("1");
obj.ExecuteMethod();


问:
Inserting PHP code into the InnerHTML of a SELECT Tag
I am trying to create a function when called, will write PHP code into my document.

For example (original code) .

```<code><select name="impressora" class="form-control">
<option value="selecione">Selecione1...</option><?php foreach($result as
$prod){?><option value="<?php echo $prod['nome'] ?>"><?php echo
$prod['nome'] ?></option><?php } ?></select>
</code>```

The SELECT-Tag above connects to my database to retrieve the data.

When i try using a JavaScript function to insert the retrieved data (seen below)

```<code>function impressora_select(){
var imp = document.getElementById("impressora_div").innerHTML = "<select name='impressora' class='form-control'><option value='selecione'>Selecione2...</option><?php foreach($result as $prod){?><option value='<?php $prod['nome'] ?>'><?php $prod['nome'] ?></option><?php } ?></select>"

  }
</code>```

All that is returned(inserted) is a select option called " Selecione2..."
How do i make this function insert data from my database into my document via innerHTML?

Thanks.

Update with changes from Hasan Delibas.

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jque
ry.min.js"></script>
<script>
$.ajax
({ url: "functions3.php?get=getvalue",
 })
 .done(function( data ) {
  var imp = document.getElementById("impressora_div").innerHTML = data; });
  </script>
  functions3.php -> select name='impressora' class='form-control'><option
  value='selecione'>Selecione2...</option><?php foreach($result as $prod){?>
 <option value='<?php $prod['nome'] ?>'><?php $prod['nome'] ?></option><?php
 } ?></select>
</code>```

But is retuning this error.

```<code> portnew.php:5 GET

portnew.php:7 Uncaught ReferenceError: $ is not defined
at portnew.php:7
(anonymous) @ portnew.php:7
porntnew.php:42 Uncaught ReferenceError: $ is not defined
at portnew.php:42
</code>```

答:
You must use ajax.

First create new .php file for change inside #impressora_div

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>

$.ajax({
  url: "newPhpFile.php?get=getvalue",
})
  .done(function( data ) {
      var imp = document.getElementById("impressora_div").innerHTML = data;
  });
</script>
</code>```

You can not use php web browser side. You but you can call .php file with ajax.

Body:
I am trying to create a function when called, will write PHP code into my document.

For example (original code) .

<select name="impressora" class="form-control">
<option value="selecione">Selecione1...</option><?php foreach($result as
$prod){?><option value="<?php echo $prod['nome'] ?>"><?php echo
$prod['nome'] ?></option><?php } ?></select>

The SELECT-Tag above connects to my database to retrieve the data.

When i try using a JavaScript function to insert the retrieved data (seen below)

function impressora_select(){
var imp = document.getElementById("impressora_div").innerHTML = "<select name='impressora' class='form-control'><option value='selecione'>Selecione2...</option><?php foreach($result as $prod){?><option value='<?php $prod['nome'] ?>'><?php $prod['nome'] ?></option><?php } ?></select>"

  }

All that is returned(inserted) is a select option called " Selecione2..."
How do i make this function insert data from my database into my document via innerHTML?

Thanks.

Update with changes from Hasan Delibas.

  functions3.php -> select name='impressora' class='form-control'><option
  value='selecione'>Selecione2...</option><?php foreach($result as $prod){?>
 <option value='<?php $prod['nome'] ?>'><?php $prod['nome'] ?></option><?php
 } ?></select>

But is retuning this error.

 portnew.php:5 GET

portnew.php:7 Uncaught ReferenceError: $ is not defined
at portnew.php:7
(anonymous) @ portnew.php:7
porntnew.php:42 Uncaught ReferenceError: $ is not defined
at portnew.php:42

Body:
You must use ajax.

First create new .php file for change inside #impressora_div

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>

$.ajax({
  url: "newPhpFile.php?get=getvalue",
})
  .done(function( data ) {
      var imp = document.getElementById("impressora_div").innerHTML = data;
  });
</script>

You can not use php web browser side. You but you can call .php file with ajax.


问:
Error on row collection
I'm beginner and please bear with me. I have an error:

"Additional information: Index was out of range. Must be non-negative
  and less than the size of the collection."

What I wanted to achieve is to click a row on my datagridview and pass all value of selected row on a textboxes.

Here is my code below:

1st I'm selecting everything on "table" and use MySqlDataAdapter to fill my DataTable.

```<code>    private void loadrecord()
    {
        using (MySqlConnection loadcon = new MySqlConnection(connString))
        {
            loadcon.Open();
            MySqlCommand loadcom = new MySqlCommand("SELECT * FROM table1", loadcon);
            MySqlDataAdapter loadad = new MySqlDataAdapter(loadcom);
            DataTable loaddt = new DataTable();
            loadad.Fill(loaddt);

            BindingSource loadbindsource = new BindingSource();
            loadbindsource.DataSource = loaddt;
            dataGridView1.DataSource = loadbindsource;
            loadcon.Close();
        }
    }
</code>```

2nd I'm calling the function loadrecord on Form1_Load

```<code>    private void Form1_Load(object sender, EventArgs e)
    {
     loadrecord();
    }
</code>```

Finally, I have this dataGridView1

```<code>    private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
    {
     //I have 3 records. 1 Balice Book1, 2 Coyman Book2, 3 Pale Book3
     //Click primarykey on datagridview "1" and pass the value of selected   row of "1", pass "1" to Textbox1, pass "Balice" to Textbox2 and pass "Book1" to Textbox3
     //What I have tried so far is this:
     Textbox1.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
     Textbox2.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
     Textbox3.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
     //then this error appear whenever I try to click the cells
     //Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
    }
</code>```

Thank you so much if you did reply on this thread.

答:
Change:

```<code>Textbox1.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
</code>```

to:

```<code>Textbox1.Text = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
</code>```

Also have a squiz at https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcelleventargs(v=vs.110).aspx .

Title: Error on row collection

Body:
I'm beginner and please bear with me. I have an error:

"Additional information: Index was out of range. Must be non-negative
  and less than the size of the collection."

What I wanted to achieve is to click a row on my datagridview and pass all value of selected row on a textboxes.

Here is my code below:

1st I'm selecting everything on "table" and use MySqlDataAdapter to fill my DataTable.

    private void loadrecord()
    {
        using (MySqlConnection loadcon = new MySqlConnection(connString))
        {
            loadcon.Open();
            MySqlCommand loadcom = new MySqlCommand("SELECT * FROM table1", loadcon);
            MySqlDataAdapter loadad = new MySqlDataAdapter(loadcom);
            DataTable loaddt = new DataTable();
            loadad.Fill(loaddt);

            BindingSource loadbindsource = new BindingSource();
            loadbindsource.DataSource = loaddt;
            dataGridView1.DataSource = loadbindsource;
            loadcon.Close();
        }
    }

2nd I'm calling the function loadrecord on Form1_Load

    private void Form1_Load(object sender, EventArgs e)
    {
     loadrecord();
    }

Finally, I have this dataGridView1

    private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
    {
     //I have 3 records. 1 Balice Book1, 2 Coyman Book2, 3 Pale Book3
     //Click primarykey on datagridview "1" and pass the value of selected   row of "1", pass "1" to Textbox1, pass "Balice" to Textbox2 and pass "Book1" to Textbox3
     //What I have tried so far is this:
     Textbox1.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
     Textbox2.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
     Textbox3.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
     //then this error appear whenever I try to click the cells
     //Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
    }

Thank you so much if you did reply on this thread.

Body:
Change:

Textbox1.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();

to:

Textbox1.Text = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();

Also have a squiz at https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcelleventargs(v=vs.110).aspx .


问:
Split a String Into Multiple Strings Using a Regex With Different Capture Groups
I am trying to split a string into multiple strings but rather than using a string just one simple regex pattern, I am trying to use a regex pattern that will split a string into different strings if it detects certain characters, but the characters are different. Instead of splitting the string into different strings, it's giving me each and every individual characters in said string.

```<code>String[] splitstr = line.split("([&]{2})?([|]{2})?(!=)?");
</code>```

Using the above line, I have a variable called line which, as an example, I am putting this line from a file:

```<code>:if[input=right || input=Right]:
</code>```

I am just wondering if there is a way to make this split into

```<code>":if[input=right", "input=Right]:"
</code>```

And if I put in a line like this:

```<code>:if[input=right || input=Right && input != null]:
</code>```

So that it splits into

```<code>":if[input=right", "input=Right", "input != null]:"
</code>```

I was using String#split(regex) for the || symbol and it worked just fine, but now that I want it to split wherever that are || or && or != and I want my code to be efficient and clean and easy to read.

答:
It is a very interesting question. There are more answers for that on the site like: Java String.split() Regex
Also, it so easy to check, like:

```<code>public class Reg {

    public static void main(String args[]) {
        String string = "00!=4-0||34 & 55!=6";
        String[] parts = string.split("[&||!=]");
        for (int i = 0; i < parts.length; i++) {
            System.out.println("Part: " + parts[i]);
        }
    }
}
</code>```

OUTPUT:

```<code>Part: 00
Part:
Part: 4-0
Part:
Part: 34
Part:  55
Part:
Part: 6
</code>```

But problem with symbol "&&", for example, for the:

```<code>    String string = "00!=4-0||34 && 55!=6";
    String[] parts = string.split("[&&||!=]");
</code>```

OUTPUT:

```<code>Part: 00
Part:
Part: 4-0
Part:
Part: 34 && 55
Part:
Part: 6
</code>```

I can guess that we need to understand && in other interpretation, for example:

```<code>public class Reg {

    public static void main(String args[]) {
        String string = "00!=4-0||34 && 55!=6";
        String[] parts = string.split("[&^&||!=]");
        for (int i = 0; i < parts.length; i++) {
            System.out.println("Part: " + parts[i]);
        }
    }
}
</code>```

OUTPUT:

```<code>Part: 00
Part:
Part: 4-0
Part:
Part: 34
Part:
Part:  55
Part:
Part: 6
</code>```

Body:
I am trying to split a string into multiple strings but rather than using a string just one simple regex pattern, I am trying to use a regex pattern that will split a string into different strings if it detects certain characters, but the characters are different. Instead of splitting the string into different strings, it's giving me each and every individual characters in said string.

String[] splitstr = line.split("([&]{2})?([|]{2})?(!=)?");

Using the above line, I have a variable called line which, as an example, I am putting this line from a file:

:if[input=right || input=Right]:

I am just wondering if there is a way to make this split into

":if[input=right", "input=Right]:"

And if I put in a line like this:

:if[input=right || input=Right && input != null]:

So that it splits into

":if[input=right", "input=Right", "input != null]:"

I was using String#split(regex) for the || symbol and it worked just fine, but now that I want it to split wherever that are || or && or != and I want my code to be efficient and clean and easy to read.

Body:
It is a very interesting question. There are more answers for that on the site like: Java String.split() Regex
Also, it so easy to check, like:

public class Reg {

    public static void main(String args[]) {
        String string = "00!=4-0||34 & 55!=6";
        String[] parts = string.split("[&||!=]");
        for (int i = 0; i < parts.length; i++) {
            System.out.println("Part: " + parts[i]);
        }
    }
}

OUTPUT:

Part: 00
Part:
Part: 4-0
Part:
Part: 34
Part:  55
Part:
Part: 6

But problem with symbol "&&", for example, for the:

    String string = "00!=4-0||34 && 55!=6";
    String[] parts = string.split("[&&||!=]");

OUTPUT:

Part: 00
Part:
Part: 4-0
Part:
Part: 34 && 55
Part:
Part: 6

I can guess that we need to understand && in other interpretation, for example:

public class Reg {

    public static void main(String args[]) {
        String string = "00!=4-0||34 && 55!=6";
        String[] parts = string.split("[&^&||!=]");
        for (int i = 0; i < parts.length; i++) {
            System.out.println("Part: " + parts[i]);
        }
    }
}

OUTPUT:

Part: 00
Part:
Part: 4-0
Part:
Part: 34
Part:
Part:  55
Part:
Part: 6


问:
version control in Salesforce?
Has any body implemented version control for salesforce based projects? If yes pleas. share as to how and what tools/technology used to implement the same. Mainly from github to Salesforce</p>

答: Yes by using bitbucket we have implemented version control . We create branches from the master repository . Every developer has their own sandbox . Each branch has been developed in respective sandbox . After completion we merge back each branches to master. </p>

Title: version control in Salesforce?


问:
php function nl2p to ignore lines that start or end with square brackets
I have a function that is working but can not figure a way to modify it for my needs.

Function:

```<code>function mynl2p($string, $line_breaks = true, $xml = true) {
$string = str_replace(array('<p>', '</p>', '<br>', '<br />'), '',     $string);
if ($line_breaks == true)
return '<p>'.preg_replace(array("/([\n]{2,})/i", "/([^>])\n([^<])/i"), array("</p>\n<p>", '$1<br'.($xml == true ? ' /' : '').'>$2'), trim($string)).'</p>';
else
return '<p>'.preg_replace(
array("/([\n]{2,})/i", "/([\r\n]{3,})/i","/([^>])\n([^<])/i"),
array("</p>\n<p>", "</p>\n<p>", '$1<br'.($xml == true ? ' /' : '').'>$2'),

trim($string)).'</p>';
}
</code>```

Example data that is processed:

```<code>    [img]2700:800[/img]

    Some text that is separated with linebreaks in the database and should   be put inside <i>paragraph</i>.
    Sometimes single break can exist and should not be made into new paragraph.
    [quote]
    [img]right:2701:350[/img]
    <b>This is</b>: yet another text for proper paragraph.
    [/quote]
</code>```

Desired result after processing:

```<code>    [img]2700:800[/img]

    <p>Some text that is separated with linebreaks in the database and should be put inside <i>paragraph</i>.
    Sometimes single break can exist and should not be made into new paragraph.</p>
    [quote]
    [img]right:2701:350[/img]
    <p><b>This is</b>: yet another text for proper paragraph.</p>
    [/quote]
</code>```

Please note that all breaks and new lines in the examples are given on purpose to explain the different variants the function can find.

There are many custom tags that can exist inside the square brackets and while it looks close to bbcode it is not.

答:
Since you are asking to ignore the lines that start or ends with brackets,
why not try to find first if the line contains brackets?

```<code>if (strpos($lines, "]") !== false) //for lines that has ]
//proceed to next line
else
//do process here
</code>```

if you want to check if the line has [ at the beginning and ] at the end try to explode the line first,

```<code>$str = explode("",$line); //notice that nothing is inside the double qoute
if($str[0] == '[' && $str[$str.length-1] == ']')
//proceed to next line
else
//do process here
</code>```

Body:
I have a function that is working but can not figure a way to modify it for my needs.

Function:

function mynl2p($string, $line_breaks = true, $xml = true) {
$string = str_replace(array('
', '
', '
', '
'), '',     $string);
if ($line_breaks == true)
return '
'.preg_replace(array("/([\n]{2,})/i", "/([^>])\n([^<])/i"), array("
\n
", '$1
$2'), trim($string)).'
';
else
return '
'.preg_replace(
array("/([\n]{2,})/i", "/([\r\n]{3,})/i","/([^>])\n([^<])/i"),
array("
\n
", "
\n
", '$1
$2'),

trim($string)).'
';
}

Example data that is processed:

    [img]2700:800[/img]

    Some text that is separated with linebreaks in the database and should   be put inside paragraph.
    Sometimes single break can exist and should not be made into new paragraph.
    [quote]
    [img]right:2701:350[/img]
    This is: yet another text for proper paragraph.
    [/quote]

Desired result after processing:

    [img]2700:800[/img]

Some text that is separated with linebreaks in the database and should be put inside paragraph.
    Sometimes single break can exist and should not be made into new paragraph.

    [quote]
    [img]right:2701:350[/img]

This is: yet another text for proper paragraph.

    [/quote]

Please note that all breaks and new lines in the examples are given on purpose to explain the different variants the function can find.

There are many custom tags that can exist inside the square brackets and while it looks close to bbcode it is not.

Body:
Since you are asking to ignore the lines that start or ends with brackets,
why not try to find first if the line contains brackets?

if (strpos($lines, "]") !== false) //for lines that has ]
//proceed to next line
else
//do process here

if you want to check if the line has [ at the beginning and ] at the end try to explode the line first,

$str = explode("",$line); //notice that nothing is inside the double qoute
if($str[0] == '[' && $str[$str.length-1] == ']')
//proceed to next line
else
//do process here


问:
Explicit vs implicit SQL joins
Is there any efficiency difference in an explicit vs implicit inner join?
For example:

```<code>SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;
</code>```

vs.

```<code>SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;
</code>```

答:
@lomaxx:  Just to clarify, I'm pretty certain that both above syntax are supported by SQL Serv 2005.  The syntax below is NOT supported however

```<code>select a.*, b.*
from table a, table b
where a.id *= b.id;
</code>```

Specifically, the outer join (*=) is not supported.

OwnerDisplayName: dmanxiii

Title: Explicit vs implicit SQL joins

Body:
Is there any efficiency difference in an explicit vs implicit inner join?
For example:

SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;

vs.

SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;

LastEditorDisplayName: Eric Z Beard

Body:
@lomaxx:  Just to clarify, I'm pretty certain that both above syntax are supported by SQL Serv 2005.  The syntax below is NOT supported however

select a.*, b.*
from table a, table b
where a.id *= b.id;

Specifically, the outer join (*=) is not supported.

OwnerDisplayName: deadbug


问:
How can I show file sizes with commas when getting a directory listing with 'ls -l'?
You can do 'ls -l' to get a detailed directory listing like this:

```<code>-rw-rw-rw-  1 alice themonkeys 1159995999 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob         244251992 2008-08-20 05:30 bar.txt
</code>```

But notice how you have to slide your finger along the screen to figure out the order of magnitude of those file sizes.

What's a good way to add commas to the file sizes in the directory listing, like this:

```<code>-rw-rw-rw-  1 alice themonkeys 1,159,995,999 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob          244,251,992 2008-08-20 05:30 bar.txt
</code>```

答:
If the order of magnitude is all you're interested in, ls -lh does something like this:

```<code>-rw-r----- 1 alice themonkeys 626M 2007-02-05 01:15 foo.log
-rw-rw-r-- 1 bob   bob        699M 2007-03-12 23:14 bar.txt
</code>```

OwnerDisplayName: dreeves

Body:
You can do 'ls -l' to get a detailed directory listing like this:

-rw-rw-rw-  1 alice themonkeys 1159995999 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob         244251992 2008-08-20 05:30 bar.txt

But notice how you have to slide your finger along the screen to figure out the order of magnitude of those file sizes.

What's a good way to add commas to the file sizes in the directory listing, like this:

-rw-rw-rw-  1 alice themonkeys 1,159,995,999 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob          244,251,992 2008-08-20 05:30 bar.txt

Body:
If the order of magnitude is all you're interested in, ls -lh does something like this:

-rw-r----- 1 alice themonkeys 626M 2007-02-05 01:15 foo.log
-rw-rw-r-- 1 bob   bob        699M 2007-03-12 23:14 bar.txt

OwnerDisplayName: JB