问:
How to fetch the value from an API based on select box value?
I have an API to get the value for dropdown and scoring value.

1) I have an UI which looks like below screenshot.

2) Code is mentioned below:

```<code><td>
    <div class="">
        <select ng-if="question.MasterDataCategoryId != null" id="answer{{question.QuestionId}}" ng-model="question.MasterData" ng-init="question.MasterData;" class="form-control" style="width: 300px; white-space:pre-wrap;">
            <option selected="selected"></option>
            <option ng-repeat="answer in answerData[question.MasterDataCategoryId]" value="{{answer.MasterData}}">{{answer.MasterData}}</option>
        </select>
        <input ng-if="question.MasterDataCategoryId == null" id="{{question.QuestionId}}" ng-model="question.MasterData" type="text" style="width: 300px;" name="question.QuestionId" class="form-control">
    </div>
</td>
<td>
    <div class="">
        <span ng-if="question.MasterDataCategoryId != null">{{question.Score}}</span>
        <select ng-if="question.MasterDataCategoryId == null" id="projectlist" class="form-control" required ng-model="scoring">
            <option selected="selected"></option>
            <option ng-repeat="score in scoringDetails" value="{{score.Score}}">
                {{score.Score}}
            </option>
        </select>
    </div>
</td>
</code>```

Based on the dropdown value I need to dynamically show the scoring which I will get in the same API.

Can any let me know how to achive this.

答:
In ng-change of dropdown write a fucntion which changes the score dropdown value. Suppose the follwing code

In HTML

```<code><select ng-change="scoreChange()"  ng-model="dropvalue">
  <option></option>.....
</select>

<select ng-model="score">
  <option></option>.....
</select>
</code>```

In Controller

```<code>$scope.scoreChange = function(){
  $scope.score = desiredvalue;
  //or you can call api and assign it here.
}
</code>```

Body:
I have an API to get the value for dropdown and scoring value.

1) I have an UI which looks like below screenshot.

2) Code is mentioned below:

        <select ng-if="question.MasterDataCategoryId != null" id="answer{{question.QuestionId}}" ng-model="question.MasterData" ng-init="question.MasterData;" class="form-control" style="width: 300px; white-space:pre-wrap;">
            <option selected="selected"></option>
            <option ng-repeat="answer in answerData[question.MasterDataCategoryId]" value="{{answer.MasterData}}">{{answer.MasterData}}</option>
        </select>
        <input ng-if="question.MasterDataCategoryId == null" id="{{question.QuestionId}}" ng-model="question.MasterData" type="text" style="width: 300px;" name="question.QuestionId" class="form-control">

        {{question.Score}}
        <select ng-if="question.MasterDataCategoryId == null" id="projectlist" class="form-control" required ng-model="scoring">
            <option selected="selected"></option>
            <option ng-repeat="score in scoringDetails" value="{{score.Score}}">
                {{score.Score}}
            </option>
        </select>

Based on the dropdown value I need to dynamically show the scoring which I will get in the same API.

Can any let me know how to achive this.

Body:
In ng-change of dropdown write a fucntion which changes the score dropdown value. Suppose the follwing code

In HTML

<select ng-change="scoreChange()"  ng-model="dropvalue">
  <option></option>.....
</select>

<select ng-model="score">
  <option></option>.....
</select>

In Controller

$scope.scoreChange = function(){
  $scope.score = desiredvalue;
  //or you can call api and assign it here.
}


来源: stackexchange

问:
Why and when Liquibase?
I have searched for this answer on stack overflow, but I couldn't find any questions on this.
I am new to Liquibase and want to learn

Why Liquibase?

When exactly one should use Liquibase in the project?

I know that this is to keep all database changes in one place but the similar can be done by creating a simple SQL files in some repository system and keep updating it with time.

答: When you have multiple database instances in dev, qa, production and you want to have a tool to automatically track the change history and apply changes intelligently(apply the diff of current schema and final schema), tools like liquibase or flyway will be very useful.</p>

ContentLicense: CC BY-SA 4.0

Title: Why and when Liquibase?


问:
I would want to write regEx for character to accept from a-zA-z0-9 (from 1-to any) with mandatory one special character from . OR _
I tried this:

```<code>^(?=.*[a-zA-Z0-9])(?=[.|_]).$
</code>```

I am not sure where I am going wrong

答:
You can try the following regular expression, if you want only one special character:

```<code>/^[a-z\d]+[._][a-z\d]*|[a-z\d]*[._][a-z\d]+$/i
</code>```

If, instead, you want at least one special character you can use the following:

```<code>/^(?:[a-z\d]+[._]+[a-z\d]*|[a-z\d]*[._]+[a-z\d]+)+$/i
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I tried this:

^(?=.*[a-zA-Z0-9])(?=[.|_]).$

I am not sure where I am going wrong

Body:
You can try the following regular expression, if you want only one special character:

/^[a-z\d]+[._][a-z\d]*|[a-z\d]*[._][a-z\d]+$/i

If, instead, you want at least one special character you can use the following:

/^(?:[a-z\d]+[._]+[a-z\d]*|[a-z\d]*[._]+[a-z\d]+)+$/i


问:
How to convert a DBNULL to double?
im getting a value from the database. it came out an error saying "Conversion from DBNULL to Double is not Valid." anyone, pls help me?

Public Function Total() As Double
        Dim Total As Double

```<code>    Dim strConn As String
    strConn = ConfigurationManager.ConnectionStrings("***").ToString
    Dim conn As New SqlConnection(strConn)

    Dim strSql As String
    strSql = "SELECT SUM (p.Price * c.Quantity) as 'Total' " & _
    "FROM CartItem sci INNER JOIN Product p ON c.ProductID=p.ProductID " & _
    "WHERE c.CartID=@CartID "

    Dim cmd As New SqlCommand(strSql, conn)

    cmd.Parameters.AddWithValue("@CartID", CartID)

    Dim da As New SqlDataAdapter(cmd)

    Dim ds As New DataSet

    conn.Open()

    da.Fill(ds, "CartItem")

    conn.Close()

    If (ds.Tables("CartItem").Rows.Count) <> 0 Then
        **Total = ds.Tables("ShopCartItem").Rows(0)("Total")**
    Else
        Total = 0.0
    End If
    Return Total
End Function
</code>```

答: Can you instead use Nullable(Of double) as your data type on the VB side?</p>

ContentLicense: CC BY-SA 2.5

Title: How to convert a DBNULL to double?

Body:
im getting a value from the database. it came out an error saying "Conversion from DBNULL to Double is not Valid." anyone, pls help me?

Public Function Total() As Double
        Dim Total As Double

    Dim strConn As String
    strConn = ConfigurationManager.ConnectionStrings("***").ToString
    Dim conn As New SqlConnection(strConn)

    Dim strSql As String
    strSql = "SELECT SUM (p.Price * c.Quantity) as 'Total' " & _
    "FROM CartItem sci INNER JOIN Product p ON c.ProductID=p.ProductID " & _
    "WHERE c.CartID=@CartID "

    Dim cmd As New SqlCommand(strSql, conn)

    cmd.Parameters.AddWithValue("@CartID", CartID)

    Dim da As New SqlDataAdapter(cmd)

    Dim ds As New DataSet

    conn.Open()

    da.Fill(ds, "CartItem")

    conn.Close()

    If (ds.Tables("CartItem").Rows.Count) <> 0 Then
        **Total = ds.Tables("ShopCartItem").Rows(0)("Total")**
    Else
        Total = 0.0
    End If
    Return Total
End Function


问:
Generic way to avoid special characters in R
The following are a series of e mail subjects. DF- data.frame. Note I have imported this from an excel sheet.

```<code>  EmailSubject
 Buy the stunning new phone
 The game changer is here.
  Experience a phone ahead of its time.
  Thank You Chennai
   Limited Period offer
   Valentines day special
  Buy a phone at 10000 and get a new sim free
   Limited Period offer
  Valentines day special
  Buy a phone at 10000 and get a new sim free
  Buy the stunning new phone
  The game changer is here.
  Experience a phone ahead of its time.
  Thank You Chennai
   Limited Period offer
   Valentines day special
  Buy a phone at 10000 and get a new sim free
 Thank You Chennai
Limited Period offer
 Valentines day special
 Buy a phone at 10000 and get a new sim free
 Buy a phone at 10000 and get a new sim free
 Buy the stunning new phone
 The game changer is here.
</code>```

I have created a term document matrix in R with the following code

```<code> require(tm)
 mytext<-DF$EmailSubject
 mycorpus<-Corpus(VectorSource(mytext))
 mycorpus<-tm_map(mycorpus,removePunctuation)
 mycorpus<-tm_map(mycorpus, removeNumbers)
 mycorpus<-tm_map(mycorpus, tolower)
 mycorpus<-tm_map(mycorpus, removeWords, stopwords("english"))

    # # Create a term diocumentmatrix
    dtm<-TermDocumentMatrix(mycorpus)
     m<-as.matrix(dtm)
     v <- sort(rowSums(m),decreasing=TRUE)
     d <- data.frame(word = names(v),freq=v)
     head(d, 10)
</code>```

This yields the following term document matrix

```<code>                          word freq

                          get   45
                          free   44
                          edge   35

                          new   29
                          buy   24
                        charger   23
                        wireless   23
                          just   21
                          month   21
                            per   21
                        starting   21
                        stunning   21
                            pro   20
                            now   17
                         offers   17
                           gear   16
                       exclusive   15
                          offer   14
                           gift   13

                       irresistible   10
                           loved   10
                    valentineâ€™s   10
</code>```

I m getting a term document matrix. However, some words appear with â€™ special characters only in the term document matrix- they arent present in the original data frame. I have tried adjusting the encoding and have manually removed the same with Gsub. Is there a way to avoid the words from my excel sheet being processed with special characters.

```<code>gsub("€™", "", d$word)
</code>```

This is a manual method. Is there an automatic method. The encoding is UTF-8. Are there packages that enable us to avoid this error

答:
This should help you :</p>

```<code>Encoding(x) <- "UTF-8"

iconv(dtm, "UTF-8", "ASCII", sub="")
</code>```

Body:
The following are a series of e mail subjects. DF- data.frame. Note I have imported this from an excel sheet.

  EmailSubject
 Buy the stunning new phone
 The game changer is here.
  Experience a phone ahead of its time.
  Thank You Chennai
   Limited Period offer
   Valentines day special
  Buy a phone at 10000 and get a new sim free
   Limited Period offer
  Valentines day special
  Buy a phone at 10000 and get a new sim free
  Buy the stunning new phone
  The game changer is here.
  Experience a phone ahead of its time.
  Thank You Chennai
   Limited Period offer
   Valentines day special
  Buy a phone at 10000 and get a new sim free
 Thank You Chennai
Limited Period offer
 Valentines day special
 Buy a phone at 10000 and get a new sim free
 Buy a phone at 10000 and get a new sim free
 Buy the stunning new phone
 The game changer is here.

I have created a term document matrix in R with the following code

 require(tm)
 mytext<-DF$EmailSubject
 mycorpus<-Corpus(VectorSource(mytext))
 mycorpus<-tm_map(mycorpus,removePunctuation)
 mycorpus<-tm_map(mycorpus, removeNumbers)
 mycorpus<-tm_map(mycorpus, tolower)
 mycorpus<-tm_map(mycorpus, removeWords, stopwords("english"))

    # # Create a term diocumentmatrix
    dtm<-TermDocumentMatrix(mycorpus)
     m<-as.matrix(dtm)
     v <- sort(rowSums(m),decreasing=TRUE)
     d <- data.frame(word = names(v),freq=v)
     head(d, 10)

This yields the following term document matrix

                          word freq

                          get   45
                          free   44
                          edge   35

                          new   29
                          buy   24
                        charger   23
                        wireless   23
                          just   21
                          month   21
                            per   21
                        starting   21
                        stunning   21
                            pro   20
                            now   17
                         offers   17
                           gear   16
                       exclusive   15
                          offer   14
                           gift   13

                       irresistible   10
                           loved   10
                    valentineâ€™s   10

I m getting a term document matrix. However, some words appear with â€™ special characters only in the term document matrix- they arent present in the original data frame. I have tried adjusting the encoding and have manually removed the same with Gsub. Is there a way to avoid the words from my excel sheet being processed with special characters.

gsub("€™", "", d$word)

This is a manual method. Is there an automatic method. The encoding is UTF-8. Are there packages that enable us to avoid this error

Body:
This should help you :

Encoding(x) <- "UTF-8"

iconv(dtm, "UTF-8", "ASCII", sub="")


问:
How to run a JAVA Fx application along with other components through .exe file
I have created a JavaFx application in NetBeans. I just created a sample textfield page where user enters Ip address and port number so that I will be connecting to the server on local host written in basic JAVA socket library. Mean while in a parallel thread I am starting a JAVA TCP server in the same application which receives data from a tcp client. Now the problem is when I run through NetBeans the server is able to start happily. But when I made a .exe file using launch4j only the TCp client is starting which user has filled the details in UI. And after that the next process is not starting up.

But it is working absolutely fine when running through NetBeans. I made several .exe files through launch4j but I never included GUI part into the .exe files. Is this causing any issue? The GUI only takes the IP address and port number from the user and when the user clicks on OK button the UI page closes and remaining process has to start. But when I run through .exe file it is not running. Please help me with this. When I built my project with netbeans I am seeing the output as:

```<code>Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Copying 12 files to D:\NetBeansProjects\QTSimulator\build\classes
compile:
Created dir: D:\NetBeansProjects\QTSimulator\dist
Copying 12 files to D:\NetBeansProjects\QTSimulator\dist\lib
Detected JavaFX Ant API version 1.3
Launching <fx:jar> task from C:\Program Files\Java\jdk1.8.0_144\jre\..\lib\ant-javafx.jar
Launching <fx:deploy> task from C:\Program Files\Java\jdk1.8.0_144\jre\..\lib\ant-javafx.jar
No base JDK. Package will use system JRE.
No base JDK. Package will use system JRE.
jfx-deployment-script:
jfx-deployment:
jar:
jfx-rebuild:
BUILD SUCCESSFUL (total time: 15 seconds)
</code>```

Am I doing any wrong here. Please help me.

答: NetBeans has bugs with the JAVAFx applications. You can run through NetBeans IDE but when you run through the Jar we get these kind of issues. Try installing Eclipse and import the project and build. Later make a runnable jar and then launch it. It works</p>

Body:
I have created a JavaFx application in NetBeans. I just created a sample textfield page where user enters Ip address and port number so that I will be connecting to the server on local host written in basic JAVA socket library. Mean while in a parallel thread I am starting a JAVA TCP server in the same application which receives data from a tcp client. Now the problem is when I run through NetBeans the server is able to start happily. But when I made a .exe file using launch4j only the TCp client is starting which user has filled the details in UI. And after that the next process is not starting up.

But it is working absolutely fine when running through NetBeans. I made several .exe files through launch4j but I never included GUI part into the .exe files. Is this causing any issue? The GUI only takes the IP address and port number from the user and when the user clicks on OK button the UI page closes and remaining process has to start. But when I run through .exe file it is not running. Please help me with this. When I built my project with netbeans I am seeing the output as:

Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Copying 12 files to D:\NetBeansProjects\QTSimulator\build\classes
compile:
Created dir: D:\NetBeansProjects\QTSimulator\dist
Copying 12 files to D:\NetBeansProjects\QTSimulator\dist\lib
Detected JavaFX Ant API version 1.3
Launching <fx:jar> task from C:\Program Files\Java\jdk1.8.0_144\jre\..\lib\ant-javafx.jar
Launching <fx:deploy> task from C:\Program Files\Java\jdk1.8.0_144\jre\..\lib\ant-javafx.jar
No base JDK. Package will use system JRE.
No base JDK. Package will use system JRE.
jfx-deployment-script:
jfx-deployment:
jar:
jfx-rebuild:
BUILD SUCCESSFUL (total time: 15 seconds)

Am I doing any wrong here. Please help me.


问:
Unable to get last character of string

** Code: **

```<code>String test = "32132SSS654";
char Lastchar = test[test.Length - 1];

Assert.IsTrue((Lastchar).Equals("4"));
</code>```

I am trying to get the last character from the string then doing assert but it returns me something extra like 52 with the last character 4 and that's why my assert getting fail.

答: The value of Lastchar is correct. 52 is the decimal representation / value for the character 4 (see ASCII table). It's just a debug specific display.

Title: Unable to get last character of string

Body:
** Code: **

String test = "32132SSS654";
char Lastchar = test[test.Length - 1];

Assert.IsTrue((Lastchar).Equals("4"));

I am trying to get the last character from the string then doing assert but it returns me something extra like 52 with the last character 4 and that's why my assert getting fail.


问:
Why I test golang goroutine slow than java Thread
====================== Edit 2016 05 27 16:55 Solved =======================

This problem is solved! thanks to @Paul Hankin, You are right! Java is good at do "for() {i = i + 1}", so when i change code to "for() {i = i + i}", java lose.

(PS: Use Java ExecutorService really make the java result nice, but still not as good as goroutine, no ExecutorService example here)

Java Code :

```<code>import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String args[]) throws InterruptedException {
        List<Thread> threads = new ArrayList<Thread>();

        for(int i = 0; i < 10; i ++) {
            threads.add(new Thread(new RunableAdd()));
        }

        long timeStart = System.currentTimeMillis();

        for(Thread t: threads) {
            t.start();
        }

        for(Thread t: threads) {
            t.join();
        }

        System.out.println("Time Use : " + (System.currentTimeMillis() - timeStart) + "ms");
    }

}

class RunableAdd implements Runnable {
    @Override
    public void run() {
        long i = 1;
        while(true) {
            i += i;
            if (i > 1000 * 1000* 1000) {
                return;
            }
        }
    }
}
</code>```

Golang code:

```<code>package main

import (
    "fmt"
    "time"
)

func main() {
    chanSignal := make(chan bool)

    startTime := time.Now()

    goroutineNum := 10

    for i := 0; i < goroutineNum; i++ {
        go func() {
            j := 1
            for {
                j = j + j
                if j > 1000*1000*1000 {
                    chanSignal <- true
                    return
                }
            }
        }()
    }

    for i := 0; i < goroutineNum; i++ {
        <-chanSignal
    }

    fmt.Println(time.Since(startTime))
}
</code>```

Result :

Thread/goroutine num : 10

```<code>java : Time Use : 4ms
golang : 19.105µs
</code>```

Thread/goroutine num : 100

```<code>java : Time Use : 27ms
golang : 180.272µs
</code>```

Thread/goroutine num : 1000

```<code>java: Time Use : 512ms
golang : 1.565521ms
</code>```

turns out that golang is good, and java is good at "i = i + 1",

What's instering is that , when goroutine num pluse 10, the time cost is less than 10 times.

===============================End====================================

I'm test golang goroutine with java thread today, I think golang goroutine should faster than java Thread, but my test result show that java thread wins.

Environment:
java 1.8
golang 1.6

cpu are 4 core

```<code>$ cat /proc/cpuinfo | grep 'core id'
core id     : 0
core id     : 0
core id     : 1
core id     : 1
</code>```

Java code:

```<code>import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String args[]) throws InterruptedException {
        List<Thread> threads = new ArrayList<Thread>();

        for(int i = 0; i < 100; i ++) {
            threads.add(new Thread(new RunableAdd()));
        }

        long timeStart = System.currentTimeMillis();

        for(Thread t: threads) {
            t.start();
        }

        for(Thread t: threads) {
            t.join();
        }

        System.out.println("Time Use : " + (System.currentTimeMillis() - timeStart) + "ms");
    }

}

class RunableAdd implements Runnable {
    @Override
    public void run() {
        int i = 0;
        while(true) {
            i ++;
            if (i == 10 * 1000* 1000) {
                return;
            }
        }
    }
}
</code>```

golang code:

```<code>package main

import (
    "fmt"
    "time"
)

func main() {
    chanSignal := make(chan bool)

    startTime := time.Now()

    goroutineNum := 100

    for i := 0; i < goroutineNum; i++ {
        go func() {
            j := 0
            for {
                if j == 10*1000*1000 {
                    chanSignal <- true
                    return
                } else {
                    j = j + 1
                }
            }
        }()
    }

    for i := 0; i < goroutineNum; i++ {
        <-chanSignal
    }

    fmt.Println(time.Since(startTime))
}
</code>```

and result is :

when i set thread num 10:

```<code>Java : Time Use : 18ms
golang : 50.952259ms
</code>```

Thread num 100:

```<code>Java : Time Use : 88ms
golang : Time Use : 458.239685ms
</code>```

Thread num 1000:

```<code>Java : Time Use : 1452ms
golang : 4.701811465s
</code>```

Did Java Thread really fast than golang goroutine? Or my program did something wrong?

答:
The i = i+i test is silly, since it performs nearly only 24 adds and 24 < comparisons, and I believe we all admit that we don't often encounter real world problem which can be completed with only 48 machine instructions.

And rather than Thread, Executors.newFixedThreadPool is more close Java equivalent of goroutine, try it with warm up, you might get different results.

Body:
====================== Edit 2016 05 27 16:55 Solved =======================

This problem is solved! thanks to @Paul Hankin, You are right! Java is good at do "for() {i = i + 1}", so when i change code to "for() {i = i + i}", java lose.

(PS: Use Java ExecutorService really make the java result nice, but still not as good as goroutine, no ExecutorService example here)

Java Code :

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String args[]) throws InterruptedException {
        List<Thread> threads = new ArrayList<Thread>();

        for(int i = 0; i < 10; i ++) {
            threads.add(new Thread(new RunableAdd()));
        }

        long timeStart = System.currentTimeMillis();

        for(Thread t: threads) {
            t.start();
        }

        for(Thread t: threads) {
            t.join();
        }

        System.out.println("Time Use : " + (System.currentTimeMillis() - timeStart) + "ms");
    }

}

class RunableAdd implements Runnable {
    @Override
    public void run() {
        long i = 1;
        while(true) {
            i += i;
            if (i > 1000 * 1000* 1000) {
                return;
            }
        }
    }
}

Golang code:

package main

import (
    "fmt"
    "time"
)

func main() {
    chanSignal := make(chan bool)

    startTime := time.Now()

    goroutineNum := 10

    for i := 0; i < goroutineNum; i++ {
        go func() {
            j := 1
            for {
                j = j + j
                if j > 1000*1000*1000 {
                    chanSignal <- true
                    return
                }
            }
        }()
    }

    for i := 0; i < goroutineNum; i++ {
        <-chanSignal
    }

    fmt.Println(time.Since(startTime))
}

Result :

Thread/goroutine num : 10

java : Time Use : 4ms
golang : 19.105µs

Thread/goroutine num : 100

java : Time Use : 27ms
golang : 180.272µs

Thread/goroutine num : 1000

java: Time Use : 512ms
golang : 1.565521ms

turns out that golang is good, and java is good at "i = i + 1",

What's instering is that , when goroutine num pluse 10, the time cost is less than 10 times.

===============================End====================================

I'm test golang goroutine with java thread today, I think golang goroutine should faster than java Thread, but my test result show that java thread wins.

Environment:
java 1.8
golang 1.6

cpu are 4 core

$ cat /proc/cpuinfo | grep 'core id'
core id     : 0
core id     : 0
core id     : 1
core id     : 1

Java code:

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String args[]) throws InterruptedException {
        List<Thread> threads = new ArrayList<Thread>();

        for(int i = 0; i < 100; i ++) {
            threads.add(new Thread(new RunableAdd()));
        }

        long timeStart = System.currentTimeMillis();

        for(Thread t: threads) {
            t.start();
        }

        for(Thread t: threads) {
            t.join();
        }

        System.out.println("Time Use : " + (System.currentTimeMillis() - timeStart) + "ms");
    }

}

class RunableAdd implements Runnable {
    @Override
    public void run() {
        int i = 0;
        while(true) {
            i ++;
            if (i == 10 * 1000* 1000) {
                return;
            }
        }
    }
}

golang code:

package main

import (
    "fmt"
    "time"
)

func main() {
    chanSignal := make(chan bool)

    startTime := time.Now()

    goroutineNum := 100

    for i := 0; i < goroutineNum; i++ {
        go func() {
            j := 0
            for {
                if j == 10*1000*1000 {
                    chanSignal <- true
                    return
                } else {
                    j = j + 1
                }
            }
        }()
    }

    for i := 0; i < goroutineNum; i++ {
        <-chanSignal
    }

    fmt.Println(time.Since(startTime))
}

and result is :

when i set thread num 10:

Java : Time Use : 18ms
golang : 50.952259ms

Thread num 100:

Java : Time Use : 88ms
golang : Time Use : 458.239685ms

Thread num 1000:

Java : Time Use : 1452ms
golang : 4.701811465s

Did Java Thread really fast than golang goroutine? Or my program did something wrong?


答:
The last character is a char not a string:

```<code>Assert.IsTrue((Lastchar).Equals('4'));
</code>```

(char literals use single quotes).

The 52 is the ASCII value for the character "4"

Title: Unable to get last character of string

Body:
The last character is a char not a string:

Assert.IsTrue((Lastchar).Equals('4'));

(char literals use single quotes).

The 52 is the ASCII value for the character "4"


问:
automatic href to div when page loaded
I have html code

```<code><h1>Popup/Modal Windows without JavaScript</h1>
<div class="box">
<a class="button" href="#popup1">Let me Pop up</a>
</div>

<div id="popup1" class="overlay">
  <div class="popup">
    <h2>Here i am</h2>
    <a class="close" href="#">×</a>
    <div class="content">
        Thank to pop me out of that button, but now i'm done so you can
    </div>
  </div>
</div>
</code>```

I want popup window show when page is loaded. not waiting when i click to button. How to make with javascript or jquery? This example i found in here

答:
Please use onload function.

HTML

```<code><body onload="load()">
    <div id="popup">
       <div id="popUPAlert" style="display:none;">
          //Model content
       </div>
    </div>
</body>
</code>```

Javascript

```<code>function load(){
    document.getElementById('popUPAlert').style.display="block";
}
</code>```

Title: automatic href to div when page loaded

Body:
I have html code

Popup/Modal Windows without JavaScript

Let me Pop up

Here i am

    ×

        Thank to pop me out of that button, but now i'm done so you can

I want popup window show when page is loaded. not waiting when i click to button. How to make with javascript or jquery? This example i found in here

Body:
Please use onload function.

HTML

<body onload="load()">
    <div id="popup">
       <div id="popUPAlert" style="display:none;">
          //Model content
       </div>
    </div>
</body>

Javascript

function load(){
    document.getElementById('popUPAlert').style.display="block";
}


问:
How to clear datagridview using timer?
I want to update datagridview every 10 seconds. So far after update, new rows are added and I want to clean the datagridview before update.

The problem is that, when I call inside of OnCallBack() dataGridView2.Rows.Clear(); and dataGridView2.Refresh();, I get an exception:

Cross-thread operation not valid

I have tried to Invoke it, but it doesn't help.

```<code> if(dataGridView2.InvokeRequired){
        dataGridView2.Invoke(new MethodInvoker(delegate{
        dataGridView2.Rows.Clear();
        dataGridView2.Refresh();
 }));
</code>```

My code:

```<code>    private void Live(){
        timer = new System.Threading.Timer (_ => OnCallBack(), null, 1000,Timeout.Infinite);
    }

    private void OnCallBack()
    {
        timer.Dispose();
        counter--;

        label8.Text = counter.ToString();
        if (counter == 0){
                string[] pr = {"124"};
                search.SearchLive(pr, dataGridView2, label10);
                counter = 10;
        }
        timer = new System.Threading.Timer (_ => OnCallBack(), null, 1000,Timeout.Infinite);
     }
</code>```

答:
You can only access UI components from the UI thread. The Threading.Timer will execute the callback on a thread from the thread pool, and not the UI thread, causing your exception.But there are ways to dispatch your function call to the UI thread.

Dispatch your call to the UI thread

Most UI frameworks are completely single threaded. It is not allowed to access any component from a different thread than the UI thread.

You need to dispatch to the current UI thread. Looking it at your control names, it looks either like a WinForms or a WPF application.

In WinForms you need the following code to dispatch back to the UI thread:

```<code>public void UpdateUI(object parameter)
{
    if (this.InvokeRequired)
    {
       Dispatcher.BeginInvoke(new Action(() => UpdateUI(parameter)));
        return;
    }

    // Update or access here
}
</code>```

In WPF the following snipped allows you to change the ui form a different thread:

```<code>public void UpdateUI(object parameter)
{
    if (!Dispatcher.CheckAccess())
    {
       Dispatcher.BeginInvoke(new Action(() => UpdateUI(parameter)));
       return;
    }

    // Do update or access here
}
</code>```

The important thing to notice here, is that those functions will be executed on the UI thread and not on the calling thread.

Edit: the object parameter is completely optional. It was intended as a example of how to use this method with a function with parameters.

Using System.Timers.Timer

You could also use the System.Timers.Timer, which works quite similiar to the timer in System.Threading.Timer but will execute the callback on the UI thread.

Title: How to clear datagridview using timer?

Body:
I want to update datagridview every 10 seconds. So far after update, new rows are added and I want to clean the datagridview before update.

The problem is that, when I call inside of OnCallBack() dataGridView2.Rows.Clear(); and dataGridView2.Refresh();, I get an exception:

Cross-thread operation not valid

I have tried to Invoke it, but it doesn't help.

 if(dataGridView2.InvokeRequired){
        dataGridView2.Invoke(new MethodInvoker(delegate{
        dataGridView2.Rows.Clear();
        dataGridView2.Refresh();
 }));

My code:

    private void Live(){
        timer = new System.Threading.Timer (_ => OnCallBack(), null, 1000,Timeout.Infinite);
    }

    private void OnCallBack()
    {
        timer.Dispose();
        counter--;

        label8.Text = counter.ToString();
        if (counter == 0){
                string[] pr = {"124"};
                search.SearchLive(pr, dataGridView2, label10);
                counter = 10;
        }
        timer = new System.Threading.Timer (_ => OnCallBack(), null, 1000,Timeout.Infinite);
     }

Body:
You can only access UI components from the UI thread. The Threading.Timer will execute the callback on a thread from the thread pool, and not the UI thread, causing your exception.But there are ways to dispatch your function call to the UI thread.

Dispatch your call to the UI thread

Most UI frameworks are completely single threaded. It is not allowed to access any component from a different thread than the UI thread.

You need to dispatch to the current UI thread. Looking it at your control names, it looks either like a WinForms or a WPF application.

In WinForms you need the following code to dispatch back to the UI thread:

public void UpdateUI(object parameter)
{
    if (this.InvokeRequired)
    {
       Dispatcher.BeginInvoke(new Action(() => UpdateUI(parameter)));
        return;
    }

    // Update or access here
}

In WPF the following snipped allows you to change the ui form a different thread:

public void UpdateUI(object parameter)
{
    if (!Dispatcher.CheckAccess())
    {
       Dispatcher.BeginInvoke(new Action(() => UpdateUI(parameter)));
       return;
    }

    // Do update or access here
}

The important thing to notice here, is that those functions will be executed on the UI thread and not on the calling thread.

Edit: the object parameter is completely optional. It was intended as a example of how to use this method with a function with parameters.

Using System.Timers.Timer

You could also use the System.Timers.Timer, which works quite similiar to the timer in System.Threading.Timer but will execute the callback on the UI thread.


问:
Weird Characters outputed whenever ptr from CURL_WRITEFUNCTION is printed.
I'm having a bit of an issue, here is my code (I'm using C): </p>

```<code>#include <stdio.h>
#include <curl/curl.h>
#include <stdlib.h>
#include <json/json.h>

size_t callback_func(void *ptr, size_t size, size_t count, void *stream) {
//json_object *json_obj = json_tokener_parse(ptr);
printf ("%s",(char*)ptr);

return count;

}

int main(void)
{
      CURL *curl;
          CURLcode res;

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://stream.twitter.com/1/statuses/filter.json?track=http");
    curl_easy_setopt(curl, CURLOPT_USERPWD, "Firrus:password");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback_func);
    curl_easy_perform(curl);

    /* always cleanup */
    curl_easy_cleanup(curl);

  }

  return 0;
}
</code>```

<p>The problem is that, every time ptr is printed, three weird (seemingly random) characters are also outputted at the top, e.g. 77D or 6DA. What do these characters mean? How can I remove them? </p>

答:
In according with the documentation the callback functions works on this way:

Function pointer that should match the
  following prototype: size_t function(
  void *ptr, size_t size, size_t nmemb,
  void *userdata); This function gets
  called by libcurl as soon as there is
  data received that needs to be saved.
  The size of the data pointed to by ptr
  is size multiplied with nmemb, it will
  not be zero terminated. Return the
  number of bytes actually taken care
  of. If that amount differs from the
  amount passed to your function, it'll
  signal an error to the library. This
  will abort the transfer and return
  CURLE_WRITE_ERROR.
  From 7.18.0, the function can return
  CURL_WRITEFUNC_PAUSE which then will
  cause writing to this connection to
  become paused. See curl_easy_pause(3)
  for further details.

This function may be called with zero
  bytes data if the transferred file is
  empty.

.....

Set the userdata argument with the
  CURLOPT_WRITEDATA option.

The callback function will be passed
  as much data as possible in all
  invokes, but you cannot possibly make
  any assumptions. It may be one byte,
  it may be thousands. The maximum
  amount of data that can be passed to
  the write callback is defined in the
  curl.h header file:
  CURL_MAX_WRITE_SIZE.

So your callback could be called many times.
You need to store the data into your own structure which will keep track about the data read so far.

Try this solution:

```<code>#include <stdio.h>
#include <curl/curl.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    size_t size;
    char *payload;
}srvresponse;

size_t callback_func(void *ptr, size_t size, size_t count, void *stream) {
    //printf("%s", (char*) ptr);

    size_t realsize = size * count;
    printf("Chuncksize:%lu\n",realsize);
    srvresponse *ret = (srvresponse*)stream;
    //Increase the payload size
    ret->payload = realloc(ret->payload,ret->size + realsize + 1);
    //Copy the new data
    memcpy(&(ret->payload[ret->size]),ptr,realsize);
    //Update the size
    ret->size += realsize;
    //Terminate the string
    ret->payload[ret->size] = 0;
    printf("Read so far:%s",ret->payload);
    return realsize;

}

int main(void) {
    CURL *curl;

    srvresponse retdata;
    retdata.payload = malloc(1);//We increase the capacity later
    retdata.size = 0;

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://stream.twitter.com/1/statuses/filter.json?track=http");
        curl_easy_setopt(curl, CURLOPT_USERPWD, "user:pass");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback_func);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&retdata);
        curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        curl_global_cleanup();

        if (retdata.payload){
            puts(retdata.payload);
            free(retdata.payload);
        }
    }

    return 0;
}
</code>```

Body:
I'm having a bit of an issue, here is my code (I'm using C):

#include <stdio.h>
#include <curl/curl.h>
#include <stdlib.h>
#include <json/json.h>

size_t callback_func(void *ptr, size_t size, size_t count, void *stream) {
//json_object *json_obj = json_tokener_parse(ptr);
printf ("%s",(char*)ptr);

return count;

}

int main(void)
{
      CURL *curl;
          CURLcode res;

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://stream.twitter.com/1/statuses/filter.json?track=http");
    curl_easy_setopt(curl, CURLOPT_USERPWD, "Firrus:password");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback_func);
    curl_easy_perform(curl);

    /* always cleanup */
    curl_easy_cleanup(curl);

  }

  return 0;
}

The problem is that, every time ptr is printed, three weird (seemingly random) characters are also outputted at the top, e.g. 77D or 6DA. What do these characters mean? How can I remove them?

Body:
In according with the documentation the callback functions works on this way:

Function pointer that should match the
  following prototype: size_t function(
  void *ptr, size_t size, size_t nmemb,
  void *userdata); This function gets
  called by libcurl as soon as there is
  data received that needs to be saved.
  The size of the data pointed to by ptr
  is size multiplied with nmemb, it will
  not be zero terminated. Return the
  number of bytes actually taken care
  of. If that amount differs from the
  amount passed to your function, it'll
  signal an error to the library. This
  will abort the transfer and return
  CURLE_WRITE_ERROR.
  From 7.18.0, the function can return
  CURL_WRITEFUNC_PAUSE which then will
  cause writing to this connection to
  become paused. See curl_easy_pause(3)
  for further details.

This function may be called with zero
  bytes data if the transferred file is
  empty.

.....

Set the userdata argument with the
  CURLOPT_WRITEDATA option.

The callback function will be passed
  as much data as possible in all
  invokes, but you cannot possibly make
  any assumptions. It may be one byte,
  it may be thousands. The maximum
  amount of data that can be passed to
  the write callback is defined in the
  curl.h header file:
  CURL_MAX_WRITE_SIZE.

So your callback could be called many times.
You need to store the data into your own structure which will keep track about the data read so far.

Try this solution:

#include <stdio.h>
#include <curl/curl.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    size_t size;
    char *payload;
}srvresponse;

size_t callback_func(void *ptr, size_t size, size_t count, void *stream) {
    //printf("%s", (char*) ptr);

    size_t realsize = size * count;
    printf("Chuncksize:%lu\n",realsize);
    srvresponse *ret = (srvresponse*)stream;
    //Increase the payload size
    ret->payload = realloc(ret->payload,ret->size + realsize + 1);
    //Copy the new data
    memcpy(&(ret->payload[ret->size]),ptr,realsize);
    //Update the size
    ret->size += realsize;
    //Terminate the string
    ret->payload[ret->size] = 0;
    printf("Read so far:%s",ret->payload);
    return realsize;

}

int main(void) {
    CURL *curl;

    srvresponse retdata;
    retdata.payload = malloc(1);//We increase the capacity later
    retdata.size = 0;

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://stream.twitter.com/1/statuses/filter.json?track=http");
        curl_easy_setopt(curl, CURLOPT_USERPWD, "user:pass");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback_func);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&retdata);
        curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        curl_global_cleanup();

        if (retdata.payload){
            puts(retdata.payload);
            free(retdata.payload);
        }
    }

    return 0;
}


问:
Using grpc+mpi protocol in distributed tensorflow - Error
I have just compiled TensorFlow (master) with MPI support and am now specifying the "grpc+mpi" protocol in the tf.train.Server object. However, when attempting to launch the training procedure, there is always exactly one worker who fails with the error

F ./tensorflow/contrib/mpi/mpi_utils.h:47] Failed to convert worker name to MPI index: ps:0:0

Every time I reproduce the error, it is a different worker that fails to "convert". It is quite suspicious to me that the name that it fails to convert is a "worker" name considering that it actually cannot "convert" a property of the Parameter Server.

The whole training procedure works fine when using the "standard" protocol "grpc".

Each worker as well as the single parameter server run on a dedicated machine (no shared machine).
The OpenMPI version is 2.1.1

How would I approach debugging this? Unfortunately I don't have much knowledge of MPI.

Thanks,

Mat

答:
I met the same problem when I used TensorFlow with MPI support. The reason is that I didn't use the mpirun to launch the training procedure.

For example, my train script is mpi_train.sh:

```<code>#! /bin/bash

host=$(hostname -s)
if [[ $host = "node-1" ]]; then
        job_name=ps
        task_id=0
elif [[ $host = "node-2" ]]; then
        job_name=worker
        task_id=0
elif [[ $host = "node-3" ]]; then
       job_name=worker
       task_id=1
fi

cd /test/models/inception

bazel-bin/inception/imagenet_distributed_train --batch_size=32 --data_dir=/test/data/ILSVRC2012 --job_name=${job_name} --task_id=${task_id} --ps_hosts=10.0.20.14:2276 --worker_hosts=10.0.20.15:2276,10.0.20.16:2276 --protocol=grpc+mpi --max_steps=1020
</code>```

I should use the mpirun to launch my train script:

mpirun -host 10.0.0.14,10.0.0.15,10.0.0.16 /test/mpi_train.sh

Body:
I met the same problem when I used TensorFlow with MPI support. The reason is that I didn't use the mpirun to launch the training procedure.

For example, my train script is mpi_train.sh:

#! /bin/bash

host=$(hostname -s)
if [[ $host = "node-1" ]]; then
        job_name=ps
        task_id=0
elif [[ $host = "node-2" ]]; then
        job_name=worker
        task_id=0
elif [[ $host = "node-3" ]]; then
       job_name=worker
       task_id=1
fi

cd /test/models/inception

bazel-bin/inception/imagenet_distributed_train --batch_size=32 --data_dir=/test/data/ILSVRC2012 --job_name=${job_name} --task_id=${task_id} --ps_hosts=10.0.20.14:2276 --worker_hosts=10.0.20.15:2276,10.0.20.16:2276 --protocol=grpc+mpi --max_steps=1020

I should use the mpirun to launch my train script:

mpirun -host 10.0.0.14,10.0.0.15,10.0.0.16 /test/mpi_train.sh


问:
Packing properties into type object and return it as result of method
I would like to create instance of type object in method, add to It two properties and return object as result of method.

```<code>public object method()
{
TypeOfClassA a;
int b;
if(method(out a, out b))
{
res = new {a=a, b=b};
}
return res;
}
</code>```

Something like this

答:
If you don't want Tuple<T1, T2>, then dynamic is your only choice.

```<code>public dynamic method()
{
    TypeOfClassA a;
    int b;
    if(method(out a, out b))
    {
        var res = new {a=a, b=b};
        return res;
    }

    return null; // You need to return something here. What happens if the if statement is not executed?
}
</code>```

You can call method like this:

```<code>dynamic val = method();
Console.WriteLine(val.a); // or "val.b"
</code>```

Body:
I would like to create instance of type object in method, add to It two properties and return object as result of method.

public object method()
{
TypeOfClassA a;
int b;
if(method(out a, out b))
{
res = new {a=a, b=b};
}
return res;
}

Something like this

Body:
If you don't want Tuple<T1, T2>, then dynamic is your only choice.

public dynamic method()
{
    TypeOfClassA a;
    int b;
    if(method(out a, out b))
    {
        var res = new {a=a, b=b};
        return res;
    }

    return null; // You need to return something here. What happens if the if statement is not executed?
}

You can call method like this:

dynamic val = method();
Console.WriteLine(val.a); // or "val.b"


问:
JSSC writeString return true but device cannot receive
Im using JSSC library to communicate with a hardware device in my project.

My software and my team hardware need to work synchronously (My software needs to display what is currently displayed in the hardware and vice versa)

Everything works perfectly with our team's breadboard, until we make it into a real PCB with buttons mounted.

Our team's currently using this USB-to-Serial adapter for the device: https://www.sparkfun.com/products/14050

When we were doing the testing with the breadboard, it's connected through COM3. The current device's connected through COM5.

My software now can just receive the data from the device and cannot send back a signal when a button in my software is clicked (Actually the writeString method returns true but our device receives nothing)

Let's have a look at some code snippet of my software:

I've got this CONNECT button to open the port and establish the communication:

```<code>private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {
    if (selectedPort != null && selectedPort.isOpened()) {
        // Disconnect
        selectedPort.closePort();
        connectButton.setText("Connect");
    } else { // Connect
        selectedPort = new SerialPort(listPort.getSelectedItem().toString());
        try {
            connectButton.setText("Disconnect");
            selectedPort.openPort();
            selectedPort.setParams(9600, 8, 1, 0, true, false);
            selectedPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
            int mask = SerialPort.MASK_RXCHAR;
            selectedPort.setEventsMask(mask);
            selectedPort.addEventListener(new SerialPortReader());
        } catch (SerialPortException ex) {
            System.out.println(ex);
        }
    }
}
</code>```

I've also got a jcombobox to send a character to the device:

```<code>private void modeListActionPerformed(java.awt.event.ActionEvent evt) {
    try {
        JComboBox cb = (JComboBox) evt.getSource();
        String selectedItem = (String) cb.getSelectedItem();
        switch (selectedItem) {
            case "VOLTAGE_DC":
                dataMode = VOL_DC;
                selectedPort.writeString("v");
                break;
            case "VOLTAGE_AC":
                dataMode = VOL_AC;
                selectedPort.writeString("V");
                break;
            case "CURRENT_DC":
                dataMode = "CUR_DC";
                selectedPort.writeString("i");
                break;
            case "CURRENT_AC":
                dataMode = "CUR_AC";
                selectedPort.writeString("I");
                break;
            case "RESISTANCE":
                dataMode = RES;
                selectedPort.writeString("r");
                break;
            case "RESISTANCE_CON":
                dataMode = CON;
                selectedPort.writeString("c");
                break;
            default:
                break;
        }
        selectedPort.closePort();
        selectedPort.openPort();
        selectedPort.addEventListener(new SerialPortReader());
    } catch (SerialPortException ex) {
        Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
    }
}
</code>```

My SerialPortReader:

```<code>public class SerialPortReader implements SerialPortEventListener {
      @Override
public void serialEvent(SerialPortEvent event) {
    if (event.isRXCHAR() && event.getEventValue() > 0) {
        try {
            byte[] buffer = selectedPort.readBytes(event.getEventValue());
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    update_display_by_buffer(buffer);
            });
        }
        catch (SerialPortException ex) {
            System.out.println(ex);
        }
}
</code>```

Recap few important points:

My software can communicate smoothly with the breadboard while testing (COM3)

My software now can just receive data but not the other way around with the real device (even writeString method return true)

Our real device works perfectly with Putty

What could the reasons for this problem?

Any pointers will be appreciated.

// UPDATED:

Problem's solved by using jSerialComm library

Conclusion:

RXTX is a mess.

JSSC library sucks.

答: I observed same behaviour in another project and sometimes it was due to "not flushing data" after writing to serial port. JSSC does not seem to have any flushing.</p>

Body:
Im using JSSC library to communicate with a hardware device in my project.

My software and my team hardware need to work synchronously (My software needs to display what is currently displayed in the hardware and vice versa)

Everything works perfectly with our team's breadboard, until we make it into a real PCB with buttons mounted.

Our team's currently using this USB-to-Serial adapter for the device: https://www.sparkfun.com/products/14050

When we were doing the testing with the breadboard, it's connected through COM3. The current device's connected through COM5.

My software now can just receive the data from the device and cannot send back a signal when a button in my software is clicked (Actually the writeString method returns true but our device receives nothing)

Let's have a look at some code snippet of my software:

I've got this CONNECT button to open the port and establish the communication:

private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {
    if (selectedPort != null && selectedPort.isOpened()) {
        // Disconnect
        selectedPort.closePort();
        connectButton.setText("Connect");
    } else { // Connect
        selectedPort = new SerialPort(listPort.getSelectedItem().toString());
        try {
            connectButton.setText("Disconnect");
            selectedPort.openPort();
            selectedPort.setParams(9600, 8, 1, 0, true, false);
            selectedPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
            int mask = SerialPort.MASK_RXCHAR;
            selectedPort.setEventsMask(mask);
            selectedPort.addEventListener(new SerialPortReader());
        } catch (SerialPortException ex) {
            System.out.println(ex);
        }
    }
}

I've also got a jcombobox to send a character to the device:

private void modeListActionPerformed(java.awt.event.ActionEvent evt) {
    try {
        JComboBox cb = (JComboBox) evt.getSource();
        String selectedItem = (String) cb.getSelectedItem();
        switch (selectedItem) {
            case "VOLTAGE_DC":
                dataMode = VOL_DC;
                selectedPort.writeString("v");
                break;
            case "VOLTAGE_AC":
                dataMode = VOL_AC;
                selectedPort.writeString("V");
                break;
            case "CURRENT_DC":
                dataMode = "CUR_DC";
                selectedPort.writeString("i");
                break;
            case "CURRENT_AC":
                dataMode = "CUR_AC";
                selectedPort.writeString("I");
                break;
            case "RESISTANCE":
                dataMode = RES;
                selectedPort.writeString("r");
                break;
            case "RESISTANCE_CON":
                dataMode = CON;
                selectedPort.writeString("c");
                break;
            default:
                break;
        }
        selectedPort.closePort();
        selectedPort.openPort();
        selectedPort.addEventListener(new SerialPortReader());
    } catch (SerialPortException ex) {
        Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
    }
}

My SerialPortReader:

public class SerialPortReader implements SerialPortEventListener {
      @Override
public void serialEvent(SerialPortEvent event) {
    if (event.isRXCHAR() && event.getEventValue() > 0) {
        try {
            byte[] buffer = selectedPort.readBytes(event.getEventValue());
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    update_display_by_buffer(buffer);
            });
        }
        catch (SerialPortException ex) {
            System.out.println(ex);
        }
}

Recap few important points:

My software can communicate smoothly with the breadboard while testing (COM3)

My software now can just receive data but not the other way around with the real device (even writeString method return true)

Our real device works perfectly with Putty

What could the reasons for this problem?

Any pointers will be appreciated.

// UPDATED:

Problem's solved by using jSerialComm library

Conclusion:

RXTX is a mess.

JSSC library sucks.


问:
UIDatePicker Click done and display text
I would like to get the date after the UIPicker pop-up and straight away click done button to display the date on "dobTxt.text" without scroll and select the date from UIDatePicker. How to do it?

```<code>   func doneBtnForDate(){

    if (dobTxt.text == "Please select your DOB"){
         //let selectedDate = How to get picker date without scroll it?
         dobTxt.text = selectedDate
    }

    picker.isHidden = true
    toolBar2.isHidden = true
    datePicker.isHidden = true
}
</code>```

答:
Here is objective c Code for it. </p>

```<code>     [datepicker addTarget:self  action:@selector(DateChange:)
            forControlEvents:UIControlEventValueChanged];

    //method for change date

    - (void)DateChange:(id)sender
{
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd-MM-yyyy"];
        label.text = [dateFormatter stringFromDate:datepicker.date];
        date.text=strDate;
}
</code>```

Body:
I would like to get the date after the UIPicker pop-up and straight away click done button to display the date on "dobTxt.text" without scroll and select the date from UIDatePicker. How to do it?

   func doneBtnForDate(){

    if (dobTxt.text == "Please select your DOB"){
         //let selectedDate = How to get picker date without scroll it?
         dobTxt.text = selectedDate
    }

    picker.isHidden = true
    toolBar2.isHidden = true
    datePicker.isHidden = true
}

Body:
Here is objective c Code for it.

     [datepicker addTarget:self  action:@selector(DateChange:)
            forControlEvents:UIControlEventValueChanged];

    //method for change date

    - (void)DateChange:(id)sender
{
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd-MM-yyyy"];
        label.text = [dateFormatter stringFromDate:datepicker.date];
        date.text=strDate;
}


答:
Can you please set dobTxt.inputView = picker in viewDidLoad method

It works fine for me. Hope it will helps you.

Title: UIDatePicker Click done and display text


问:
form_open method not working in codeigniter
I have try to action control/method but form_open method are not working I have loaded helper

hello.php  controller

```<code><?php

class hello extends CI_Controller {

    public function index() {

        $this->load->helper('form');
        $this->load->view("fv");
    }

    public function f_validation() {
        echo "hello";

    }
}

?>
</code>```

fv.php view file

```<code><html>
<head>
<title>My Form</title>
</head>
<body>

    <?php echo form_open('hello/f_validation'); ?>
    <h5>Username</h5>
    <input type="text" name="username" value="">

    <h5>Password</h5>
    <input type="text" name="password" value="" >

    <h5>Password Confirm</h5>
    <input type="text" name="passconf" value="" >

    <h5>Email Address</h5>
    <input type="text" name="email" value="" >

    <div><input type="submit" value="Submit" /></div>

    </form>

</body>
</html>
</code>```

答:
Use Like this

```<code> <?php
    class Hello extends CI_Controller {

    public function __construct()
    {
           parent::__construct();
           $this->load->helper('form');
    }

    public function index()
    {
       $this->load->view("fv");
    }

    public function f_validation()
    {
      echo "hello";

    }
 }
</code>```

See This :

https://www.codeigniter.com/user_guide/general/controllers.html

https://www.codeigniter.com/user_guide/general/helpers.html#loading-a-helper

Body:
I have try to action control/method but form_open method are not working I have loaded helper

hello.php  controller

<?php

class hello extends CI_Controller {

    public function index() {

        $this->load->helper('form');
        $this->load->view("fv");
    }

    public function f_validation() {
        echo "hello";

    }
}

?>

fv.php view file

<title>My Form</title>

    <?php echo form_open('hello/f_validation'); ?>

Username

    <input type="text" name="username" value="">

Password

    <input type="text" name="password" value="" >

Password Confirm

    <input type="text" name="passconf" value="" >

Email Address

    <input type="text" name="email" value="" >

<input type="submit" value="Submit" />

    </form>

Body:
Use Like this

 <?php
    class Hello extends CI_Controller {

    public function __construct()
    {
           parent::__construct();
           $this->load->helper('form');
    }

    public function index()
    {
       $this->load->view("fv");
    }

    public function f_validation()
    {
      echo "hello";

    }
 }

See This :

https://www.codeigniter.com/user_guide/general/controllers.html

https://www.codeigniter.com/user_guide/general/helpers.html#loading-a-helper


问:
Setting a gradient in a text
I want this output:

The two colors are :

```<code><color name="clrc2">#c27a1c</color>
    <color name="clrfe">#fee17f</color>
</code>```

And i have tried this code :

```<code>Shader shader = new LinearGradient(0,100,10,100,
                new int[]{resources.getColor(R.color.clrc2),resources.getColor(R.color.clrfe),resources.getColor(R.color.clrc2)}
                ,new float[]{0.4f,0.2f,0.4f}, Shader.TileMode.MIRROR);
        option_.setTextColor(resources.getColor(R.color.clrc2));
        option_.getPaint().setShader( shader );
</code>```

I am not achieving the desired result.

This is the result I get :

答:
Got the accurate gradient by this code :

```<code>Shader textShader = new LinearGradient(0, 8, 0, 18,
            new int[]{Color.parseColor("#c27a1c"), Color.parseColor("#fee17f")},
            new float[]{0, 1}, Shader.TileMode.MIRROR);
    option_.setTextColor(resources.getColor(R.color.clrfe));
    option_.getPaint().setShader(textShader);
</code>```

Ref from : https://stackoverflow.com/a/16958396/5327912

Title: Setting a gradient in a text

Body:
I want this output:

The two colors are :

<color name="clrc2">#c27a1c</color>
    <color name="clrfe">#fee17f</color>

And i have tried this code :

Shader shader = new LinearGradient(0,100,10,100,
                new int[]{resources.getColor(R.color.clrc2),resources.getColor(R.color.clrfe),resources.getColor(R.color.clrc2)}
                ,new float[]{0.4f,0.2f,0.4f}, Shader.TileMode.MIRROR);
        option_.setTextColor(resources.getColor(R.color.clrc2));
        option_.getPaint().setShader( shader );

I am not achieving the desired result.

This is the result I get :

Body:
Got the accurate gradient by this code :

Shader textShader = new LinearGradient(0, 8, 0, 18,
            new int[]{Color.parseColor("#c27a1c"), Color.parseColor("#fee17f")},
            new float[]{0, 1}, Shader.TileMode.MIRROR);
    option_.setTextColor(resources.getColor(R.color.clrfe));
    option_.getPaint().setShader(textShader);

Ref from : https://stackoverflow.com/a/16958396/5327912


答:
The problem is that in your Equals call you are comparing the char to a string ("4"):

```<code>char Lastchar = test[test.Length - 1];
Assert.IsTrue((Lastchar).Equals("4"));
</code>```

This returns false because the types differ. If you compare to a char of '4' it will return true:

```<code>Assert.IsTrue((Lastchar).Equals('4'));
</code>```

Title: Unable to get last character of string

Body:
** Code: **

String test = "32132SSS654";
char Lastchar = test[test.Length - 1];

Assert.IsTrue((Lastchar).Equals("4"));

I am trying to get the last character from the string then doing assert but it returns me something extra like 52 with the last character 4 and that's why my assert getting fail.

Body:
The problem is that in your Equals call you are comparing the char to a string ("4"):

char Lastchar = test[test.Length - 1];
Assert.IsTrue((Lastchar).Equals("4"));

This returns false because the types differ. If you compare to a char of '4' it will return true:

Assert.IsTrue((Lastchar).Equals('4'));


答:
https://codepen.io/anon/pen/EbMBqE

set location.href

```<code>window.onload = function() {
  console.log("load");
  location.href = "#popup1";
};
</code>```

window.onload = function() {
  console.log("load");
  location.href = "#popup1";
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: Arial, sans-serif;
  background: url(http://www.shukatsu-note.com/wp-content/uploads/2014/12/computer-564136_1280.jpg) no-repeat;
  background-size: cover;
  height: 100vh;
}

h1 {
  text-align: center;
  font-family: Tahoma, Arial, sans-serif;
  color: #06D85F;
  margin: 80px 0;
}

.box {
  width: 40%;
  margin: 0 auto;
  background: rgba(255,255,255,0.2);
  padding: 35px;
  border: 2px solid #fff;
  border-radius: 20px/50px;
  background-clip: padding-box;
  text-align: center;
}

.button {
  font-size: 1em;
  padding: 10px;
  color: #fff;
  border: 2px solid #06D85F;
  border-radius: 20px/50px;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.3s ease-out;
}
.button:hover {
  background: #06D85F;
}

.overlay {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  transition: opacity 500ms;
  visibility: hidden;
  opacity: 0;
}
.overlay:target {
  visibility: visible;
  opacity: 1;
}

.popup {
  margin: 70px auto;
  padding: 20px;
  background: #fff;
  border-radius: 5px;
  width: 30%;
  position: relative;
  transition: all 5s ease-in-out;
}

.popup h2 {
  margin-top: 0;
  color: #333;
  font-family: Tahoma, Arial, sans-serif;
}
.popup .close {
  position: absolute;
  top: 20px;
  right: 30px;
  transition: all 200ms;
  font-size: 30px;
  font-weight: bold;
  text-decoration: none;
  color: #333;
}
.popup .close:hover {
  color: #06D85F;
}
.popup .content {
  max-height: 30%;
  overflow: auto;
}

@media screen and (max-width: 700px){
  .box{
    width: 70%;
  }
  .popup{
    width: 70%;
  }
}</code>```

Popup/Modal Windows without JavaScript

 Let me Pop up

Here i am

  ×

   Thank to pop me out of that button, but now i'm done so you can close this window.

```

Title: automatic href to div when page loaded

Body:
I have html code

Popup/Modal Windows without JavaScript

Let me Pop up

Here i am

    ×

        Thank to pop me out of that button, but now i'm done so you can

I want popup window show when page is loaded. not waiting when i click to button. How to make with javascript or jquery? This example i found in here

Body:
https://codepen.io/anon/pen/EbMBqE

set location.href

window.onload = function() {
  console.log("load");
  location.href = "#popup1";
};

window.onload = function() {
  console.log("load");
  location.href = "#popup1";
};

body {
  font-family: Arial, sans-serif;
  background: url(http://www.shukatsu-note.com/wp-content/uploads/2014/12/computer-564136_1280.jpg) no-repeat;
  background-size: cover;
  height: 100vh;
}

h1 {
  text-align: center;
  font-family: Tahoma, Arial, sans-serif;
  color: #06D85F;
  margin: 80px 0;
}

.box {
  width: 40%;
  margin: 0 auto;
  background: rgba(255,255,255,0.2);
  padding: 35px;
  border: 2px solid #fff;
  border-radius: 20px/50px;
  background-clip: padding-box;
  text-align: center;
}

.button {
  font-size: 1em;
  padding: 10px;
  color: #fff;
  border: 2px solid #06D85F;
  border-radius: 20px/50px;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.3s ease-out;
}
.button:hover {
  background: #06D85F;
}

.overlay {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  transition: opacity 500ms;
  visibility: hidden;
  opacity: 0;
}
.overlay:target {
  visibility: visible;
  opacity: 1;
}

.popup {
  margin: 70px auto;
  padding: 20px;
  background: #fff;
  border-radius: 5px;
  width: 30%;
  position: relative;
  transition: all 5s ease-in-out;
}

.popup h2 {
  margin-top: 0;
  color: #333;
  font-family: Tahoma, Arial, sans-serif;
}
.popup .close {
  position: absolute;
  top: 20px;
  right: 30px;
  transition: all 200ms;
  font-size: 30px;
  font-weight: bold;
  text-decoration: none;
  color: #333;
}
.popup .close:hover {
  color: #06D85F;
}
.popup .content {
  max-height: 30%;
  overflow: auto;
}

@media screen and (max-width: 700px){
  .box{
    width: 70%;
  }
  .popup{
    width: 70%;
  }
}

<h1>Popup/Modal Windows without JavaScript</h1>
<div class="box">
 <a class="button" href="#popup1">Let me Pop up</a>
</div>

<div id="popup1" class="overlay">
 <div class="popup">
  <h2>Here i am</h2>
  <a class="close" href="#">&times;</a>
  <div class="content">
   Thank to pop me out of that button, but now i'm done so you can close this window.
  </div>
 </div>
</div>


问:
How to expand allocated memory in place
Is there something like std::realloc but do nothing if it fails to expand the existing memory (of course it will let you know it failed)?

I mean truly expand in place. Not copy to a newly created memory chunk.

答:
Contrary to what other answers say, the function you need could be provided by the C standard ibrary. It isn't for some reason or other.

It was considered for an adition to the C standard, see e.g. http://www.open-std.org/JTC1/SC22/wg14/www/docs/n1527.pdf (search for try_realloc). I don't know if the C committee is still pursuing this.

Bottom line, there's no such function as of now.

Title: How to expand allocated memory in place


问:
update perticular view in layout without affecting other views of layout

I want to update only Linearlayout which between toolbar and edittext
after every 3 sec, without affecting edittext, Is it possible? I have tried all ways but when schedular calls update method ,it clears edittext entered data also. How to stop this. Please Help me

答:
LinearLayout ll = (LinearLayout) findViewById(R.id.chatList);

ll.invalidate();


问:
Posting multiple Photos to one post
I have been trying to create an application which needs multiple photos to be attached to one post. These are the following attempts i tried,

First i used facebook-node-sdk which JS SDK to achieve different functionality, but Official Js Sdk does't have option for file to upload, when then i moved to attaching/inserting photo itself to HTTP POST with the help of form-data, with the following code-

```<code>    var form = new FormData();
    form.append('file', fs.createReadStream(picPaths[0]));
    form.append('message', "Hello"); //Put message
    var ACCESS_TOKEN = "ACCESS_TOKEN";
    var options = {
        method: 'post',
        host: 'graph.facebook.com',
        path:  '{Object-ID}/photos' + '?access_token=' + ACCESS_TOKEN,
        headers: form.getHeaders(),
    }

    var request = https.request(options, function(res) {
        console.log(res, false, null);
    });

    form.pipe(request);

    request.on('error', function(error) {
        console.log(error);
    });
</code>```

This works with one photo.

But as you can see in this github.com/Thuzi/facebook-node-sdk/issues/113 which i started, it is not possible to attach more than one photo.

So as mentioned by dantman i stated looking in batch process, which can be found developers.facebook.com/docs/graph-api/making-multiple-requests titled under Uploading binary data. The one thing that hits and give me hope is this one statement.

The attached_files property can take a comma separated list of attachment names in its value.

Note That (batching with photos) also is not possible with this library or JS SDK (Please correct me if i am wrong)

You can do post images with curl like this,

```<code>curl -F 'access_token=ACCESS_TOKEN' -F 'batch=[{"method":"POST","relative_url":"{Object-Id}/photos","body":"message=Test Post","attached_files":"file1"}]' -F 'file1=@image1' -F 'file2=@image2' https://graph.facebook.com
</code>```

The above code posts with one image

So my question is this, it possible to attach multiple images/binary_files to the post with the help of curl, something like ..."attached_files":"file1,file2"... as suggested by docs, please help me with this problem and if you have already done this can you please post the snapshot of your code.

Thanks, Ravi

答:
I finally figured out how.

So first, read the section here titled "Publishing a multi-photo post with uploaded photos": https://developers.facebook.com/docs/graph-api/reference/page/photos/#Creating

What it says is basically correct, however, it is not in JavaScript. Also, they don't emphasize enough an important step: You have to set "published" to "false" for the image you upload, for it to then be attachable to the post that gets created.

So anyway, here is the working code -- in JavaScript, and with "published" correctly set to false:

```<code>async function PostImageToFacebook(token, filename, mimeType, imageDataBlob, message) {
    var fd = new FormData();
    fd.append("access_token", token);
    fd.append("source", imageDataBlob);
    //fd.append("message", "photo message for " + filename);
    fd.append("no_story", "true");
    //fd.append("privacy", "SELF");
    fd.append("published", "false");

    // Upload image to facebook without story(post to feed)
    let uploadPhotoResponse = await $.ajax({
         url: "https://graph.facebook.com/me/photos?access_token=" + token,
         type: "POST",
         data: fd,
         processData: false,
         contentType: false,
         cache: false
    });
    console.log(`Uploaded photo "${filename}": `, uploadPhotoResponse);

    let uploadPhotoResponse2 = await $.ajax({
        url: "https://graph.facebook.com/me/photos?access_token=" + token,
        type: "POST",
        data: fd,
        processData: false,
        contentType: false,
        cache: false
  });
  console.log(`Uploaded photo "${filename}": `, uploadPhotoResponse2);

    let makePostResponse = await $.ajax({
        "async": true,
        "crossDomain": true,
        "url": "https://graph.facebook.com/v2.11/me/feed",
        "method": "POST",
        "headers": {
            "cache-control": "no-cache",
            "content-type": "application/x-www-form-urlencoded"
        },
        "data": {
            "message": "Testing multi-photo post2!",
            "attached_media[0]": `{"media_fbid":${uploadPhotoResponse.id}}`,
            "attached_media[1]": `{"media_fbid":${uploadPhotoResponse2.id}}`,
            "access_token": token
        }
    });
    console.log(`Made post: `, makePostResponse);
}
</code>```

The code above currently just uploads the same image twice, then attaches both to the new post. Obviously, in real world usage you would replace the data in the second photo-upload with a different image.

Anyway, to use the function, just call it like so:

```<code>function dataURItoBlob(dataURI) {
    var byteString = atob(dataURI.split(",")[1]);
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
         ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ab], {type: "image/png"});
}

let imageDataURI = GetImageDataURIFromSomewhere();
let imageBlob = dataURItoBlob(imageDataURI);

PostImageToFacebook(fbToken, "some_filename", "image/png", imageBlob, window.location.href);
</code>```

Title: Posting multiple Photos to one post

Body:
I have been trying to create an application which needs multiple photos to be attached to one post. These are the following attempts i tried,

First i used facebook-node-sdk which JS SDK to achieve different functionality, but Official Js Sdk does't have option for file to upload, when then i moved to attaching/inserting photo itself to HTTP POST with the help of form-data, with the following code-

    var form = new FormData();
    form.append('file', fs.createReadStream(picPaths[0]));
    form.append('message', "Hello"); //Put message
    var ACCESS_TOKEN = "ACCESS_TOKEN";
    var options = {
        method: 'post',
        host: 'graph.facebook.com',
        path:  '{Object-ID}/photos' + '?access_token=' + ACCESS_TOKEN,
        headers: form.getHeaders(),
    }

    var request = https.request(options, function(res) {
        console.log(res, false, null);
    });

    form.pipe(request);

    request.on('error', function(error) {
        console.log(error);
    });

This works with one photo.

But as you can see in this github.com/Thuzi/facebook-node-sdk/issues/113 which i started, it is not possible to attach more than one photo.

So as mentioned by dantman i stated looking in batch process, which can be found developers.facebook.com/docs/graph-api/making-multiple-requests titled under Uploading binary data. The one thing that hits and give me hope is this one statement.

The attached_files property can take a comma separated list of attachment names in its value.

Note That (batching with photos) also is not possible with this library or JS SDK (Please correct me if i am wrong)

You can do post images with curl like this,

curl -F 'access_token=ACCESS_TOKEN' -F 'batch=[{"method":"POST","relative_url":"{Object-Id}/photos","body":"message=Test Post","attached_files":"file1"}]' -F 'file1=@image1' -F 'file2=@image2' https://graph.facebook.com

The above code posts with one image

So my question is this, it possible to attach multiple images/binary_files to the post with the help of curl, something like ..."attached_files":"file1,file2"... as suggested by docs, please help me with this problem and if you have already done this can you please post the snapshot of your code.

Thanks, Ravi

Body:
I finally figured out how.

So first, read the section here titled "Publishing a multi-photo post with uploaded photos": https://developers.facebook.com/docs/graph-api/reference/page/photos/#Creating

What it says is basically correct, however, it is not in JavaScript. Also, they don't emphasize enough an important step: You have to set "published" to "false" for the image you upload, for it to then be attachable to the post that gets created.

So anyway, here is the working code -- in JavaScript, and with "published" correctly set to false:

async function PostImageToFacebook(token, filename, mimeType, imageDataBlob, message) {
    var fd = new FormData();
    fd.append("access_token", token);
    fd.append("source", imageDataBlob);
    //fd.append("message", "photo message for " + filename);
    fd.append("no_story", "true");
    //fd.append("privacy", "SELF");
    fd.append("published", "false");

    // Upload image to facebook without story(post to feed)
    let uploadPhotoResponse = await $.ajax({
         url: "https://graph.facebook.com/me/photos?access_token=" + token,
         type: "POST",
         data: fd,
         processData: false,
         contentType: false,
         cache: false
    });
    console.log(`Uploaded photo "${filename}": `, uploadPhotoResponse);

    let uploadPhotoResponse2 = await $.ajax({
        url: "https://graph.facebook.com/me/photos?access_token=" + token,
        type: "POST",
        data: fd,
        processData: false,
        contentType: false,
        cache: false
  });
  console.log(`Uploaded photo "${filename}": `, uploadPhotoResponse2);

    let makePostResponse = await $.ajax({
        "async": true,
        "crossDomain": true,
        "url": "https://graph.facebook.com/v2.11/me/feed",
        "method": "POST",
        "headers": {
            "cache-control": "no-cache",
            "content-type": "application/x-www-form-urlencoded"
        },
        "data": {
            "message": "Testing multi-photo post2!",
            "attached_media[0]": `{"media_fbid":${uploadPhotoResponse.id}}`,
            "attached_media[1]": `{"media_fbid":${uploadPhotoResponse2.id}}`,
            "access_token": token
        }
    });
    console.log(`Made post: `, makePostResponse);
}

The code above currently just uploads the same image twice, then attaches both to the new post. Obviously, in real world usage you would replace the data in the second photo-upload with a different image.

Anyway, to use the function, just call it like so:

function dataURItoBlob(dataURI) {
    var byteString = atob(dataURI.split(",")[1]);
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
         ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ab], {type: "image/png"});
}

let imageDataURI = GetImageDataURIFromSomewhere();
let imageBlob = dataURItoBlob(imageDataURI);

PostImageToFacebook(fbToken, "some_filename", "image/png", imageBlob, window.location.href);


问:
Move to the latest file in the jumplist
With vim, I like to use C-o and C-i to move through the jumplist and I want to use the same to move to the previous and the next file with <leader>o and <leader>i.

I know I can use the buffer but the list is not always the same.

I tried to use EnhancedJump but I have some bugs and it seems to be obsolete.

Do you have solution?

答:
It would be possible with functions like that:

```<code>function! JumpBack()
  let l:cfile=expand('%')
  let l:nfile=l:cfile
  while l:cfile == l:nfile
    execute 'normal ' . 1 . "\<c-o>"
    let l:nfile=expand('%')
  endwhile
endfunction
</code>```

*Note this could be written cleaner, it is mostly pasted togheter.

However it seems like a sledgehammer method for me, maybe there is a better one.

Update

It was not surprising to hear, that this would lead to an endless loop if the jumplist only contains one file. Here is a better solution:

```<code>function! JumpBack()
  let l:cfile=expand('%')
  let l:jl = split(execute('jumps'), '\n')
  let l:jumpcounter = 0
  for l:jumpline in reverse(l:jl)
    let l:jumpcounter = l:jumpcounter + 1
    let l:nfile = split(l:jumpline, '\s')[-1]
    if l:cfile != l:nfile
      execute 'normal '. l:jumpcounter . "\<c-o>"
      return
    endif
  endfor
endfunction
</code>```

Title: Move to the latest file in the jumplist

Body:
It would be possible with functions like that:

function! JumpBack()
  let l:cfile=expand('%')
  let l:nfile=l:cfile
  while l:cfile == l:nfile
    execute 'normal ' . 1 . "\<c-o>"
    let l:nfile=expand('%')
  endwhile
endfunction

*Note this could be written cleaner, it is mostly pasted togheter.

However it seems like a sledgehammer method for me, maybe there is a better one.

Update

It was not surprising to hear, that this would lead to an endless loop if the jumplist only contains one file. Here is a better solution:

function! JumpBack()
  let l:cfile=expand('%')
  let l:jl = split(execute('jumps'), '\n')
  let l:jumpcounter = 0
  for l:jumpline in reverse(l:jl)
    let l:jumpcounter = l:jumpcounter + 1
    let l:nfile = split(l:jumpline, '\s')[-1]
    if l:cfile != l:nfile
      execute 'normal '. l:jumpcounter . "\<c-o>"
      return
    endif
  endfor
endfunction


问:
I would want to write regEx for character to accept from a-zA-z0-9 (from 1-to any) with mandatory one special character from . OR _
I tried this:

```<code>^(?=.*[a-zA-Z0-9])(?=[.|_]).$
</code>```

I am not sure where I am going wrong

答: You can try this one <code>^[a-zA-Z0-9[.][_][-]]+</code> and any special character is between two parenthesis </p>

Body:
I tried this:

^(?=.*[a-zA-Z0-9])(?=[.|_]).$

I am not sure where I am going wrong

Body: You can try this one ^[a-zA-Z0-9[.][_][-]]+ and any special character is between two parenthesis


问:
ScrollView unable to display image which passed from another VC
I need to display the image pass in from the another ViewController

first,I have tested using only ImageView to display the image and it works as below:

Thanks. Your help is greatly appreciated.

```<code>class ViewController: UIViewController, UIScrollViewDelegate {

    @IBOutlet weak var TempImgView: UIImgeView!
    var passInImg: UIImage?

    override func viewDidLoad() {

        super.viewDidLoad()

       TempImgView.image = passInImg!

   }
</code>```

When I use UIScrollView ( for scrolling the large passInImg) , below code not working

Probelm:

error : fatal error: unexpectedly found nil while unwrapping an
  optional value

But I have tested the pass in image  in the above code.

what need to be done with the scrollView?

Should be used in viewDidLoad?

class ViewController: UIViewController, UIScrollViewDelegate {

```<code>@IBOutlet weak var myUIScrollView: UIScrollView!

var myImgView: UIImageView!
var passInImg: UIImage?

override func viewDidLoad() {
    super.viewDidLoad()

    self.myUIScrollView.maximumZoomScale = 10.0

    self.myUIScrollView.minimumZoomScale = 1.0

    self.myUIScrollView.delegate = self

    myImgView.image = passInImg!

    self.myUIScrollView.addSubview(myImgView)

}

func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {

    return myImgView
}
</code>```

答:
The difference is the way you are declaring the UIImageView.
In the first case:

```<code>@IBOutlet weak var TempImgView: UIImageView!
</code>```

TempImgView is an @IBOutlet and hence initialised whenever the storyboard view/xib is loaded.

But then when you are using the scrollview, you have declared the UIImageView as a class variable and not @IBOutlet.

```<code>var myImgView: UIImageView!
</code>```

It has to initialised before you try to access it.
Try:

```<code>myImgView = UIImageView()
myImgView.image = passInImg!
</code>```

Body:
I need to display the image pass in from the another ViewController

first,I have tested using only ImageView to display the image and it works as below:

Thanks. Your help is greatly appreciated.

class ViewController: UIViewController, UIScrollViewDelegate {

    @IBOutlet weak var TempImgView: UIImgeView!
    var passInImg: UIImage?

    override func viewDidLoad() {

        super.viewDidLoad()

       TempImgView.image = passInImg!

   }

When I use UIScrollView ( for scrolling the large passInImg) , below code not working

Probelm:

error : fatal error: unexpectedly found nil while unwrapping an
  optional value

But I have tested the pass in image  in the above code.

what need to be done with the scrollView?

Should be used in viewDidLoad?

class ViewController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var myUIScrollView: UIScrollView!

var myImgView: UIImageView!
var passInImg: UIImage?

override func viewDidLoad() {
    super.viewDidLoad()

    self.myUIScrollView.maximumZoomScale = 10.0

    self.myUIScrollView.minimumZoomScale = 1.0

    self.myUIScrollView.delegate = self

    myImgView.image = passInImg!

    self.myUIScrollView.addSubview(myImgView)

}

func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {

    return myImgView
}

Body:
The difference is the way you are declaring the UIImageView.
In the first case:

@IBOutlet weak var TempImgView: UIImageView!

TempImgView is an @IBOutlet and hence initialised whenever the storyboard view/xib is loaded.

But then when you are using the scrollview, you have declared the UIImageView as a class variable and not @IBOutlet.

var myImgView: UIImageView!

It has to initialised before you try to access it.
Try:

myImgView = UIImageView()
myImgView.image = passInImg!


问:
Unable to get last character of string

** Code: **

```<code>String test = "32132SSS654";
char Lastchar = test[test.Length - 1];

Assert.IsTrue((Lastchar).Equals("4"));
</code>```

I am trying to get the last character from the string then doing assert but it returns me something extra like 52 with the last character 4 and that's why my assert getting fail.

答:
52 is the ASCII value of the character- 4 and you are comparing it wrongly to "4" which is a string type.

In C#, when you enclose a value in double quotes that is a string value. When you put them in single quotes that becomes a char value and within single quotes you can put any single char value.

Change your code to-

```<code>Assert.IsTrue((Lastchar).Equals('4'));
</code>```

Assert not only compares the value but also compares the type of the object whether they are equal. So just in case if you compare something like-

```<code>Assert.IsTrue((4).Equals('4'));
</code>```

would return false since it compares int value to a char value which would never be equal.

Title: Unable to get last character of string

Body:
52 is the ASCII value of the character- 4 and you are comparing it wrongly to "4" which is a string type.

In C#, when you enclose a value in double quotes that is a string value. When you put them in single quotes that becomes a char value and within single quotes you can put any single char value.

Change your code to-

Assert.IsTrue((Lastchar).Equals('4'));

Assert not only compares the value but also compares the type of the object whether they are equal. So just in case if you compare something like-

Assert.IsTrue((4).Equals('4'));

would return false since it compares int value to a char value which would never be equal.


问:
Converting an image_tag into a link that goes to the destroy route
I would like to convert this line of code into a link that goes to the destroy route in my routes table.  When this picture is pressed it will delete the current photo.

```<code><%= image_tag @user.avatar.avatarpic %>
</code>```

The route is as follows:

```<code>user_avatar DELETE /users/:user_id/avatars/:id(.:format) avatars#destroy
</code>```

The Avatar controller is as follow:

```<code>class AvatarsController < ApplicationController

  def create
    @user = User.find(params[:user_id])
    @avatar = Avatar.new(avatar_params)
    @avatar.user = @user
    @avatar.save
    # Three lines above can be replaced with
    # @user.create_avatar(params)
    redirect_to user_path(@user)
  end

private

def avatar_params
  params.require(:avatar).permit(:avatarpic)
end

end
</code>```

Currently I have an if/else statement that will display a default image if an avatar photo isn't available:

```<code><% if @user.avatar.present? %>
  <%= image_tag @user.avatar.avatarpic %>
<% else %>
  <%= image_tag 'user.png' %>
  <a href="#" class="add-image" data-toggle="modal" data-
  target="#avatarpic">
    Add a Picture
  </a>
<% end %>
</code>```

I would also like for a message to display once the mouse is hovering over the current avatar photo.  It will say something to the effect of "Upload a different image".  Once pressed, there should be a warning that asks the user "Are you sure you would like to delete this image?".  Thank you for your help.

答:
Following the route you give above, please try this:</p>

```<code><%= link_to user_avatar_path, method: :delete, data: { confirm: 'Are you sure' } do %>
  <%= image_tag @user.avatar.avatarpic %>
<% end %>
</code>```

Body:
I would like to convert this line of code into a link that goes to the destroy route in my routes table.  When this picture is pressed it will delete the current photo.

<%= image_tag @user.avatar.avatarpic %>

The route is as follows:

user_avatar DELETE /users/:user_id/avatars/:id(.:format) avatars#destroy

The Avatar controller is as follow:

class AvatarsController < ApplicationController

  def create
    @user = User.find(params[:user_id])
    @avatar = Avatar.new(avatar_params)
    @avatar.user = @user
    @avatar.save
    # Three lines above can be replaced with
    # @user.create_avatar(params)
    redirect_to user_path(@user)
  end

private

def avatar_params
  params.require(:avatar).permit(:avatarpic)
end

end

Currently I have an if/else statement that will display a default image if an avatar photo isn't available:

<% if @user.avatar.present? %>
  <%= image_tag @user.avatar.avatarpic %>
<% else %>
  <%= image_tag 'user.png' %>

    Add a Picture

<% end %>

I would also like for a message to display once the mouse is hovering over the current avatar photo.  It will say something to the effect of "Upload a different image".  Once pressed, there should be a warning that asks the user "Are you sure you would like to delete this image?".  Thank you for your help.

Body:
Following the route you give above, please try this:

<%= link_to user_avatar_path, method: :delete, data: { confirm: 'Are you sure' } do %>
  <%= image_tag @user.avatar.avatarpic %>
<% end %>