问:
Parsing JSON and sorting by outputted dates in Java
This REST query gives among other stuff, the created_at dates. I want to parse the output to get all the dates and then sort them. The lines in question i need to parse look like

```<code>  "created_at": "2013-01-08T20:11:48Z",
</code>```

Query here

```<code>https://api.github.com/search/repositories?q=language:Java
</code>```

Is there an efficient way of doing this?

My code sofar

```<code> public static String processRestResponse(String language){
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("https://api.github.com/search/repositories?q=language:" + language);
    HttpResponse response = null;
    BufferedReader rd = null;
    try {
        response = client.execute(request);
        rd = new BufferedReader
            (new InputStreamReader(
                    response.getEntity().getContent()));
    } catch (IOException e) {
        e.printStackTrace();
    }
    String line = "";

    String output  = language;
    try {
        while ((line = rd.readLine()) != null) {
            output += "\n" + line.substring(line.indexOf("\""), line.indexOf(",")) + "\n";
        }
    }catch (IOException e){}

    return output;
}
</code>```

答:
All right, I'll bite:

```<code>import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonStructure;
import javax.json.JsonValue;

public class StackOverflow44316515{

    public static void main(final String[] args) throws Exception{
        final StackOverflow44316515 example = new StackOverflow44316515();

        // Get data:
        final JsonObject jsonLangObjs = example.getLanguages("java");

        // Copy items into a mutable array:
        final JsonArray items = jsonLangObjs.getJsonArray("items");
        final JsonObject[] itemsArray = items.toArray(new JsonObject[items.size()]);

        // Sort the array:
        Arrays.sort(itemsArray, new Comparator<JsonValue>(){
            @Override
            public int compare(final JsonValue o1, final JsonValue o2){
                return ((JsonObject)o1).getString("created_at")
                    .compareTo(((JsonObject)o2).getString("created_at"));
            }

        });

        // Re-wrap in a list API for convenience (optional):
        final List<JsonObject> itemsArrayList = Arrays.asList(itemsArray);

        // Print sample:
        for(final JsonObject jo : itemsArrayList){
            System.out.println(jo.getString("created_at") + " - " + jo.getString("full_name"));
        }
    }

    public JsonObject getLanguages(final String language) throws Exception{
        final URL url = new URL("https://api.github.com/search/repositories?q=language:"
            + URLEncoder.encode(language, "UTF-8")
            + "&per_page=10");

        final HttpURLConnection huc = (HttpURLConnection)url.openConnection();
        if(huc.getResponseCode() != 200){
            throw new Exception("Error calling web service: "
                +  huc.getResponseCode() + " - " + huc.getResponseMessage());
        }

        try(final InputStream is = huc.getInputStream()){
            final JsonStructure json = Json.createReader(is).read();
            return (JsonObject)json;
        }
    }

}
</code>```

Output:

```<code>2010-02-08T13:20:56Z - elastic/elasticsearch
2010-09-06T21:39:43Z - square/retrofit
2012-07-23T13:42:55Z - square/okhttp
2013-01-08T20:11:48Z - ReactiveX/RxJava
2013-03-05T08:18:59Z - JakeWharton/butterknife
2013-07-08T22:52:33Z - bumptech/glide
2014-04-25T14:29:47Z - PhilJay/MPAndroidChart
2014-05-29T16:23:17Z - google/guava
2014-08-09T16:45:18Z - iluwatar/java-design-patterns
2015-04-29T23:54:16Z - square/leakcanary
</code>```

ISO-8601-formatted dates are fortunately properly sorted by their lexicographical ordering - so for a simple exercise as this, we don't even need to first parse them to Java data objects or such.

See also: https://xkcd.com/1179/

Make note of GitHub's server-side pagination here - necessary to not flood you with all 3.2+ million results at once.  I limited the default of 30 results to 10 for this example.  If you truly need to analyze ALL of the results, I'll leave this as an exercise to the reader.  https://developer.github.com/v3/guides/traversing-with-pagination/ has some additional details around this.

This sample code assumes that the created_at value always exists for all records.  Unless this is an API guarantee by GitHub (and even if), additional checks should be added here for production code.

Note the URL-encoding of the language argument, to help prevent against injection attacks (assuming the "language" parameter is not trusted).

Note the use of Java's built-in java.net classes - no need for a 3rd-party HTTP library here.

Note that this code doesn't catch any exceptions it can't handle.  An empty catch block, or even a catch block that only outputs the exception is almost always of no benefit to anyone.  ("OK, now what?")  I.E., do you really want the code to proceed on as if nothing bad happened?

This code also builds each set of JSON results into an in-memory object model (JsonArray of JsonObjects).  While the simplest for the example here, a more efficient implementation would make use of the streaming interfaces, e.g. JsonParser.  See also:

http://docs.oracle.com/javaee/7/api/index.html?javax/json/package-tree.html

http://docs.oracle.com/javaee/7/api/index.html?javax/json/stream/package-summary.html

How can I import javax.json in eclipse

Body:
This REST query gives among other stuff, the created_at dates. I want to parse the output to get all the dates and then sort them. The lines in question i need to parse look like

  "created_at": "2013-01-08T20:11:48Z",

Query here

https://api.github.com/search/repositories?q=language:Java

Is there an efficient way of doing this?

My code sofar

 public static String processRestResponse(String language){
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("https://api.github.com/search/repositories?q=language:" + language);
    HttpResponse response = null;
    BufferedReader rd = null;
    try {
        response = client.execute(request);
        rd = new BufferedReader
            (new InputStreamReader(
                    response.getEntity().getContent()));
    } catch (IOException e) {
        e.printStackTrace();
    }
    String line = "";

    String output  = language;
    try {
        while ((line = rd.readLine()) != null) {
            output += "\n" + line.substring(line.indexOf("\""), line.indexOf(",")) + "\n";
        }
    }catch (IOException e){}

    return output;
}

Body:
All right, I'll bite:

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonStructure;
import javax.json.JsonValue;

public class StackOverflow44316515{

    public static void main(final String[] args) throws Exception{
        final StackOverflow44316515 example = new StackOverflow44316515();

        // Get data:
        final JsonObject jsonLangObjs = example.getLanguages("java");

        // Copy items into a mutable array:
        final JsonArray items = jsonLangObjs.getJsonArray("items");
        final JsonObject[] itemsArray = items.toArray(new JsonObject[items.size()]);

        // Sort the array:
        Arrays.sort(itemsArray, new Comparator<JsonValue>(){
            @Override
            public int compare(final JsonValue o1, final JsonValue o2){
                return ((JsonObject)o1).getString("created_at")
                    .compareTo(((JsonObject)o2).getString("created_at"));
            }

        });

        // Re-wrap in a list API for convenience (optional):
        final List<JsonObject> itemsArrayList = Arrays.asList(itemsArray);

        // Print sample:
        for(final JsonObject jo : itemsArrayList){
            System.out.println(jo.getString("created_at") + " - " + jo.getString("full_name"));
        }
    }

    public JsonObject getLanguages(final String language) throws Exception{
        final URL url = new URL("https://api.github.com/search/repositories?q=language:"
            + URLEncoder.encode(language, "UTF-8")
            + "&per_page=10");

        final HttpURLConnection huc = (HttpURLConnection)url.openConnection();
        if(huc.getResponseCode() != 200){
            throw new Exception("Error calling web service: "
                +  huc.getResponseCode() + " - " + huc.getResponseMessage());
        }

        try(final InputStream is = huc.getInputStream()){
            final JsonStructure json = Json.createReader(is).read();
            return (JsonObject)json;
        }
    }

}

Output:

2010-02-08T13:20:56Z - elastic/elasticsearch
2010-09-06T21:39:43Z - square/retrofit
2012-07-23T13:42:55Z - square/okhttp
2013-01-08T20:11:48Z - ReactiveX/RxJava
2013-03-05T08:18:59Z - JakeWharton/butterknife
2013-07-08T22:52:33Z - bumptech/glide
2014-04-25T14:29:47Z - PhilJay/MPAndroidChart
2014-05-29T16:23:17Z - google/guava
2014-08-09T16:45:18Z - iluwatar/java-design-patterns
2015-04-29T23:54:16Z - square/leakcanary

ISO-8601-formatted dates are fortunately properly sorted by their lexicographical ordering - so for a simple exercise as this, we don't even need to first parse them to Java data objects or such.

See also: https://xkcd.com/1179/

Make note of GitHub's server-side pagination here - necessary to not flood you with all 3.2+ million results at once.  I limited the default of 30 results to 10 for this example.  If you truly need to analyze ALL of the results, I'll leave this as an exercise to the reader.  https://developer.github.com/v3/guides/traversing-with-pagination/ has some additional details around this.

This sample code assumes that the created_at value always exists for all records.  Unless this is an API guarantee by GitHub (and even if), additional checks should be added here for production code.

Note the URL-encoding of the language argument, to help prevent against injection attacks (assuming the "language" parameter is not trusted).

Note the use of Java's built-in java.net classes - no need for a 3rd-party HTTP library here.

Note that this code doesn't catch any exceptions it can't handle.  An empty catch block, or even a catch block that only outputs the exception is almost always of no benefit to anyone.  ("OK, now what?")  I.E., do you really want the code to proceed on as if nothing bad happened?

This code also builds each set of JSON results into an in-memory object model (JsonArray of JsonObjects).  While the simplest for the example here, a more efficient implementation would make use of the streaming interfaces, e.g. JsonParser.  See also:

http://docs.oracle.com/javaee/7/api/index.html?javax/json/package-tree.html

http://docs.oracle.com/javaee/7/api/index.html?javax/json/stream/package-summary.html

How can I import javax.json in eclipse


来源: stackexchange

问:
How to find the name of an Oracle Sequence used by a column in SQLAlchemy?
```
    class Foo(Base):
        __tablename__ = 'foo'
        id = Column(Integer, Sequence('foo_id_seq'), primary_key=True)
        bar = Column(String(10))
```

Is it possible to reflect the name of the the sequence foo_id_seq from Foo.c ?

答:
If by Foo.c you mean an instance of Foo then:

```<code>f = Foo()
print(f.__table__.c['id'].default.name)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
    class Foo(Base):
        __tablename__ = 'foo'
        id = Column(Integer, Sequence('foo_id_seq'), primary_key=True)
        bar = Column(String(10))

Is it possible to reflect the name of the the sequence foo_id_seq from Foo.c ?

Body:
If by Foo.c you mean an instance of Foo then:

f = Foo()
print(f.__table__.c['id'].default.name)


问:
Xamarin Live Player does not connect after scanning barcode by mobile device
I have tried to try new features of Xamarin live player but when I scanned the QR Code just scanned and did nothing.

I checked connection of all device and I am sure all device in same network.

I closed every thing  and re-start all device

I checked all available update.

In xamarin's web site write something like that "The network may be tightly secured (such as some corporate networks), blocking the ports needed by Xamarin Live Player."

How can I fix this problem do you have any idea guys ?

答:
Phone and laptop must be on the same network.
From the same network you should be able to access internet (they provide no information for the purpos of this requirement)
They assume that your internal networking does not have port restrictions like firewalls. I observe that port 8084 is used by VS 2017.

Your network might restrict port  8090

is the only port specific to Xamarin Live connection.
This information is not officialy confirmed (there is a lot of fog around).

https://forums.xamarin.com/discussion/95435/which-ports-are-needed-for-live-player

Other ports used by Xamarin are 80 and 443 and 5000:

https://forums.xamarin.com/discussion/13862/ports-required-for-installation-behind-firewall

If you are on a Mac, For Xamarin Mac Agent port 22:

https://developer.xamarin.com/guides/cross-platform/getting_started/installation/firewall/


问:
How could I enable print statement in pytest looponfail mode?
I execute py.test like this : py.test -s -f, -f is looponfail mode and -s is --capture=no mode.

But print() statement is allowed only when the test is fail. If all tests succeeded, all print() in all codes doesn't work.

How could I enable print() statement even in looponfail mode?

Python 3.4

Py.test 2.7.2

答: You should just update to newer pytest. Looks like this problem was fixed in pytest=2.9.0.


问:
Set string while series is a boolean value?
I would like to set a string in Column C while values in Column B are >= 2 (yes if>= is True, no if >= is False). The output should be as follows:

```<code>    A B   C
1   A 2 'yes'
2   B 3 'yes'
3   C 4 'yes'
4   D 5 'yes'
5   A 6 'yes'
6   B 7 'yes'
7   C 0 'no'
8   D 1 'no'
9   A 2 'yes'
10  B 3 'yes'
11  C 4 'yes'
12  D 0 'no'
</code>```

So far I have tried to implement nested loops, which are far too slow:

```<code>i= 0
for row in range(0, len(df)-1):
    if df['B'][i] >= 2:
        if df['B'][i] >= 2:
            df['C'][i] = 'yes'
        elif df['B'][i] >= 2:
            df['C'][i] = 'yes'
</code>```

答:
This can also be done simply by creating a Boolean valued column 'C' as per your condition:

```<code>df['C'] = df['B'] >= 2
</code>```

But if you only want 'Yes' and 'No' values then you can convert your Boolean valued column to string and apply replace function.

```<code>df['C'] = df['C'].astype(str)
df['C'].replace('False','No', inplace=True)
df['C'].replace('True','Yes', inplace=True)
</code>```

Body:
I would like to set a string in Column C while values in Column B are >= 2 (yes if>= is True, no if >= is False). The output should be as follows:

    A B   C
1   A 2 'yes'
2   B 3 'yes'
3   C 4 'yes'
4   D 5 'yes'
5   A 6 'yes'
6   B 7 'yes'
7   C 0 'no'
8   D 1 'no'
9   A 2 'yes'
10  B 3 'yes'
11  C 4 'yes'
12  D 0 'no'

So far I have tried to implement nested loops, which are far too slow:

i= 0
for row in range(0, len(df)-1):
    if df['B'][i] >= 2:
        if df['B'][i] >= 2:
            df['C'][i] = 'yes'
        elif df['B'][i] >= 2:
            df['C'][i] = 'yes'

Body:
This can also be done simply by creating a Boolean valued column 'C' as per your condition:

df['C'] = df['B'] >= 2

But if you only want 'Yes' and 'No' values then you can convert your Boolean valued column to string and apply replace function.

df['C'] = df['C'].astype(str)
df['C'].replace('False','No', inplace=True)
df['C'].replace('True','Yes', inplace=True)


问:
Correct Output for java method
I am trying to create a method that counts the number of times a specified character appears in a given string, by printing the sentence and the specified character and its count.

This is what I have completed so far:-

```<code>import java.util.Scanner;

public class Program4 {

public int count ( String sentence, char letter)
 {
   int times = 0;
   for (int x=0;x<sentence.length();x++)
 {
if (sentence.charAt(x) ==letter){times++;}

 }
return times;
 }

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Program4 program4 = new Program4();
}
program4.count("Hello World",'o');
scan.close();
}
}
</code>```

I understand I need a "system.output.println" but I don't know what value goes inside to get the output I am looking for. I would appreciate any help, I am beginner with java. Thank you.

答:
it works, you had compile time error in code</p>

```<code>import java.util.Scanner;

public class Program4 {

    public int count(String sentence, char letter) {
        int times = 0;
        for (int x = 0; x < sentence.length(); x++) {
            if (sentence.charAt(x) == letter) {
                times++;
            }

        }
        return times;
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        Program4 program4 = new Program4();

        int timesCount =    program4.count("Hello World", 'o');
         System.out.println("count is :" + timesCount);
        scan.close();
    }
}
</code>```

Title: Correct Output for java method

Body:
I am trying to create a method that counts the number of times a specified character appears in a given string, by printing the sentence and the specified character and its count.

This is what I have completed so far:-

import java.util.Scanner;

public class Program4 {

public int count ( String sentence, char letter)
 {
   int times = 0;
   for (int x=0;x<sentence.length();x++)
 {
if (sentence.charAt(x) ==letter){times++;}

 }
return times;
 }

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Program4 program4 = new Program4();
}
program4.count("Hello World",'o');
scan.close();
}
}

I understand I need a "system.output.println" but I don't know what value goes inside to get the output I am looking for. I would appreciate any help, I am beginner with java. Thank you.

Body:
it works, you had compile time error in code

import java.util.Scanner;

public class Program4 {

    public int count(String sentence, char letter) {
        int times = 0;
        for (int x = 0; x < sentence.length(); x++) {
            if (sentence.charAt(x) == letter) {
                times++;
            }

        }
        return times;
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        Program4 program4 = new Program4();

        int timesCount =    program4.count("Hello World", 'o');
         System.out.println("count is :" + timesCount);
        scan.close();
    }
}


问:
How to display a message box on PyQT4?
I'd like a MessageBox to display when I click a button on my simple PyQT application. How can I declare two textboxes and have a MessageBox display with the text from both textboxes?

Here's my code far:

```<code>import sys
from PyQt4 import QtGui, QtCore

class myWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        #The setGeometry method is used to position the control.
        #Order: X, Y position - Width, Height of control.
        self.setGeometry(300, 300, 500, 350)
        self.setWindowTitle("Sergio's QT Application.")
        self.setWindowIcon(QtGui.QIcon('menuScreenFolderShadow.png'))

        self.setToolTip('<i>Welcome</i> to the <b>first</b> app ever!')
        QtGui.QToolTip.setFont(QtGui.QFont('Helvetica', 12))

        txtFirstName = QtGui.?
        txtLastName = QtGui.?

        btnQuit = QtGui.QPushButton('Exit Application', self)
        btnQuit.setGeometry(340, 300, 150, 35)

        self.connect(btnQuit, QtCore.SIGNAL('clicked()'),
                    QtGui.qApp, QtCore.SLOT('quit()'))

app = QtGui.QApplication(sys.argv)
mainForm = myWindow()
mainForm.show()
sys.exit(app.exec_())
</code>```

答:
```<code>from PyQt4 import QtGui, QtCore

class Window( QtGui.QWidget ):

    def __init__( self ):
        QtGui.QWidget.__init__( self )

        msgBox = QtGui.QMessageBox( self )
        msgBox.setIcon( QtGui.QMessageBox.Information )
        msgBox.setText( "Do not stare into laser with remaining eye" )

        msgBox.setInformativeText( "Do you really want to disable safety enforcement?" )
        msgBox.addButton( QtGui.QMessageBox.Yes )
        msgBox.addButton( QtGui.QMessageBox.No )

        msgBox.setDefaultButton( QtGui.QMessageBox.No )
        ret = msgBox.exec_()

        if ret == QtGui.QMessageBox.Yes:
            print( "Yes" )
            return
        else:
            print( "No" )
            return

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication( sys.argv )
    window = Window()
    # window.show()
    sys.exit( app.exec_() )
</code>```

Source:

http://pyqt.sourceforge.net/Docs/PyQt4/qmessagebox.html

http://www.programcreek.com/python/example/62361/PyQt4.QtGui.QMessageBox

OwnerDisplayName: delete

ContentLicense: CC BY-SA 2.5

Title: How to display a message box on PyQT4?

Body:
I'd like a MessageBox to display when I click a button on my simple PyQT application. How can I declare two textboxes and have a MessageBox display with the text from both textboxes?

Here's my code far:

import sys
from PyQt4 import QtGui, QtCore

class myWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        #The setGeometry method is used to position the control.
        #Order: X, Y position - Width, Height of control.
        self.setGeometry(300, 300, 500, 350)
        self.setWindowTitle("Sergio's QT Application.")
        self.setWindowIcon(QtGui.QIcon('menuScreenFolderShadow.png'))

        self.setToolTip('Welcome to the first app ever!')
        QtGui.QToolTip.setFont(QtGui.QFont('Helvetica', 12))

        txtFirstName = QtGui.?
        txtLastName = QtGui.?

        btnQuit = QtGui.QPushButton('Exit Application', self)
        btnQuit.setGeometry(340, 300, 150, 35)

        self.connect(btnQuit, QtCore.SIGNAL('clicked()'),
                    QtGui.qApp, QtCore.SLOT('quit()'))

app = QtGui.QApplication(sys.argv)
mainForm = myWindow()
mainForm.show()
sys.exit(app.exec_())

Body:
from PyQt4 import QtGui, QtCore

class Window( QtGui.QWidget ):

    def __init__( self ):
        QtGui.QWidget.__init__( self )

        msgBox = QtGui.QMessageBox( self )
        msgBox.setIcon( QtGui.QMessageBox.Information )
        msgBox.setText( "Do not stare into laser with remaining eye" )

        msgBox.setInformativeText( "Do you really want to disable safety enforcement?" )
        msgBox.addButton( QtGui.QMessageBox.Yes )
        msgBox.addButton( QtGui.QMessageBox.No )

        msgBox.setDefaultButton( QtGui.QMessageBox.No )
        ret = msgBox.exec_()

        if ret == QtGui.QMessageBox.Yes:
            print( "Yes" )
            return
        else:
            print( "No" )
            return

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication( sys.argv )
    window = Window()
    # window.show()
    sys.exit( app.exec_() )

Source:

http://pyqt.sourceforge.net/Docs/PyQt4/qmessagebox.html

http://www.programcreek.com/python/example/62361/PyQt4.QtGui.QMessageBox


Title: Simplify data from conflicting sources

Body:
I have data from some data sources of questionable reliability:

 date        | value      |  source
 ===================================
 2011-09-30  |  10.9910   |  best
 2011-12-31  |  11.5000   |  ok
 2011-12-31  |  11.5290   |  best
 2012-03-31  |  12.8477   |  ok
 2012-03-31  |  12.4677   |  worst
 2012-06-30  |  -1.5      |  unacceptable

And I want to clean it up into a simple time series, with an order of preference based on the data source:  "best" beats "ok" beats "worst", and throw away "unacceptable".  In my example:

 date        | value
 ========================
 2011-09-30  | 10.9910
 2011-12-31  | 11.5290
 2012-03-31  | 12.8477
 2012-06-30  | NA           # or just skip this line

Any ideas on how to do this nicely?  The dput for my sample data is:

df = structure(list(date = structure(c(15247, 15339, 15339, 15430, 15430, 15491, 15613, 15613, 15705, 15795, 15795, 15886, 15978, 15978, 15978, 16070, 16070, 16070, 16160, 16160), class = "Date"),
    value = c(10.991, 11.500, 11.529, 12.8477, 12.4677, 11.542, 12.1203, 12.1146, 12.5053, 13.3556, 13.3628, 13.3372, 13.844, 13.844, 13.8419, 15.3403, 15.3403, 15.3306, 15.202, 15.202    ),
    source = c("best", "ok", "best", "ok", "worst", "ok", "ok", "worst", "ok", "ok", "worst", "unacceptable", "ok", "best", "worst", "ok", "best", "worst", "ok", "best")),
    row.names = c(NA, 20L),
    .Names = c("date", "value", "source"),
    class = "data.frame")

Body:
You can transform source to factor and compare them.

library(dplyr)
df %>%
  mutate(source=factor(source, c("best", "ok", "worst"))) %>%
  group_by(date) %>%
  top_n(-1, source) %>%
  ungroup()

# A tibble: 10 x 3
         date   value source
       <date>   <dbl> <fctr>
 1 2011-09-30 10.9910   best
 2 2011-12-31 11.5290   best
 3 2012-03-31 12.8477     ok
 4 2012-05-31 11.5420     ok
 5 2012-09-30 12.1203     ok
 6 2012-12-31 12.5053     ok
 7 2013-03-31 13.3556     ok
 8 2013-09-30 13.8440   best
 9 2013-12-31 15.3403   best
10 2014-03-31 15.2020   best


问:
How to select option in select list using jquery
i have a form that has select element

```<code><select name="adddisplaypage[]" id="adddisplaypage" multiple="multiple">
    <option value="all" label="all">all</option>
    <option value="index" label="index">index</option>
    <option value="tour" label="tour">tour</option>
    <option value="aboutus" label="about us">about us</option>
    <option value="contactus" label="contact us">contact us</option>
    <option value="destination" label="destination">destination</option>
    <option value="reservation" label="reservation">reservation</option>
</select>
</code>```

can anyone help me to select this option (multiple select) on click i.e the option gets selected when clicked, and deselected if selected on click.

答:
I realized I may have misunderstood your question. Something like the following should work, though I'm not sure about browser support:</p>

```<code>$('#adddisplaypage option').click(function(e) {
  e.preventDefault();
  var self = $(this);

  if(self.attr('selected') == '') {
    self.attr('selected', 'selected');
  } else {
    self.attr('selected', '');
  }
});
</code>```

Body:
i have a form that has select element

<select name="adddisplaypage[]" id="adddisplaypage" multiple="multiple">
    <option value="all" label="all">all</option>
    <option value="index" label="index">index</option>
    <option value="tour" label="tour">tour</option>
    <option value="aboutus" label="about us">about us</option>
    <option value="contactus" label="contact us">contact us</option>
    <option value="destination" label="destination">destination</option>
    <option value="reservation" label="reservation">reservation</option>
</select>

can anyone help me to select this option (multiple select) on click i.e the option gets selected when clicked, and deselected if selected on click.

Body:
I realized I may have misunderstood your question. Something like the following should work, though I'm not sure about browser support:

$('#adddisplaypage option').click(function(e) {
  e.preventDefault();
  var self = $(this);

  if(self.attr('selected') == '') {
    self.attr('selected', 'selected');
  } else {
    self.attr('selected', '');
  }
});


问:
r - ggplot2 - Add differences to grouped bar charts
I am plotting the following data on ggplot:

```<code>library(ggplot2)

DF <- structure(list(Type = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L), .Label = c("Observed", "Simulated"), class = "factor"),
    variable = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L), .Label = c("EM to V6",
    "V6 to R0", "R0 to R4", "R4 to R9"), class = "factor"), value = c(28,
    30, 29, 35, 32, 34, 26, 29)), row.names = c(NA, -8L), .Names = c("Type",
"variable", "value"), class = "data.frame")

ggplot(DF, aes(variable, value)) +
      geom_bar(aes(fill = Type), position = "dodge", stat="identity", width=.5) +
      geom_text(aes(label=value, group=Type), position=position_dodge(width=0.5), vjust=-0.5) +
      theme_bw(base_size = 18) +
      ylab('Duration (days)') + xlab('Growth stages')
</code>```

I was wondering if there is any graphical way to add the differences between each group of bars to the chart?

This is the data frame with the differences to be added:

```<code>DF2 <- data.frame(variable=c("EM to V6", "V6 to R0", "R0 to R4", "R4 to R9"), value=c(2,6,2,3)
</code>```

The final chart would look somewhat like this (notice the coloured bars):

source: https://www.excelcampus.com/charts/variance-clustered-column-bar-chart/

Is that possible to do using ggplot?

答:
As rawr suggested, you can add a layer of bars behind the current ones with a slightly smaller width:

```<code>library(tidyverse)
diff_df = DF %>%
    group_by(variable) %>%
    spread(Type, value) %>%
    mutate(diff = Simulated - Observed)

ggplot(DF, aes(variable, value)) +
    geom_bar(aes(y = Simulated), data = diff_df, stat = "identity", fill = "grey80", width = 0.4) +
    geom_bar(aes(fill = Type), position = "dodge", stat="identity", width=.5) +
    geom_text(aes(label=value, group=Type), position=position_dodge(width=0.5), vjust=-0.5) +
    geom_text(aes(label = diff, y = Simulated), vjust=-0.5, data = diff_df, hjust = 2, colour = scales::muted("red")) +
    theme_bw(base_size = 18) +
    ylab('Duration (days)') + xlab('Growth stages')
</code>```

Updated code to deal with Observed sometimes being higher than Simulated:

```<code>library(tidyverse)
diff_df = DF %>%
    group_by(variable) %>%
    spread(Type, value) %>%
    mutate(diff = Simulated - Observed,
           max_y = max(Simulated, Observed),
           sim_higher = Simulated > Observed)

ggplot(DF, aes(variable, value)) +
    geom_bar(aes(y = max_y), data = diff_df, stat = "identity", fill = "grey80", width = 0.4) +
    geom_bar(aes(fill = Type), position = "dodge", stat="identity", width=.5) +
    geom_text(aes(label=value, group=Type), position=position_dodge(width=0.5), vjust=-0.5) +
    geom_text(aes(label = diff, y = max_y), vjust=-0.5, data = diff_df %>% filter(sim_higher),
              hjust = 2, colour = scales::muted("red")) +
    geom_text(aes(label = diff, y = max_y), vjust=-0.5, data = diff_df %>% filter(!sim_higher),
              hjust = -1, colour = scales::muted("red")) +
    theme_bw(base_size = 18) +
    ylab('Duration (days)') + xlab('Growth stages')
</code>```

Body:
I am plotting the following data on ggplot:

library(ggplot2)

DF <- structure(list(Type = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L), .Label = c("Observed", "Simulated"), class = "factor"),
    variable = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L), .Label = c("EM to V6",
    "V6 to R0", "R0 to R4", "R4 to R9"), class = "factor"), value = c(28,
    30, 29, 35, 32, 34, 26, 29)), row.names = c(NA, -8L), .Names = c("Type",
"variable", "value"), class = "data.frame")

ggplot(DF, aes(variable, value)) +
      geom_bar(aes(fill = Type), position = "dodge", stat="identity", width=.5) +
      geom_text(aes(label=value, group=Type), position=position_dodge(width=0.5), vjust=-0.5) +
      theme_bw(base_size = 18) +
      ylab('Duration (days)') + xlab('Growth stages')

I was wondering if there is any graphical way to add the differences between each group of bars to the chart?

This is the data frame with the differences to be added:

DF2 <- data.frame(variable=c("EM to V6", "V6 to R0", "R0 to R4", "R4 to R9"), value=c(2,6,2,3)

The final chart would look somewhat like this (notice the coloured bars):

source: https://www.excelcampus.com/charts/variance-clustered-column-bar-chart/

Is that possible to do using ggplot?

Body:
As rawr suggested, you can add a layer of bars behind the current ones with a slightly smaller width:

library(tidyverse)
diff_df = DF %>%
    group_by(variable) %>%
    spread(Type, value) %>%
    mutate(diff = Simulated - Observed)

ggplot(DF, aes(variable, value)) +
    geom_bar(aes(y = Simulated), data = diff_df, stat = "identity", fill = "grey80", width = 0.4) +
    geom_bar(aes(fill = Type), position = "dodge", stat="identity", width=.5) +
    geom_text(aes(label=value, group=Type), position=position_dodge(width=0.5), vjust=-0.5) +
    geom_text(aes(label = diff, y = Simulated), vjust=-0.5, data = diff_df, hjust = 2, colour = scales::muted("red")) +
    theme_bw(base_size = 18) +
    ylab('Duration (days)') + xlab('Growth stages')

Updated code to deal with Observed sometimes being higher than Simulated:

library(tidyverse)
diff_df = DF %>%
    group_by(variable) %>%
    spread(Type, value) %>%
    mutate(diff = Simulated - Observed,
           max_y = max(Simulated, Observed),
           sim_higher = Simulated > Observed)

ggplot(DF, aes(variable, value)) +
    geom_bar(aes(y = max_y), data = diff_df, stat = "identity", fill = "grey80", width = 0.4) +
    geom_bar(aes(fill = Type), position = "dodge", stat="identity", width=.5) +
    geom_text(aes(label=value, group=Type), position=position_dodge(width=0.5), vjust=-0.5) +
    geom_text(aes(label = diff, y = max_y), vjust=-0.5, data = diff_df %>% filter(sim_higher),
              hjust = 2, colour = scales::muted("red")) +
    geom_text(aes(label = diff, y = max_y), vjust=-0.5, data = diff_df %>% filter(!sim_higher),
              hjust = -1, colour = scales::muted("red")) +
    theme_bw(base_size = 18) +
    ylab('Duration (days)') + xlab('Growth stages')


问:
How to replace/shuffle one column with another in R?
I am very new to R and I was wondering that is there way to shuffle two columns in matrix?
I have a matrix of 800 x 12. I want to replace column 1 by column 2 and column 2 by column 1. Can anyone help me, please?</p>

Body:
before <- data.frame(c1=1:3, c2=4:6)
after <- before[,c("c2", "c1")]


问:
aggregation parameter in log-normal distribution
I want to know if it is possible to get an aggregation parameter from a log-normal distribution. Usually, in ecology, it is used the aggregation parameter k from a negative binomial, this parameter measures the amount of clustering, or aggregation, or heterogeneity, in the data: a smaller k means more heterogeneity. The variance of the negative binomial distribution is μ+ μ2/k, and so as k becomes large the variance approaches the mean and the distribution approaches the Poisson distribution. In R the aggregation parameter is called the size parameter (Bolker, 2008).

When I fit my data in fitdistr my data fits better a log-normal distribution when compared to negative binomial, gamma and Poisson.

According to Anscombe, the logarithmic series is obtained by a limiting process from the negative binomial considering a sample of N reading letting N tend to infinity and k to zero and neglecting the zero readings.

I wonder if it is possible to get the aggregation parameter from a lognormal distribution using sdlog and meanlog or should I use the aggregation parameter k from a negative binomial given that a log-normal would be the result of a small k? Thanks in advance.

Reference:
Bolker Benjamin M.(2008) Ecological Models and Data in R. Princeton University Press

答:
It is somewhat unusual question, but if I understood correctly, you have a log-normal fit, so there is a curve with known mu and sigma

If you pretend it is neg-binomial, it also has two parameters n and p. So the good way you could try to find size (n) is to find mean and variance

For Neg-Binomial

```<code>mean = n*q/p
var  = n*q/p^2, where q = 1-p
</code>```

Taking mean and variance for log-normal from the link above

```<code>mean/var = p = exp(- mu - sigma^2/2) / [exp(sigma^2) - 1]
q = 1 - p
n = mean * p / q = exp(mu + sigma^2/2) * exp(- mu - sigma^2/2) / [exp(sigma^2) - 1] / q = 1 / ([exp(sigma^2) - 1] * q) = 1 / (exp(sigma^2) - 1 - exp(- mu - sigma^2/2))
</code>```

Please check my math carefully...

UPDATE

There is no one single solution for this problem. For example, to get n and p from log-normal, you could try to match mode and variance instead of mean and variance as I did

Body:
It is somewhat unusual question, but if I understood correctly, you have a log-normal fit, so there is a curve with known mu and sigma

If you pretend it is neg-binomial, it also has two parameters n and p. So the good way you could try to find size (n) is to find mean and variance

For Neg-Binomial

mean = n*q/p
var  = n*q/p^2, where q = 1-p

Taking mean and variance for log-normal from the link above

mean/var = p = exp(- mu - sigma^2/2) / [exp(sigma^2) - 1]
q = 1 - p
n = mean * p / q = exp(mu + sigma^2/2) * exp(- mu - sigma^2/2) / [exp(sigma^2) - 1] / q = 1 / ([exp(sigma^2) - 1] * q) = 1 / (exp(sigma^2) - 1 - exp(- mu - sigma^2/2))

Please check my math carefully...

UPDATE

There is no one single solution for this problem. For example, to get n and p from log-normal, you could try to match mode and variance instead of mean and variance as I did


问:
jQuery how to bind onclick event to dynamically added HTML element
I want to bind an onclick event to an element I insert dynamically with jQuery

But It never runs the binded function. I'd be happy if you can point out why this example is not working and how I can get it to run properly:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

          <title>test of click binding</title>

Test of click binding

problem: to bind a click event to an element I append via JQuery.

The link is created, then added here below:

Another is added here below:

        ```

EDIT: I edited the example to contain two elements the method is inserted to. In that case, the alert() call is never executed. (thanks to @Daff for pointing that out in a comment)

答:
```<code>    function load_tpl(selected=""){
        $("#load_tpl").empty();
        for(x in ds_tpl){
            $("#load_tpl").append('<li><a id="'+ds_tpl[x]+'" href="#" >'+ds_tpl[x]+'</a></li>');
        }
        $.each($("#load_tpl a"),function(){
            $(this).on("click",function(e){
                alert(e.target.id);
            });
        });
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to bind an onclick event to an element I insert dynamically with jQuery

But It never runs the binded function. I'd be happy if you can point out why this example is not working and how I can get it to run properly:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

          <title>test of click binding</title>

Test of click binding

problem: to bind a click event to an element I append via JQuery.

The link is created, then added here below:

Another is added here below:

EDIT: I edited the example to contain two elements the method is inserted to. In that case, the alert() call is never executed. (thanks to @Daff for pointing that out in a comment)


问:
Centering two divs in a wrapper
I am trying to center #left and #center inside #wrapper like this:

I am trying to get #center to be in the actual center of #wrapper both horizontally and vertically, and that #left will be in a slight margin to his left. How do I achieve that?

.c {
  border: 1px solid black;
  margin-left: auto;
  margin-right: auto;
  width: 60vw;
  height: 80vh;
  margin-top: 13vh;
}

#wrapper {
  height: 13vh;
  margin-top: 2vh;
  border: 1px solid blue;
}

#center {
  display: inline-block;
  width: 12vw;
  height: 10vh;
  border: 1px solid red;
}

#left {
  display: inline-block;
  width: 13vh;
  height: 13vh;
  border: 1px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="c">
  <div>content content content</div>
  <div>content content content</div>

  <div id="wrapper">
    <div id="left">left</div>
    <div id="center">center</div>

  </div>
  <div>content content content</div>
  <div>content content content</div></code>```

Jsfiddle: https://jsfiddle.net/y6r585jk/2/

答:
This works for your problem..

First apply some flex attributes to the wrapper to center the items..

```<code>#wrapper {
display: flex;
justify-content: center;
align-content: center;
border: 1px solid blue;
}
</code>```

THis putts everything in the center..

next use align-eslf to center vertically.

```<code>#center {
display: inline-block;
align-self: center;
</code>```

Finally add the margin.. I have added 1% to test..

```<code>#center {
display: inline-block;
align-self: center;
margin-left: 1%;
</code>```

I have this..

Title: Centering two divs in a wrapper

Body:
I am trying to center #left and #center inside #wrapper like this:

I am trying to get #center to be in the actual center of #wrapper both horizontally and vertically, and that #left will be in a slight margin to his left. How do I achieve that?

.c {
  border: 1px solid black;
  margin-left: auto;
  margin-right: auto;
  width: 60vw;
  height: 80vh;
  margin-top: 13vh;
}

#wrapper {
  height: 13vh;
  margin-top: 2vh;
  border: 1px solid blue;
}

#center {
  display: inline-block;
  width: 12vw;
  height: 10vh;
  border: 1px solid red;
}

#left {
  display: inline-block;
  width: 13vh;
  height: 13vh;
  border: 1px solid green;
}

content content content

content content content

left

center

content content content

content content content

Jsfiddle: https://jsfiddle.net/y6r585jk/2/

Body:
This works for your problem..

First apply some flex attributes to the wrapper to center the items..

#wrapper {
display: flex;
justify-content: center;
align-content: center;
border: 1px solid blue;
}

THis putts everything in the center..

next use align-eslf to center vertically.

#center {
display: inline-block;
align-self: center;

Finally add the margin.. I have added 1% to test..

#center {
display: inline-block;
align-self: center;
margin-left: 1%;

I have this..


问:
What is the purpose of the res.render callback argument in Express 4.0 in Node.js?
What is the purpose of the res.render callback argument?

In which case would one want to use such a callback argument, since a template is already assigned as the first argument?

Here's the code from the documentation:

```<code>// send the rendered view to the client
res.render('index');

// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', function(err, html) {
  res.send(html);
});

// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function(err, html) {
  // ...
});
</code>```

I understand the purpose of the first two arguments, but not the last.

答:
With the callback, you can intercept the rendered template before sending it on.  You might want to minify it or otherwise modify it before sending to the client.

From the documentation:

If provided, the method returns both the possible error and rendered string, but does not perform an automated response.

Body:
What is the purpose of the res.render callback argument?

In which case would one want to use such a callback argument, since a template is already assigned as the first argument?

Here's the code from the documentation:

// send the rendered view to the client
res.render('index');

// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', function(err, html) {
  res.send(html);
});

// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function(err, html) {
  // ...
});

I understand the purpose of the first two arguments, but not the last.


问:
Bash scripts extremely slow to start on OSX
I'm having a problem where my bash scripts take an extremely long time to start.  At first I thought that it was something in the script itself, but a quick experiment disproved that.

This is the example script

```<code>#!/bin/bash
echo 'ping'
</code>```

When I run it

```<code>$ time ./script.sh
</code>```

I get

```<code>ping

real    0m12.018s
user    0m0.002s
sys    0m0.002s
</code>```

(I've even seen it go up to 17 seconds...) What's incredibly strange is that when I run it the second time, it goes instantly.

```<code>ping

real    0m0.004s
user    0m0.002s
sys 0m0.002s
</code>```

But when I edit the file again, it's back to the long wait.

```<code>$ echo 'echo test' >> gbr.sh
$ time ./gbr.sh
ping
test

real    0m13.021s
user    0m0.003s
sys 0m0.003s
</code>```

It's almost like bash is compiling my script or something.  Is there any way to debug this?  It also doesn't seem to be anything with my .bash_profile - if I just put an echo on the first line of .bash_profile I still only see that after 10+ seconds.

I've tried this in iTerm2 and in native Terminal - both have exactly the same issue.  This is on macOS Sierra - 10.12.3

答:
I had the same issue on my work machine, running macOS Sierra 10.12.5 and 10.12.6, and I confirmed that @charles-duffy is right. My company's anti-malware is the problem. They are using a daemon called Confer by Carbon Black for endpoint security.

Run this command to see if the problem stops:

```<code>launchctl unload /Library/LaunchDaemons/com.confer.sensor.daemon.plist
</code>```

I think Confer is taking a fingerprint of every new program it sees and tries to compare it to a blacklist before allowing it to run. It looks like it times out after a second (trying to register the fingerprint online?), and something is making it try over and over again, yielding longer delays of integer seconds. This makes newly modified programs launch slowly, although speeds return to normal after the fingerprint has been taken.

Example runs

Here's how the problem manifested on my work laptop. As time went on, sometimes the delay increased, but always by an integer number of seconds at a time. If Confer remembers the program from before, there will be no delay.

bash scripts

```<code>$ bash --norc --noprofile -l  # make sure rc scripts don't interfere

bash-3.2$ echo exit > exit.sh && chmod +x exit.sh

bash-3.2$ time ./exit.sh

real    0m1.004s
user    0m0.001s
sys 0m0.002s

bash-3.2$ time ./exit.sh

real    0m0.002s
user    0m0.001s
sys 0m0.001s
</code>```

There were no problems running commands provided to bash -c:

```<code>bash-3.2$ time bash -c exit

real    0m0.008s
user    0m0.002s
sys 0m0.003s
</code>```

awk scripts

But the problem did affect awk scripts:

```<code>bash-3.2$ printf '%s\n' '#!/usr/bin/env awk -f' 'BEGIN { exit 0; }' > test.awk && chmod +x test.awk

bash-3.2$ time ./test.awk

real    0m4.010s
user    0m0.002s
sys 0m0.001s

bash-3.2$ time ./test.awk

real    0m0.005s
user    0m0.002s
sys 0m0.001s
</code>```

Compiled binaries

It even affected compiled C and Golang code:

```<code>bash-3.2$ printf '%s\n' '#include "stdio.h"' 'int main() {' 'printf("Hello, world!\n");' 'return 0;' '}' > hello.c && gcc -o hello hello.c

bash-3.2$ time ./hello
Hello, world!

real    0m4.006s
user    0m0.001s
sys 0m0.001s

bash-3.2$ time ./hello
Hello, world!

real    0m0.004s
user    0m0.001s
sys 0m0.001s

bash-3.2$ printf '%s\n' 'package main' 'import "fmt"' 'func main() {' 'fmt.Println("test")' '}' > test.go && go build -o test ./test.go

bash-3.2$ time ./test
test

real    0m4.018s
user    0m0.001s
sys 0m0.003s

bash-3.2$ time ./test
test

real    0m0.005s
user    0m0.001s
sys 0m0.002s
</code>```

Body:
I'm having a problem where my bash scripts take an extremely long time to start.  At first I thought that it was something in the script itself, but a quick experiment disproved that.

This is the example script

#!/bin/bash
echo 'ping'

When I run it

$ time ./script.sh

I get

ping

real    0m12.018s
user    0m0.002s
sys    0m0.002s

(I've even seen it go up to 17 seconds...) What's incredibly strange is that when I run it the second time, it goes instantly.

ping

real    0m0.004s
user    0m0.002s
sys 0m0.002s

But when I edit the file again, it's back to the long wait.

$ echo 'echo test' >> gbr.sh
$ time ./gbr.sh
ping
test

real    0m13.021s
user    0m0.003s
sys 0m0.003s

It's almost like bash is compiling my script or something.  Is there any way to debug this?  It also doesn't seem to be anything with my .bash_profile - if I just put an echo on the first line of .bash_profile I still only see that after 10+ seconds.

I've tried this in iTerm2 and in native Terminal - both have exactly the same issue.  This is on macOS Sierra - 10.12.3

Body:
I had the same issue on my work machine, running macOS Sierra 10.12.5 and 10.12.6, and I confirmed that @charles-duffy is right. My company's anti-malware is the problem. They are using a daemon called Confer by Carbon Black for endpoint security.

Run this command to see if the problem stops:

launchctl unload /Library/LaunchDaemons/com.confer.sensor.daemon.plist

I think Confer is taking a fingerprint of every new program it sees and tries to compare it to a blacklist before allowing it to run. It looks like it times out after a second (trying to register the fingerprint online?), and something is making it try over and over again, yielding longer delays of integer seconds. This makes newly modified programs launch slowly, although speeds return to normal after the fingerprint has been taken.

Example runs

Here's how the problem manifested on my work laptop. As time went on, sometimes the delay increased, but always by an integer number of seconds at a time. If Confer remembers the program from before, there will be no delay.

bash scripts

$ bash --norc --noprofile -l  # make sure rc scripts don't interfere

bash-3.2$ echo exit > exit.sh && chmod +x exit.sh

bash-3.2$ time ./exit.sh

real    0m1.004s
user    0m0.001s
sys 0m0.002s

bash-3.2$ time ./exit.sh

real    0m0.002s
user    0m0.001s
sys 0m0.001s

There were no problems running commands provided to bash -c:

bash-3.2$ time bash -c exit

real    0m0.008s
user    0m0.002s
sys 0m0.003s

awk scripts

But the problem did affect awk scripts:

bash-3.2$ printf '%s\n' '#!/usr/bin/env awk -f' 'BEGIN { exit 0; }' > test.awk && chmod +x test.awk

bash-3.2$ time ./test.awk

real    0m4.010s
user    0m0.002s
sys 0m0.001s

bash-3.2$ time ./test.awk

real    0m0.005s
user    0m0.002s
sys 0m0.001s

Compiled binaries

It even affected compiled C and Golang code:

bash-3.2$ printf '%s\n' '#include "stdio.h"' 'int main() {' 'printf("Hello, world!\n");' 'return 0;' '}' > hello.c && gcc -o hello hello.c

bash-3.2$ time ./hello
Hello, world!

real    0m4.006s
user    0m0.001s
sys 0m0.001s

bash-3.2$ time ./hello
Hello, world!

real    0m0.004s
user    0m0.001s
sys 0m0.001s

bash-3.2$ printf '%s\n' 'package main' 'import "fmt"' 'func main() {' 'fmt.Println("test")' '}' > test.go && go build -o test ./test.go

bash-3.2$ time ./test
test

real    0m4.018s
user    0m0.001s
sys 0m0.003s

bash-3.2$ time ./test
test

real    0m0.005s
user    0m0.001s
sys 0m0.002s


问:
Open YouTube video in Fancybox jQuery
Can I open YouTube video in Fancybox.

I have a list of YouTube videos links, for ex:

```<code><a href="http://www.youtube.com/watch?v=PvbqV8W96D0" class="more">Play</a>
</code>```

and Fancybox :

```<code>$("a.more").fancybox({
                    'titleShow'     : false,
                    'transitionIn'  : 'elastic',
                    'transitionOut' : 'elastic'
        });
</code>```

I don't want to create for each video new embed object.

Is there some plug in, or a other way to do that ?

答:
Thanx, Alexander!

And to set the fancy-close button above the youtube's flash-content add 'wmode' to 'swf' parameters:

```<code>'swf': {'allowfullscreen':'true', 'wmode':'transparent'}
</code>```

Title: Open YouTube video in Fancybox jQuery

Body:
Can I open YouTube video in Fancybox.

I have a list of YouTube videos links, for ex:

Play

and Fancybox :

$("a.more").fancybox({
                    'titleShow'     : false,
                    'transitionIn'  : 'elastic',
                    'transitionOut' : 'elastic'
        });

I don't want to create for each video new embed object.

Is there some plug in, or a other way to do that ?

Body:
Thanx, Alexander!

And to set the fancy-close button above the youtube's flash-content add 'wmode' to 'swf' parameters:

'swf': {'allowfullscreen':'true', 'wmode':'transparent'}


问:
SQL Query - Oracle GL Transaction Detail
I am a novice SQL coder, and need some assistance with the SQL query I'm building for the GL Transaction Detail from Oracle.

I have been able to write my query, and I am successfully able to put the data how I like it. There's something I'd like to add to the query, which I believe requires a sub query, but I'm not sure how to write it.

```<code>SELECT CLIENT,
RESPONSIBILITY,
SERVICE_LINE,
STOB,
PROJECT,
JE_LINES_NET_ACT_AMOUNT AS "ACTUAL_AMOUNT",
EFFECTIVE_DATE,
PERIOD_NAME,
VENDOR_NAME,
DISTRIBUTION_SUPPLIER_NAME,
CASE WHEN JE_LINE_DESCRIPTION='Journal Import Created' THEN
     AP_DISTRIBUTION_DESCRIPTION ELSE
     JE_LINE_DESCRIPTION END AS DESCRIPTION,
CASE WHEN JE_HEADER_NAME LIKE '%Purchase%' THEN
     INVOICE_NUMBER ELSE
     JE_HEADER_NAME END AS DOCUMENT_NUMBER
FROM GL_Detail
WHERE RESPONSIBILITY BETWEEN '17500' AND '17511'
     AND EFFECTIVE_DATE BETWEEN '2016/04/01' AND '2017/03/31'
     AND JE_LINES_NET_ACT_AMOUNT <> 0
</code>```

Above is an example of the code I'm using for my query. Currently I have it pulling data for a range of responsibility centers (or cost centers). For reporting purposes, we have these responsibility centers roll up to different levels for location and department. Most users, want to pull the data by these rolled up responsibility numbers; however our GL transaction detail table does not have these columns.

What I want to be able to do: I want to be able to define a range of responsibility centers and assign them with their rolled up responsibility number that I can define. When I set the parameter after the WHERE, I want to be able to set the rolled up responsibility number as a parameter.

Would a nested case function solve this after select do this? Or is there another function I need to use?

Any help would be greatly appreciated.

答:
You can use a PL/SQL script to give you that result. You use the ACCEPT command before your statement. Also note that because I have you shifting to PL/SQL, I added a semicolon and forward slash to the end of your query.

```<code>ACCEPT resp_start NUMBER PROMPT 'Enter responsibility start range: '
ACCEPT resp_end NUMBER PROMPT 'Enter responsibility end range:   '

SELECT
    . . .
FROM GL_Detail
WHERE RESPONSIBILITY BETWEEN '&resp_start' AND '&resp_end'
 AND EFFECTIVE_DATE BETWEEN '2016/04/01' AND '2017/03/31'
 AND JE_LINES_NET_ACT_AMOUNT <> 0;
/
</code>```

See How do I use variables in Oracle SQL Developer? for more information on substituting variables. I hope that helps!

Body:
I am a novice SQL coder, and need some assistance with the SQL query I'm building for the GL Transaction Detail from Oracle.

I have been able to write my query, and I am successfully able to put the data how I like it. There's something I'd like to add to the query, which I believe requires a sub query, but I'm not sure how to write it.

SELECT CLIENT,
RESPONSIBILITY,
SERVICE_LINE,
STOB,
PROJECT,
JE_LINES_NET_ACT_AMOUNT AS "ACTUAL_AMOUNT",
EFFECTIVE_DATE,
PERIOD_NAME,
VENDOR_NAME,
DISTRIBUTION_SUPPLIER_NAME,
CASE WHEN JE_LINE_DESCRIPTION='Journal Import Created' THEN
     AP_DISTRIBUTION_DESCRIPTION ELSE
     JE_LINE_DESCRIPTION END AS DESCRIPTION,
CASE WHEN JE_HEADER_NAME LIKE '%Purchase%' THEN
     INVOICE_NUMBER ELSE
     JE_HEADER_NAME END AS DOCUMENT_NUMBER
FROM GL_Detail
WHERE RESPONSIBILITY BETWEEN '17500' AND '17511'
     AND EFFECTIVE_DATE BETWEEN '2016/04/01' AND '2017/03/31'
     AND JE_LINES_NET_ACT_AMOUNT <> 0

Above is an example of the code I'm using for my query. Currently I have it pulling data for a range of responsibility centers (or cost centers). For reporting purposes, we have these responsibility centers roll up to different levels for location and department. Most users, want to pull the data by these rolled up responsibility numbers; however our GL transaction detail table does not have these columns.

What I want to be able to do: I want to be able to define a range of responsibility centers and assign them with their rolled up responsibility number that I can define. When I set the parameter after the WHERE, I want to be able to set the rolled up responsibility number as a parameter.

Would a nested case function solve this after select do this? Or is there another function I need to use?

Any help would be greatly appreciated.

Body:
You can use a PL/SQL script to give you that result. You use the ACCEPT command before your statement. Also note that because I have you shifting to PL/SQL, I added a semicolon and forward slash to the end of your query.

ACCEPT resp_start NUMBER PROMPT 'Enter responsibility start range: '
ACCEPT resp_end NUMBER PROMPT 'Enter responsibility end range:   '

SELECT
    . . .
FROM GL_Detail
WHERE RESPONSIBILITY BETWEEN '&resp_start' AND '&resp_end'
 AND EFFECTIVE_DATE BETWEEN '2016/04/01' AND '2017/03/31'
 AND JE_LINES_NET_ACT_AMOUNT <> 0;
/

See How do I use variables in Oracle SQL Developer? for more information on substituting variables. I hope that helps!


问:
Unable to resolve module - importing Redux in React Native
Just added Redux to my app and it's saying it cant find my store. Is this a bug in React? I've worked with Vue2 and Angular2, but I'm a total noob when it comes to all things React.

Here's a screenshot of my structure and main js file...

答: Your reference is configStore, your file name is configureStore.js. Change them to match each other.


问:
MYSQL proper way to index calulated where conditions ( where myTable.a > myTable.b)
MySQL --version is 5.7.18

What would be the proper way to optimize a query like:

```<code>select id,name from mytable where a - b > 0
</code>```

where mytable is something like

id - primary key,increments, big integer

name - varchar(255)

a - integer, unsigned, 10

b - integer, unsigned, 10

Would adding indexes to a and b columns help? Should I just add a third column a_minus_b, index it, and then just be careful to update it properly every time or is there a better way?

答:
You can use a generated column and then an index on that:

```<code>alter table mytable add column abdiff int generated always as (a - b);

create index idx_mytable_abdiff on mytable(abdiff);
</code>```

Note:  This uses an int for the type.  You can specify whatever type you like for the difference.

Body:
MySQL --version is 5.7.18

What would be the proper way to optimize a query like:

select id,name from mytable where a - b > 0

where mytable is something like

id - primary key,increments, big integer

name - varchar(255)

a - integer, unsigned, 10

b - integer, unsigned, 10

Would adding indexes to a and b columns help? Should I just add a third column a_minus_b, index it, and then just be careful to update it properly every time or is there a better way?

Body:
You can use a generated column and then an index on that:

alter table mytable add column abdiff int generated always as (a - b);

create index idx_mytable_abdiff on mytable(abdiff);

Note:  This uses an int for the type.  You can specify whatever type you like for the difference.


问:
Writing and reading XML in C#
I've written a setting file in C# as XML

```<code>XmlWriter xmlWriter = XmlWriter.Create(files);
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Settings");

xmlWriter.WriteStartElement("launch");
xmlWriter.WriteString("launch tab");
xmlWriter.WriteEndElement();

xmlWriter.WriteStartElement("some_setting");
xmlWriter.WriteString("empty");
xmlWriter.WriteEndElement();
</code>```

And so on, but how to read it back?

I keep getting errors.

```<code>XmlReader xmlReader = XmlReader.Create(files);

xmlReader.ReadStartElement("launch");
textBox1.Text = xmlReader.ReadString();
</code>```

I wish to simply read it back in but getting the error

System.Xml.XmlException: 'Element 'launch' was not found

Line 1, position 40.

答:
Read and write using XmlWriter must be symmetrical - you are missing reading Settings in your read code.

Note: it may be easier to use serialization to read/write whole objects - Serialize an object to XML

Title: Writing and reading XML in C#

Body:
I've written a setting file in C# as XML

XmlWriter xmlWriter = XmlWriter.Create(files);
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Settings");

xmlWriter.WriteStartElement("launch");
xmlWriter.WriteString("launch tab");
xmlWriter.WriteEndElement();

xmlWriter.WriteStartElement("some_setting");
xmlWriter.WriteString("empty");
xmlWriter.WriteEndElement();

And so on, but how to read it back?

I keep getting errors.

XmlReader xmlReader = XmlReader.Create(files);

xmlReader.ReadStartElement("launch");
textBox1.Text = xmlReader.ReadString();

I wish to simply read it back in but getting the error

System.Xml.XmlException: 'Element 'launch' was not found

Line 1, position 40.


问:
Add text at the end of each line
I'm on Linux command line and I have file with

```<code>127.0.0.1
128.0.0.0
121.121.33.111
</code>```

I want

```<code>127.0.0.1:80
128.0.0.0:80
121.121.33.111:80
</code>```

I remember my colleagues were using sed for that, but after reading sed manual still not clear how to do it on command line?

答:
Using a text editor, check for <code>^M</code> (control-M, or carriage return) at the end of each line. You will need to remove them first, then append the additional text at the end of the line. </p>

```<code>sed -i 's|^M||g' ips.txt
sed -i 's|$|:80|g' ips.txt
</code>```

Title: Add text at the end of each line

Body:
I'm on Linux command line and I have file with

127.0.0.1
128.0.0.0
121.121.33.111

I want

127.0.0.1:80
128.0.0.0:80
121.121.33.111:80

I remember my colleagues were using sed for that, but after reading sed manual still not clear how to do it on command line?

Body:
Using a text editor, check for ^M (control-M, or carriage return) at the end of each line. You will need to remove them first, then append the additional text at the end of the line.

sed -i 's|^M||g' ips.txt
sed -i 's|$|:80|g' ips.txt


问:
How do I mount a remote Linux folder in Windows through SSH?
I'm a blind student currently in a system admin/shell programming class. Although ssh works fine for executing commands like ls, pwd, etc editors do not work well with my screen reader and an ssh session. I was wondering if it is possible to mount a Linux folder over ssh so it appears as a windows drive? This way I could edit any files I needed to with accessible software and not have to constantly use SCP to send files back and fourth.</p>

答:
Dokan looks like a FUSE and sshfs implementation for Windows. If it works as expected and advertised, it would do exactly what you are looking for.

(Link updated and working 2015-10-15)

OwnerDisplayName: Jared

LastEditorDisplayName: Michael Haren

OwnerDisplayName: matli


问:
Bulk Remove Database Objects From Database Project
I'm currently maintaining a SQL Server database that is over 17 years old, and has a large number of unused and outdated artifacts within it.

Over the last several months we have been profiling the database to determine which of the 1800+ stored procedures are actually being used, and which ones we can safely remove.  And as of right now, we have a list of about 1300 that we are planning on removing.

This database is also checked in under our source control in a SQL Server Database Project.

Now, what I'd like to do is generate a script to remove the 1300 procedures and apply that script to the database project first, before applying the script to our Development environment.  But I can't seem to figure out a way to update the project via a script.

I've tried doing an Import > Script and importing a .sql file with DROP PROCEDURE commands, but it throws the following error whilst not removing the procedure from the project:

In the script that you provided to the import operation, one or more statements were not fully understood. These statements were moved to the ScriptsIgnoredOnImport.sql file. Review the file contents for additional information.

The contents of the file tested was the following:

```<code>Drop Procedure spProcedureName;
</code>```

I could go through the project and remove each procedure one-by-one... but there are over 1300 to remove...

Is there any way to do a bulk update (via a script or otherwise) to a database project to remove multiple database objects?

Additional Information:

Creating a shell database from the project and making updates to that will prove to be just as much effort as manually removing the 1,300 stored procedures one-by-one.  This is due to the fact that many of the stored procedures we're planning on removing contain outdated/invalid references to tables, views, functions, OPENROWSET connections, and other procedures.  Because of that, the deploy script fails, and a shell database cannot be created without modifying the individual invalid objects in the script.

Getting a backup/restore of the current database is also not a viable solution, as the current database is a little over 3 TB in size.

Because of the above limitations, I am only looking for a solution that can be applied to the database project directly without any dependency on a secondary physical database.

答:
To remove the object programmatically from a project, you may use EnvDTE.ProjectItem class, Remove() method.

https://msdn.microsoft.com/en-us/library/envdte.projectitem.remove.aspx

There are many VS extensions that can run EnvDTE commands, like this: https://vlasovstudio.com/visual-commander/index.html

Or you can use Package Management Console (Tools--> NuGet Package Manager --> Package Management Console)

Step1. Assign the list of SPs to variable:

$IncludeList = "SP1.sql", "SP2.sql"

Step2. Drop SP from the project if it is in the list.

If your project path to SPs is like "Database2\dbo\Stored Procedures\", then it's like:

$DTE.Solution.Projects | ForEach { if ($.Name -eq "Database2") {$.ProjectItems | ForEach { if ($.Name -eq "dbo") {$.ProjectItems | ForEach { if ($.Name -eq "Stored Procedures") {$.ProjectItems | ForEach {if ($IncludeList -contains $.Name) {$.Remove()}}}}}}}}

Body:
I'm currently maintaining a SQL Server database that is over 17 years old, and has a large number of unused and outdated artifacts within it.

Over the last several months we have been profiling the database to determine which of the 1800+ stored procedures are actually being used, and which ones we can safely remove.  And as of right now, we have a list of about 1300 that we are planning on removing.

This database is also checked in under our source control in a SQL Server Database Project.

Now, what I'd like to do is generate a script to remove the 1300 procedures and apply that script to the database project first, before applying the script to our Development environment.  But I can't seem to figure out a way to update the project via a script.

I've tried doing an Import > Script and importing a .sql file with DROP PROCEDURE commands, but it throws the following error whilst not removing the procedure from the project:

In the script that you provided to the import operation, one or more statements were not fully understood. These statements were moved to the ScriptsIgnoredOnImport.sql file. Review the file contents for additional information.

The contents of the file tested was the following:

Drop Procedure spProcedureName;

I could go through the project and remove each procedure one-by-one... but there are over 1300 to remove...

Is there any way to do a bulk update (via a script or otherwise) to a database project to remove multiple database objects?

Additional Information:

Creating a shell database from the project and making updates to that will prove to be just as much effort as manually removing the 1,300 stored procedures one-by-one.  This is due to the fact that many of the stored procedures we're planning on removing contain outdated/invalid references to tables, views, functions, OPENROWSET connections, and other procedures.  Because of that, the deploy script fails, and a shell database cannot be created without modifying the individual invalid objects in the script.

Getting a backup/restore of the current database is also not a viable solution, as the current database is a little over 3 TB in size.

Because of the above limitations, I am only looking for a solution that can be applied to the database project directly without any dependency on a secondary physical database.


问:
JQuery click() on anchor tag not firing from an injected script inside WebBrowser control
I am developing a web bot using WinForms WebBrowser control. Everything is working fine except for the second click() call in following code:

```<code>function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();             //<-- This is working
        var x = $('#s_at_m_4-menu li')[5];
        var saveLink = $(x).find('a')[0];
        if (saveLink != null){
            saveLink.click();           //<-- This is not working

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}
</code>```

saveLink is not null. I know this because I placed an alert() call inside the condition.

Updated code with suggested solutions

```<code>function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();
        var x = $('#s_at_m_4-menu li').eq(5);
        var saveLink = x.find('a').eq(0);
        if (saveLink != null) {
            alert(saveLink.html());
            saveLink.click();

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}
</code>```

But still the same problem. 'alert()' is working fine but html() is showing inner text instead of HTML of the anchor.

HTML Code

```<code><li data-caption="Save Record                [Ctrl+S]" class="sbui-appletmenu-item  ui-menu-item" role="presentation">
<a href="javascript:void(0)" aria-disabled="false" class="ui-corner-all" id="ui-id-254" tabindex="-1" role="menuitem">Save Record                [Ctrl+S]</a>
</li>
</code>```

ID of the anchor tag is dynamically generated.

Also, click() is triggering when the same code is executed from Google Chrome Console. So, could it be the issue with the WebBrowser control?

Update

I think guys its a problem with the webrowser control that inherits Internet Explorer. So now I am shifting to another browser control and testing the code on it. Will let you know if it works there.

答:
Remember one thing javascript and javascript frameworks are event driven,so please don't try to implement the functional programming concepts</p>

```<code>$(document).ready(function(){
   $("#s_at_m_4").click(function(){
   // put your code here
   });
});
</code>```

Body:
I am developing a web bot using WinForms WebBrowser control. Everything is working fine except for the second click() call in following code:

function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();             //<-- This is working
        var x = $('#s_at_m_4-menu li')[5];
        var saveLink = $(x).find('a')[0];
        if (saveLink != null){
            saveLink.click();           //<-- This is not working

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}

saveLink is not null. I know this because I placed an alert() call inside the condition.

Updated code with suggested solutions

function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();
        var x = $('#s_at_m_4-menu li').eq(5);
        var saveLink = x.find('a').eq(0);
        if (saveLink != null) {
            alert(saveLink.html());
            saveLink.click();

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}

But still the same problem. 'alert()' is working fine but html() is showing inner text instead of HTML of the anchor.

HTML Code

Save Record                [Ctrl+S]

ID of the anchor tag is dynamically generated.

Also, click() is triggering when the same code is executed from Google Chrome Console. So, could it be the issue with the WebBrowser control?

Update

I think guys its a problem with the webrowser control that inherits Internet Explorer. So now I am shifting to another browser control and testing the code on it. Will let you know if it works there.

Body:
Remember one thing javascript and javascript frameworks are event driven,so please don't try to implement the functional programming concepts

$(document).ready(function(){
   $("#s_at_m_4").click(function(){
   // put your code here
   });
});


问:
Grunt watch livereload over MAMP Pro virtual host and ssl returns error net::ERR_CONNECTION_CLOSED
Gruntfile:

```<code>module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    sass: {
      dist: {
        files: {
          'build/css/build.css' : 'sass/main.scss',
        },
      },
    },
    concat: {
      options: {
        separator: ';',
      },
      dist: {
        src: ['js/jquery-getquerystring.min.js','node_modules/featherlight/release/featherlight.min.js', 'js/main.js'],
        dest: 'build/js/build.js',
      },
    },
    concat_css: {
      all: {
        src: ['node_modules/featherlight/release/featherlight.min.css', 'build/css/build.css'],
        dest: 'build/css/build.css',
      }
    },
    watch: {
      sass: {
        files: ['sass/**/*.scss'],
        tasks: ['sass', 'concat_css'],
        options: {
          livereload : 35729,
        }
      },
      js: {
        files: ['js/**/*.js'],
        tasks: ['concat'],
        options: {
          livereload : 35729,
        }
      },
      php: {
        files: ['**/*.php'],
        options: {
          livereload : 35729,
        }
      },
      options: {
        style: 'expanded',
        compass: true,
        livereload : {
          port: '37925',
          host: 'mysite.dev',
          key: grunt.file.read('/absolute/path/to/mysite.key'),
          cert: grunt.file.read('/absolute/path/to/mysite.crt'),
        },
      },
    },
  });

  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-concat-css');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('default', ['sass', 'concat', 'concat_css', 'watch']);

};
</code>```

Just before my closing body tag I have:

```<code><script src="https://mysite.dev:35729/livereload.js"></script>
</code>```

Going to https://mysite.dev works without any issues but looking at the Console tab in Chrome 58 I get the error: GET https://mysite.dev:35729/livereload.js net::ERR_CONNECTION_CLOSED. However if go to the url https://mysite.dev:35729/livereload.js I see the code for livereload.js

I use MAMP Pro 4.1.1 to manage my local Wordpress development if that helps. Any help appreciated. Please let me know if I need to provide any other information. Thanks.

答:
After much trial and error I finally got it working:

```<code>module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    sass: {
      dist: {
        files: {
          'build/css/build.css' : 'sass/main.scss',
        },
      },
    },
    concat: {
      options: {
        separator: ';',
      },
      dist: {
        src: ['js/jquery-getquerystring.min.js','node_modules/featherlight/release/featherlight.min.js', 'js/main.js'],
        dest: 'build/js/build.js',
      },
    },
    concat_css: {
      all: {
        src: ['node_modules/featherlight/release/featherlight.min.css', 'build/css/build.css'],
        dest: 'build/css/build.css',
      }
    },
    watch: {
      sass: {
        files: ['sass/**/*.scss'],
        tasks: ['sass', 'concat_css']
      },
      js: {
        files: ['js/**/*.js'],
        tasks: ['concat']
      },
      php: {
        files: ['**/*.php']
      },
      options: {
        style: 'expanded',
        livereload : {
          port: 1337,
          host: 'mysite.dev',
          key: grunt.file.read('/absolute/path/to/mysite.key'),
          cert: grunt.file.read('/absolute/path/to/mysite.crt'),
        },
      },
    },
  });

  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-concat-css');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('default', ['sass', 'concat', 'concat_css', 'watch']);

};
</code>```

And just above the closing body tag:

```<code><script src="//mysite.dev:1337/livereload.js"></script>
</code>```

Body:
Gruntfile:

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    sass: {
      dist: {
        files: {
          'build/css/build.css' : 'sass/main.scss',
        },
      },
    },
    concat: {
      options: {
        separator: ';',
      },
      dist: {
        src: ['js/jquery-getquerystring.min.js','node_modules/featherlight/release/featherlight.min.js', 'js/main.js'],
        dest: 'build/js/build.js',
      },
    },
    concat_css: {
      all: {
        src: ['node_modules/featherlight/release/featherlight.min.css', 'build/css/build.css'],
        dest: 'build/css/build.css',
      }
    },
    watch: {
      sass: {
        files: ['sass/**/*.scss'],
        tasks: ['sass', 'concat_css'],
        options: {
          livereload : 35729,
        }
      },
      js: {
        files: ['js/**/*.js'],
        tasks: ['concat'],
        options: {
          livereload : 35729,
        }
      },
      php: {
        files: ['**/*.php'],
        options: {
          livereload : 35729,
        }
      },
      options: {
        style: 'expanded',
        compass: true,
        livereload : {
          port: '37925',
          host: 'mysite.dev',
          key: grunt.file.read('/absolute/path/to/mysite.key'),
          cert: grunt.file.read('/absolute/path/to/mysite.crt'),
        },
      },
    },
  });

  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-concat-css');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('default', ['sass', 'concat', 'concat_css', 'watch']);

};

Just before my closing body tag I have:

Going to https://mysite.dev works without any issues but looking at the Console tab in Chrome 58 I get the error: GET https://mysite.dev:35729/livereload.js net::ERR_CONNECTION_CLOSED. However if go to the url https://mysite.dev:35729/livereload.js I see the code for livereload.js

I use MAMP Pro 4.1.1 to manage my local Wordpress development if that helps. Any help appreciated. Please let me know if I need to provide any other information. Thanks.

Body:
After much trial and error I finally got it working:

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    sass: {
      dist: {
        files: {
          'build/css/build.css' : 'sass/main.scss',
        },
      },
    },
    concat: {
      options: {
        separator: ';',
      },
      dist: {
        src: ['js/jquery-getquerystring.min.js','node_modules/featherlight/release/featherlight.min.js', 'js/main.js'],
        dest: 'build/js/build.js',
      },
    },
    concat_css: {
      all: {
        src: ['node_modules/featherlight/release/featherlight.min.css', 'build/css/build.css'],
        dest: 'build/css/build.css',
      }
    },
    watch: {
      sass: {
        files: ['sass/**/*.scss'],
        tasks: ['sass', 'concat_css']
      },
      js: {
        files: ['js/**/*.js'],
        tasks: ['concat']
      },
      php: {
        files: ['**/*.php']
      },
      options: {
        style: 'expanded',
        livereload : {
          port: 1337,
          host: 'mysite.dev',
          key: grunt.file.read('/absolute/path/to/mysite.key'),
          cert: grunt.file.read('/absolute/path/to/mysite.crt'),
        },
      },
    },
  });

  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-concat-css');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('default', ['sass', 'concat', 'concat_css', 'watch']);

};

And just above the closing body tag:

<script src="//mysite.dev:1337/livereload.js"></script>


问:
Grow :before content width from center
I've recently discovered the following approach for text-progress styling and wonder if there is a workaround to grow the element width from the center, so the text would also fill the from center instead of from the left side.

body {
  background-color: black;
}

p {
  color: rgba(255, 255, 255, .4);
  font-family: Arial, Helvetica, sans-serif;
  font-size: 40px;
  height: 85px;
  position: relative;
}

p:before {
  max-width: 100%;
  width: 0;
  height: 85px;
  color: #fff;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
  content: attr(data-text);
  display: block;
  animation: background-fill 15s ease-in-out infinite forwards;
}

@keyframes background-fill {
  0% {
    width: 0;
   }
  100% {
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p data-text='Text'>Text</p></code>```

答:
You can achieve that by also animate left and text-indent

I also changed your p to display as inline-block, so it animate the text and not white space.

Thanks to Gaby aka G. Petrioli, it appears Firefox have issue with percent-based text-indent, so I added a CSS hack to overcome that. And again thanks to Gaby, for his now delete answer, that solved the Firefox issue (though unfortunately fails on IE)

body {
  background-color: black;
}

p {
  color: rgba(255, 255, 255, .4);
  font-family: Arial, Helvetica, sans-serif;
  font-size: 40px;
  height: 85px;
  position: relative;
  display: inline-block;
}

p:before {
  max-width: 100%;
  width: 0;
  height: 85px;
  color: #fff;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
  content: attr(data-text);
  display: block;
  animation: background-fill 5s ease-in-out infinite forwards;
}

@keyframes background-fill {
  0% {
    left: 50%;
    text-indent: -50%;
    width: 0;
   }
  100% {
    left: 0;
    text-indent: 0;
    width: 100%;
  }
}

/*  Begin - Firefox bug fix  */
@supports (-moz-appearance:meterbar) and (display:flex) {
  p:before {
    width: auto;
    right: 50%;
    left: 50%;
    display: flex;
    justify-content: center;
  }
  @keyframes background-fill {
    0% {
      right: 50%;
      left: 50%;
    }
    100% {
      right: 0;
      left: 0;
    }
  }
}
/*  End - Firefox bug fix  */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p data-text='Text'>Text</p></code>```

An alternative to the CSS hack, is a small script, that, on page load, measure the actual width of the element and set the text-indent as px instead of %.

Title: Grow :before content width from center

Body:
I've recently discovered the following approach for text-progress styling and wonder if there is a workaround to grow the element width from the center, so the text would also fill the from center instead of from the left side.

body {
  background-color: black;
}

p {
  color: rgba(255, 255, 255, .4);
  font-family: Arial, Helvetica, sans-serif;
  font-size: 40px;
  height: 85px;
  position: relative;
}

p:before {
  max-width: 100%;
  width: 0;
  height: 85px;
  color: #fff;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
  content: attr(data-text);
  display: block;
  animation: background-fill 15s ease-in-out infinite forwards;
}

@keyframes background-fill {
  0% {
    width: 0;
   }
  100% {
    width: 100%;
  }
}

Text

Body:
You can achieve that by also animate left and text-indent

I also changed your p to display as inline-block, so it animate the text and not white space.

Thanks to Gaby aka G. Petrioli, it appears Firefox have issue with percent-based text-indent, so I added a CSS hack to overcome that. And again thanks to Gaby, for his now delete answer, that solved the Firefox issue (though unfortunately fails on IE)

body {
  background-color: black;
}

p {
  color: rgba(255, 255, 255, .4);
  font-family: Arial, Helvetica, sans-serif;
  font-size: 40px;
  height: 85px;
  position: relative;
  display: inline-block;
}

p:before {
  max-width: 100%;
  width: 0;
  height: 85px;
  color: #fff;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
  content: attr(data-text);
  display: block;
  animation: background-fill 5s ease-in-out infinite forwards;
}

@keyframes background-fill {
  0% {
    left: 50%;
    text-indent: -50%;
    width: 0;
   }
  100% {
    left: 0;
    text-indent: 0;
    width: 100%;
  }
}

/*  Begin - Firefox bug fix  */
@supports (-moz-appearance:meterbar) and (display:flex) {
  p:before {
    width: auto;
    right: 50%;
    left: 50%;
    display: flex;
    justify-content: center;
  }
  @keyframes background-fill {
    0% {
      right: 50%;
      left: 50%;
    }
    100% {
      right: 0;
      left: 0;
    }
  }
}
/*  End - Firefox bug fix  */

<p data-text='Text'>Text</p>

An alternative to the CSS hack, is a small script, that, on page load, measure the actual width of the element and set the text-indent as px instead of %.


问:
Can't form a chain between two views/widgets in Android Studio
When I'm using the layout editor in Android Studio and I try to make a chain (bidirectional constraint) between a EditText View and a Button View using the constraint anchors, it doesn't make the chain.

It only makes a constraint if I try to constrain one View to the other.

I am trying to chain the right side of the EditText to the left side of the Button.

This is what my Layout Editor looks like:

答: The way I have been able to create a chain view in the blueprint layout is by drag click, select the objects to be linked. Then while they are selected right click and select "center horizontally" After doing this I can then create the other constraint and chain</p>


问:
Asm: Moving assembly instructions to specific address
Well, I am trying to find an assembly instruction that moves whole instructions to a specific address(which is independent of the size of the instruction). If there is no such instruction, could anybody give me some ideas on how multithreading could be achieved without system calls or other software? In other words, let's suppose that I am making my own operating system, how can I enable multithreading with efficient code in assembly?</p>

答:
Re the question of how to achieve multithreading in raw assembly: Modern 32-bit x86 processors have hardware support for task switching. You can use this to implement multitasking (multiple processes with distinct address spaces) and/or multithreading (multiple execution threads in a single process).

This functionality is documented in the Intel 64 and IA-32 Architectures Software Developer's Manual, Volume 3, Chapter 7, Task Management. NOTE: Reading & understanding this ridiculously dense 4700 page document is likely to require 12 lifetimes.

Using this hardware support is the most straightforward way to get something running but probably not the most efficient. x86-based operating systems early on moved away from this to manual task switching. This allows the system to implement switching features not provided by the CPU and also to perform optimized switches when a full switch would be overkill. The approach became so universal that the 64-bit long mode of x86 processors dropped hardware task management support. Modern operating systems use manual task switching.

Re the idea of moving instructions as a way to achieve multithreading, I think your concept here is to move code around the address space when switching to new code is necessary. There are 2 alternative techniques that eliminate the need to do this.

First, instead of moving code you can jump to code at a different location. Early multitasking operating systems such as Unix on the PDP-11 used this technique. You can load all active programs into memory at different locations, set up a periodic interrupt to drop control to your system software every so often, and on each interrupt choose the next program to jump to. The system should keep track of where each program stops so it can resume at the same place.

The second approach depends on virtual memory. There is still a single physical memory space. On top of that, multiple "virtual" memory spaces are defined. At any given time only 1 virtual memory space is active. Whenever memory is accessed the system translates the virtual address into some physical address. The program accessing memory only sees its own virtual address space.

Each task is given its own address space. When switching to a new task the system activates its private address space then resumes execution wherever it was last paused in the private address space. Instead of moving things around the single shared address space, or even jumping from one place to another in the shared address space, you actually define a whole set of separate address spaces. You shift into new spaces as necessary.

Modern multithreading depends heavily on this approach. Each process will have a private address space; the system shifts between them as necessary. A process will have 1+ threads. Every thread in a process shares the same address space. Then all you store per thread is where execution was last paused. Switching to a new thread in the same process keeps the current address space and just jumps within it to wherever the new thread was last paused.

Re the question of how to move instructions, assembly languages don't provide such an ability. It's not a common thing to do. If you wanted to operate on machine code in memory you would likely want to use a library like the Intel X86 Encoder Decoder library. A library like this has knowledge of the instructions that exist and the byte format of machine code. This enables it to interpret a sequence of bytes as an instruction.

Once you're aware how large the following instruction is, moving that number of bytes is an easy task in assembly. In x86 you would use the mov instruction.


问:
Printing tuple instead of three strings
I am trying to learn python, so I downloaded aptanaStudio3 and this happens.

Code:

```<code>print('One', 'Two', 'Three')
</code>```

Output:

```<code>('One', 'Two', 'Three')
</code>```

it should print just

```<code>One Two Three
</code>```

答:
'One', 'Two', 'Three' is a tuple. You need to do 'One' + 'Two' + 'Three', or you can just keep it in one string like One Two Three, so that you are printing a string.

A tuple is a group of strings, and you just need to print a single string. You probably typed , which defines a tuple, instead of +, which concatenates strings. Make sure you are using print("") for Python 3, and print "" for Python 2.

Read this and this to learn more.

Title: Printing tuple instead of three strings

Body:
I am trying to learn python, so I downloaded aptanaStudio3 and this happens.

Code:

print('One', 'Two', 'Three')

Output:

('One', 'Two', 'Three')

it should print just

One Two Three


问:
Migrate Microsoft Access application to... well, that is the question?
I developed a medium sized MS Access application back in 2004. Over the years it has grown old and my small bugfixes and improvements don't cut it anymore.

I always hear people yammering about how bad Access is and how it is not modern yadda,yadda. I'm quite happy with it and it does what it is supposed to do (Provide a stable frontend for a simple database).

My application uses lots of custom forms with subforms and lots of VBA code to do this and that. The most important part of the application is actually to provide the data for Word Mail Merges and to print badges and other material for a conference (via Access reports). And exactly this printing integration is why I can't think of any alternatives.

Any web based solution will be a hassle to create nice looking reports (or at least not with the easy of Access) - create pixel perfect layouts and mold them into PDFs, direct printing FTW. Any Windows Forms application will take long to develop and ultimately I would just be recreating functionality of MS Access (e.g. together with SSRS).

Can you think of any alternatives I have missed? I am basically just looking for ideas.

答:
Well, if you use built in functionality in Access the best path might be to not abandon Access but rather to rebuild the application as a new Access application.

Start by breaking out parts of the application to classes to get all related code together and clean up that code.

This way you could still use the parts of access you really have use for but the code will be better.

Also take a look on a book I like, Clean Code

Here is some other talk about this book.

Refactoring code like this is also a good way to get to know all the intricate parts of it  ;)

And you will not risk losing any functionality.

If you later get to build it on another platform, most of the refactoring would probably be reusable.


问:
Highlight Row if Value in Column is above 0 - Google Spreadsheet
I am trying to get a Google spreadsheet to automatically highlight all rows in a spreadsheet where the value in a particular column is above 0. I have looked for a few solutions but haven't got it to work.

I have got various metrics in the columns, so say I want to highlight all rows, in which column "I" has a value of more than zero.

Can someone help me with this?

答:
Because only to be applied to a single column there is a simpler version (that I have complicated so that text is not highlighted):

Clear formatting, select ColumnI and Format, Conditional formatting..., Format cells if... Custom formula is and:

```<code>=and(isnumber(I1),I1>0)
</code>```

with fill of choice and Done.

If to format not just the relevant cell but the entire row then change the Apply to Range (say to A1:Z1000) and add anchors ($s) as below:

```<code>=and(isnumber($I1),$I1>0)
</code>```

Body:
Because only to be applied to a single column there is a simpler version (that I have complicated so that text is not highlighted):

Clear formatting, select ColumnI and Format, Conditional formatting..., Format cells if... Custom formula is and:

=and(isnumber(I1),I1>0)

with fill of choice and Done.

If to format not just the relevant cell but the entire row then change the Apply to Range (say to A1:Z1000) and add anchors ($s) as below:

=and(isnumber($I1),$I1>0)


问:
Android - JSONArray to RecycleView Adapter?
In my Android app, I get a JSONArray of objects. Is it possible to pass this through directly into a recycleView adapter?

All of the recycleView implementations I've seen get JSONArray data first, and then loop through each object in the array, and transfer the values to a custom POJO(Plain old java object) and add it to a arrayList of the custom Java object, and then use this arrayList for the recycleView adapter.

However, it my app, I can potentially have many objects in the array. I believe it would be slow/inefficient to loop through it all in this fashion.

Is there anyway to pass the JSONArray directly into the recycleView adapter?

答:
Sure you can. Just customize an adapter:</p>

```<code>public class Adapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {

private JSONArray array;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView property;

    public MyViewHolder(View view) {
        super(view);
        property = (TextView) view.findViewById(R.id.some_view);

    }
}

public Adapter(JSONArray arr) {
    this.array = arr;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.list_row, parent, false);

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    Movie movie = moviesList.get(position);
    holder.property.setText(array.get(position).property);

}

@Override
public int getItemCount() {
    return array.length();
}
}
</code>```

Body:
Sure you can. Just customize an adapter:

public class Adapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {

private JSONArray array;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView property;

    public MyViewHolder(View view) {
        super(view);
        property = (TextView) view.findViewById(R.id.some_view);

    }
}

public Adapter(JSONArray arr) {
    this.array = arr;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.list_row, parent, false);

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    Movie movie = moviesList.get(position);
    holder.property.setText(array.get(position).property);

}

@Override
public int getItemCount() {
    return array.length();
}
}


答:
Python 2 has print as a command, so all you need is

```<code>print 'One', 'Two', 'Three'
</code>```

In Python 3, print is a function, so the parentheses are required for the call.

In most contexts, the series of values in parentheses is a tuple; this is just like a list, except that you can't change the individual elements (i.e. a tuple is immutable).

Title: Printing tuple instead of three strings

Body:
Python 2 has print as a command, so all you need is

print 'One', 'Two', 'Three'

In Python 3, print is a function, so the parentheses are required for the call.

In most contexts, the series of values in parentheses is a tuple; this is just like a list, except that you can't change the individual elements (i.e. a tuple is immutable).