问:
Get void output to variable
I have 2 .java files in my project and i want in one of them to show (in a textarea for example) the value of an Enumeration located in the other .java file.

This is the code of the first (or main) .java file - frm1.java:
(Just showing what i consider the most relevant part of the code, but if necessary, I can put it completely)

```<code>// Things HERE
    ListNets interfaceLoader = new ListNets();
    txtrBlabla.setText(names);
</code>```

Where the txtrBlabla is the name given for the JTextArea and ListNets the name for the second .java file.

And here the second .java file's content - ListNets.java:

```<code>public class ListNets {

    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    public static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
     String names = inetAddresses.toString(); //<-- This line is the only thing not "copy-pasted"
     }
}
</code>```

As you can see, the second code is just a copy&paste.
I've tried loads of ways to get the enumeration's result into a variable and then trying to set it into the textarea using the txtrBlabla.setText(names); line, but always get the error message:

names cannot be resolved into a variable

In the main java file.
I had also seen that's something related to "voids" but no results trying it.
I've also tried changing the variable but neither i get it working.

Note:
I'm an starter in JAVA but i really want to understand why this doesn't work.
Sorry for the spelling and thanks in advance.

EDIT:
Also tried putting everything in the same .java file as follows:

```<code>public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
     String names = inetAddresses.toString();
     }

        txtrBlabla.setText(displayInterfaceInformation.names);
</code>```

答:
Variable scope is your problem here.

Take a look at this:

http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm

The scope of a variable is the part of the program over which the variable name can be referenced. (from Ivor Horton's Beginning Java 2, JDK 5 Edition by Ivor Horton)

You cannot refer to a variable before its declaration.

You can declare variables in several different places:

In a class body as class fields. Variables declared here are referred to as class-level variables.

As parameters of a method or constructor.

In a method's body or a constructor's body.

Within a statement block, such as inside a while or for block.

Go to the link fo learn more about Variable Scope.

Title: Get void output to variable

Body:
I have 2 .java files in my project and i want in one of them to show (in a textarea for example) the value of an Enumeration located in the other .java file.

This is the code of the first (or main) .java file - frm1.java:
(Just showing what i consider the most relevant part of the code, but if necessary, I can put it completely)

// Things HERE
    ListNets interfaceLoader = new ListNets();
    txtrBlabla.setText(names);

Where the txtrBlabla is the name given for the JTextArea and ListNets the name for the second .java file.

And here the second .java file's content - ListNets.java:

public class ListNets {

    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    public static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
     String names = inetAddresses.toString(); //<-- This line is the only thing not "copy-pasted"
     }
}

As you can see, the second code is just a copy&paste.
I've tried loads of ways to get the enumeration's result into a variable and then trying to set it into the textarea using the txtrBlabla.setText(names); line, but always get the error message:

names cannot be resolved into a variable

In the main java file.
I had also seen that's something related to "voids" but no results trying it.
I've also tried changing the variable but neither i get it working.

Note:
I'm an starter in JAVA but i really want to understand why this doesn't work.
Sorry for the spelling and thanks in advance.

EDIT:
Also tried putting everything in the same .java file as follows:

public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
     String names = inetAddresses.toString();
     }

        txtrBlabla.setText(displayInterfaceInformation.names);


来源: stackexchange

问:
Is a Git clone without content possible?
My context is the following:

I want to do some operations on Git, that are only possible on a local repository.

I don't care about the content of history, even the current content. Only the metadata (commits, authors, dates, ...) are from interest.

So I would like to have a local Git repository that contains the least amount of data, to allow operations like:

Do a branch, and push it.

Do a tag, and push it.

Is something like that possible at all? I know already what a bare repository is (it gives you all commits including the file data), and I have read about git shallow clone, but both give me with the commits all data.

答: No, what you are asking (to have commits without the actual content) is fundamentally not supported by git.  Depending how your remote is hosted, the hosting server might provide API's that you could use to manipulate refs (branches and tags) without having to clone, but that's about it.</p>

ContentLicense: CC BY-SA 3.0


问:
Fill in the blanks won't fill in for repeat letters (Simple Program)
I'm making a program where someone has to fill in the blanks for a word. The correct blank is supposed to be filled in with the given guess, and then that list carries over so that they can keep guessing for 10 tries. It's a relatively simple code.

```<code>word = "nonagon"

wordlist=[]
blanks=[]
for i in word:
    wordlist.append(i)
    blanks.append("-")
attempts = 10

while attempts != 0:
    guess = input("Take a guess: ")
     for i in wordlist:
        if i == guess:
            blanks[wordlist.index(i)]=guess
            attempts-=1

    print(blanks)
</code>```

Basically, my program won't print a letter more than once.

E.g. if I type in "n" it won't print "n" more than once, even though "n" appears 3 times in "nonagon". I'm assuming it sees that first "n" in "nonagon" and only regards that one.

How would I go about making it print letters even if they repeat?

答:
wordlist.index(i) returns the same (first) occurrence of i in wordlist in every iteration, instead replace the for-loop by:

```<code>for p, i in enumerate(wordlist):
    if i == guess:
        blanks[p]=guess
        attempts-=1
</code>```

Body:
I'm making a program where someone has to fill in the blanks for a word. The correct blank is supposed to be filled in with the given guess, and then that list carries over so that they can keep guessing for 10 tries. It's a relatively simple code.

word = "nonagon"

wordlist=[]
blanks=[]
for i in word:
    wordlist.append(i)
    blanks.append("-")
attempts = 10

while attempts != 0:
    guess = input("Take a guess: ")
     for i in wordlist:
        if i == guess:
            blanks[wordlist.index(i)]=guess
            attempts-=1

    print(blanks)

Basically, my program won't print a letter more than once.

E.g. if I type in "n" it won't print "n" more than once, even though "n" appears 3 times in "nonagon". I'm assuming it sees that first "n" in "nonagon" and only regards that one.

How would I go about making it print letters even if they repeat?

Body:
wordlist.index(i) returns the same (first) occurrence of i in wordlist in every iteration, instead replace the for-loop by:

for p, i in enumerate(wordlist):
    if i == guess:
        blanks[p]=guess
        attempts-=1


问:
Using ConstraintLayout with custom Android Dialog
I'm creating a custom Dialog by extending Dialog and using setContentView(). The problem is when I try to show the Dialog it only shows the background shadow instead of my custom layout. I've managed to get the custom layout to show by wrapping it in a RelativeLayout, but I'm wondering if there is a better solution or something I'm doing wrong. Using constraintLayout version 1.0.2. Thanks!

Here is my Custom Dialog:

```<code>class EventsFilterDialog(context: Context): Dialog(context) {
    init {
        setContentView(R.layout.dialog_events_filter)
        setCancelable(true)
    }
}
</code>```

Here is a simplified version of my R.layout.dialog_events_filter that has the exact same result:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/white"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/headerTv"
        android:text="@string/events_filters"
        android:textColor="@color/white"
        android:textSize="18sp"
        android:textStyle="bold"
        android:gravity="center"
        android:background="@color/colorPrimaryLight"
        android:padding="16dp"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

    <View
        android:id="@+id/middleView"
        android:layout_width="0dp"
        android:layout_height="256dp"
        app:layout_constraintTop_toBottomOf="@+id/headerTv"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

    <TextView
        android:id="@+id/closeTv"
        android:text="@string/close"
        android:textColor="@color/white"
        android:textAllCaps="true"
        android:textStyle="bold"
        android:gravity="center"
        android:background="@color/colorPrimaryLight"
        android:layout_width="0dp"
        android:layout_height="48dp"
        app:layout_constraintTop_toBottomOf="@+id/middleView"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/applyTv" />

    <TextView
        android:id="@+id/applyTv"
        android:text="@string/apply_filter"
        android:textColor="@color/white"
        android:textAllCaps="true"
        android:textStyle="bold"
        android:gravity="center"
        android:background="@color/colorAccent"
        android:layout_width="0dp"
        android:layout_height="48dp"
        app:layout_constraintTop_toBottomOf="@+id/middleView"
        app:layout_constraintLeft_toRightOf="@+id/closeTv"
        app:layout_constraintRight_toRightOf="parent"/>

</android.support.constraint.ConstraintLayout>
</code>```

答:
Set LayoutParams of window of the dialog at run time. This one worked for me.

```<code>dialog.setContentView(R.layout.dialog_select_location);
Window window = dialog.getWindow();
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.CENTER);
</code>```

Best of luck!

Body:
I'm creating a custom Dialog by extending Dialog and using setContentView(). The problem is when I try to show the Dialog it only shows the background shadow instead of my custom layout. I've managed to get the custom layout to show by wrapping it in a RelativeLayout, but I'm wondering if there is a better solution or something I'm doing wrong. Using constraintLayout version 1.0.2. Thanks!

Here is my Custom Dialog:

class EventsFilterDialog(context: Context): Dialog(context) {
    init {
        setContentView(R.layout.dialog_events_filter)
        setCancelable(true)
    }
}

Here is a simplified version of my R.layout.dialog_events_filter that has the exact same result:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/white"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/headerTv"
        android:text="@string/events_filters"
        android:textColor="@color/white"
        android:textSize="18sp"
        android:textStyle="bold"
        android:gravity="center"
        android:background="@color/colorPrimaryLight"
        android:padding="16dp"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

    <View
        android:id="@+id/middleView"
        android:layout_width="0dp"
        android:layout_height="256dp"
        app:layout_constraintTop_toBottomOf="@+id/headerTv"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

    <TextView
        android:id="@+id/closeTv"
        android:text="@string/close"
        android:textColor="@color/white"
        android:textAllCaps="true"
        android:textStyle="bold"
        android:gravity="center"
        android:background="@color/colorPrimaryLight"
        android:layout_width="0dp"
        android:layout_height="48dp"
        app:layout_constraintTop_toBottomOf="@+id/middleView"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/applyTv" />

    <TextView
        android:id="@+id/applyTv"
        android:text="@string/apply_filter"
        android:textColor="@color/white"
        android:textAllCaps="true"
        android:textStyle="bold"
        android:gravity="center"
        android:background="@color/colorAccent"
        android:layout_width="0dp"
        android:layout_height="48dp"
        app:layout_constraintTop_toBottomOf="@+id/middleView"
        app:layout_constraintLeft_toRightOf="@+id/closeTv"
        app:layout_constraintRight_toRightOf="parent"/>

</android.support.constraint.ConstraintLayout>

Body:
Set LayoutParams of window of the dialog at run time. This one worked for me.

dialog.setContentView(R.layout.dialog_select_location);
Window window = dialog.getWindow();
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.CENTER);

Best of luck!


问:
Is having a global database connection allowed in WSGI applications?
I need to create a simple project in Flask. I don't want to use SQLAlchemy. In the code snippet below, everyone that connects to the server uses the same connection object but for each request, a new cursor object is created. I am asking this because I have never used Python DB api before in this way. Is it correct? Should I create a new connection object for each request or use the same connection and cursor object for each request or the method below. Which one is correct?</p>

```<code>import mysql.connector
from flask import Flask, request
app = Flask(__name__)

try:
    con = mysql.connector.connect(user='root',password='',host='localhost',database='pywork')
except mysql.connector.Error as err:
    print("Something went wrong")

@app.route('/')
def home():
    cursor = con.cursor()
    cursor.execute("INSERT INTO table_name VALUES(NULL,'test record')")
    con.commit()
    cursor.close()
    return ""
</code>```

答:
WSGI applications may be served by several worker processes and threads. So you might end up having multiple threads using the same connection. So you need to find out whether your library's implementation of the connection is thread safe. Look up the documentation and see if they claim to provide Level 2 thread safety.

Then you should reflect about whether or not you need transactions during your requests. If you find you need transactions (e.g., requests issue multiple database commands with an inconsistent state in between or possible race conditions), you should use different connections, because transactions are always connection wide. Note that some database systems or configurations don't support transactions or don't isolate separate connections from each other.

So if you share a connection, you should assume that you work with autocommit turned on (or better: actually do that).

Body:
I need to create a simple project in Flask. I don't want to use SQLAlchemy. In the code snippet below, everyone that connects to the server uses the same connection object but for each request, a new cursor object is created. I am asking this because I have never used Python DB api before in this way. Is it correct? Should I create a new connection object for each request or use the same connection and cursor object for each request or the method below. Which one is correct?

import mysql.connector
from flask import Flask, request
app = Flask(__name__)

try:
    con = mysql.connector.connect(user='root',password='',host='localhost',database='pywork')
except mysql.connector.Error as err:
    print("Something went wrong")

@app.route('/')
def home():
    cursor = con.cursor()
    cursor.execute("INSERT INTO table_name VALUES(NULL,'test record')")
    con.commit()
    cursor.close()
    return ""


问:
Arguments object different to arguments
I've hit a really strange issue, with Node & Express.

I have a middleware function, which can either be invoked in three different ways:

```<code>app.get('/', auth, handler)
app.get('/', auth('role'), handler)
app.get('/', auth('role', 'scope'), handler)
</code>```

The obvious way to do this would be like this:

```<code>exports.auth = (a, b, c) => {

    let role, scope;

    switch(arguments.length) {
        case 3:
            // Called directly by express router
            handleAuth(a, b, c);
            break;

        case 2:
        case 1:
            // Called with role/scope, return handler
            // but don't execute
            role = a;
            scope = b;
            return handleAuth;
    }

    function handleAuth(req, res, next) {

        // Do some custom auth handling, can
        // check here if role/scope is set
        return next();

    }
}
</code>```

However, I'm getting some very odd results for arguments.length. When called in the 2nd way, arguments.length == 5, and none of the arguments is role.

```<code>[ '0': '[object Object]',
  '1': 'function require(path) {\n    try {\n      exports.requireDepth += 1;\n      return mod.require(path);\n    } finally {\n      exports.requireDepth -= 1;\n    }\n  }',
  '2': '[object Object]',
  '3': '/Users/redacted/auth/index.js',
  '4': '/Users/redacted/auth' ]
</code>```

If I log a, b, c within the function, I get a: 'role', b: undefined, c: undefined.

I've tried to reproduce it in Runkit, but haven't had any luck: https://runkit.com/benedictlewis/5a2a6538895ebe00124eb64e

答:
arguments is not exposed in arrow functions (() =>). If you need them, use a regular function instead.

```<code>exports.auth = function(a, b, c) {

  let role, scope;

  switch(arguments.length) {
    ...
</code>```

Side note: The arguments your refer to in that arrow function is actually picked from the wrapper function which Node.js uses while running each module / required code. That function lets you access the "magical" variables such as exports, require, module, __dirname and __filename, which is why you see 5 arguments.

Title: Arguments object different to arguments

Body:
I've hit a really strange issue, with Node & Express.

I have a middleware function, which can either be invoked in three different ways:

app.get('/', auth, handler)
app.get('/', auth('role'), handler)
app.get('/', auth('role', 'scope'), handler)

The obvious way to do this would be like this:

exports.auth = (a, b, c) => {

    let role, scope;

    switch(arguments.length) {
        case 3:
            // Called directly by express router
            handleAuth(a, b, c);
            break;

        case 2:
        case 1:
            // Called with role/scope, return handler
            // but don't execute
            role = a;
            scope = b;
            return handleAuth;
    }

    function handleAuth(req, res, next) {

        // Do some custom auth handling, can
        // check here if role/scope is set
        return next();

    }
}

However, I'm getting some very odd results for arguments.length. When called in the 2nd way, arguments.length == 5, and none of the arguments is role.

[ '0': '[object Object]',
  '1': 'function require(path) {\n    try {\n      exports.requireDepth += 1;\n      return mod.require(path);\n    } finally {\n      exports.requireDepth -= 1;\n    }\n  }',
  '2': '[object Object]',
  '3': '/Users/redacted/auth/index.js',
  '4': '/Users/redacted/auth' ]

If I log a, b, c within the function, I get a: 'role', b: undefined, c: undefined.

I've tried to reproduce it in Runkit, but haven't had any luck: https://runkit.com/benedictlewis/5a2a6538895ebe00124eb64e

Body:
arguments is not exposed in arrow functions (() =>). If you need them, use a regular function instead.

exports.auth = function(a, b, c) {

  let role, scope;

  switch(arguments.length) {
    ...

Side note: The arguments your refer to in that arrow function is actually picked from the wrapper function which Node.js uses while running each module / required code. That function lets you access the "magical" variables such as exports, require, module, __dirname and __filename, which is why you see 5 arguments.


问:
Regex / preg_match to find 13 character unique ID
My database creates new entries using the PHP uniqid function. This means the ID is 13 characters and a mix of numbers and letters.

Examples of IDs:

5a0ae6fa29476

5a26822fbfd19

5a2a952fc9558

When an email comes in, it is meant to check the subject for a # followed by the ID - example subject: "Re: [Item #5a0ae6fa29476] Need Info". It must contain the #.

I'd like to use preg_match / regex to pull the ID from the email.

I'm currently using:

```<code>/(?!#)\w{13}/
</code>```

But the problem with it is that the # is not important and the following strings in email subjects will still be processed:

5a0ae6fa29476

13_characters

Communications

(any 13 character string involving letters, numbers or underswcores)

Can anyone advise a better regex to use? Thanks in advance

答:
You need to match the # symbol before the 13 digits, but you may also discard it easily with the \K operator:

```<code>/#\K\w{13}\b/
</code>```

Details

# - a # symbol

\K - match reset operator discarding all text matched so far

\w{13} -  13 word chars ending with a

\b - word boundary

See the regex demo.

Body:
My database creates new entries using the PHP uniqid function. This means the ID is 13 characters and a mix of numbers and letters.

Examples of IDs:

5a0ae6fa29476

5a26822fbfd19

5a2a952fc9558

When an email comes in, it is meant to check the subject for a # followed by the ID - example subject: "Re: [Item #5a0ae6fa29476] Need Info". It must contain the #.

I'd like to use preg_match / regex to pull the ID from the email.

I'm currently using:

/(?!#)\w{13}/

But the problem with it is that the # is not important and the following strings in email subjects will still be processed:

5a0ae6fa29476

13_characters

Communications

(any 13 character string involving letters, numbers or underswcores)

Can anyone advise a better regex to use? Thanks in advance

Body:
You need to match the # symbol before the 13 digits, but you may also discard it easily with the \K operator:

/#\K\w{13}\b/

Details

# - a # symbol

\K - match reset operator discarding all text matched so far

\w{13} -  13 word chars ending with a

\b - word boundary

See the regex demo.


问:
Problems getting inputted values from forms in jQuery
Hey guys, this is my first time using jQuery. I'm working on a simple Twitter app that checks whether a user is following another user, but I'm having trouble picking up on the inputted values in my form.

I've got this form on my page:

```<code><form id="form_friendship">
  Is <input type='text' name='user_a' value='username'/> following <input type='text' name='user_b' value='username'/> on Twitter? <input type="submit" value="Check">
</form>
</code>```

And using the form plugin, here's my JS:

```<code>var value = $('#form_friendship *').fieldValue( );
$('#form_friendship *').submit(alert(value));
</code>```

The only thing that's being alerted is "username, username" and it's not registered text inputted into the fields at all. Any ideas on what's wrong here? Thanks

答:
not sure what's wrong with your's but i link them both up as below and it works for me.

```<code> <html class="ui-widget-content" lang="en_US"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>jQuery Form Plugin</title>
<style type="text/css">
form { background: #DFEFFC; border: 5px solid #c5dbec; margin: 10px 0; padding: 20px }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="https://github.com/malsup/form/raw/master/jquery.form.js?v2.43"></script>
<script type="text/javascript">

$(document).ready(function(){
    var value = $('#form_friendship *').fieldValue();
    $('#form_friendship').submit(function(){
        alert(value);
        return false;
    });
});
</script>
</head>
<body>

<form id="form_friendship">
  Is <input type='text' name='user_a' value='jack'/> following <input type='text' name='user_b' value='username'/> on Twitter? <input type="submit" value="Check">
</form>
</body></html>
</code>```

think the * after your form id is messing with the submit.
this line:

```<code>$('#form_friendship').submit(function()
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hey guys, this is my first time using jQuery. I'm working on a simple Twitter app that checks whether a user is following another user, but I'm having trouble picking up on the inputted values in my form.

I've got this form on my page:

<form id="form_friendship">
  Is <input type='text' name='user_a' value='username'/> following <input type='text' name='user_b' value='username'/> on Twitter? <input type="submit" value="Check">
</form>

And using the form plugin, here's my JS:

var value = $('#form_friendship *').fieldValue( );
$('#form_friendship *').submit(alert(value));

The only thing that's being alerted is "username, username" and it's not registered text inputted into the fields at all. Any ideas on what's wrong here? Thanks

Body:
not sure what's wrong with your's but i link them both up as below and it works for me.

 <html class="ui-widget-content" lang="en_US"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>jQuery Form Plugin</title>
<style type="text/css">
form { background: #DFEFFC; border: 5px solid #c5dbec; margin: 10px 0; padding: 20px }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="https://github.com/malsup/form/raw/master/jquery.form.js?v2.43"></script>
<script type="text/javascript">

$(document).ready(function(){
    var value = $('#form_friendship *').fieldValue();
    $('#form_friendship').submit(function(){
        alert(value);
        return false;
    });
});
</script>
</head>
<body>

<form id="form_friendship">
  Is <input type='text' name='user_a' value='jack'/> following <input type='text' name='user_b' value='username'/> on Twitter? <input type="submit" value="Check">
</form>
</body></html>

think the * after your form id is messing with the submit.
this line:

$('#form_friendship').submit(function()


问:
Selenium Webdriver C# - how can I remove this hard wait?
I am having a really hard time with the following issue. I am trying to navigate through some web pages that have various inputs (text boxes/dropdowns/buttons) followed by a continue button at the bottom to move onto the next screen. My tests frequently fall over because they can't always locate the first element in order to interact with it.

As far as I'm aware the page doesn't do any fancy AJAX post loading or anything, so once the page has loaded then Webdriver should be able to locate every element.

My code:

FRAMEWORK

```<code>public static void WaitOnPageForXPathClickable(string selector)
    {
        new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable((By.XPath(selector))));
    }
</code>```

TEST CASE

```<code>Utilities.WaitOnPageForXPathClickable("the xpath of the continue button and checks that it is clickable");
Driver.Instance.FindElement(By.XPath("the xpath of the first button that I want to click")).Click();
</code>```

Do I need to try and include a function to ensure that the page is fully loaded before test execution? I am confused about this because I have read that Selenium already waits for the page to load by default. I would have thought that waiting for one element (the continue button) to be clickable should mean that all other elements are ready by then too? I really want to avoid having to wait for every single element before clicking it.

答:
Can you please share html, have you tried with Visible instead of Clickable

```<code>public static void WaitOnPageForXPathClickable(string selector)
{
    new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible((By.XPath(selector))));
}
</code>```

You can wait for the page to be fully loaded with something like:

```<code>        public void WaitForPageToBeFullyLoaded(int timeSpan)
    {
        new WebDriverWait(Driver, TimeSpan.FromSeconds(timeSpan)).Until(
            d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));
    }
</code>```

You can check for displayed or Enabled element too.

Body:
I am having a really hard time with the following issue. I am trying to navigate through some web pages that have various inputs (text boxes/dropdowns/buttons) followed by a continue button at the bottom to move onto the next screen. My tests frequently fall over because they can't always locate the first element in order to interact with it.

As far as I'm aware the page doesn't do any fancy AJAX post loading or anything, so once the page has loaded then Webdriver should be able to locate every element.

My code:

FRAMEWORK

public static void WaitOnPageForXPathClickable(string selector)
    {
        new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable((By.XPath(selector))));
    }

TEST CASE

Utilities.WaitOnPageForXPathClickable("the xpath of the continue button and checks that it is clickable");
Driver.Instance.FindElement(By.XPath("the xpath of the first button that I want to click")).Click();

Do I need to try and include a function to ensure that the page is fully loaded before test execution? I am confused about this because I have read that Selenium already waits for the page to load by default. I would have thought that waiting for one element (the continue button) to be clickable should mean that all other elements are ready by then too? I really want to avoid having to wait for every single element before clicking it.

Body:
Can you please share html, have you tried with Visible instead of Clickable

public static void WaitOnPageForXPathClickable(string selector)
{
    new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible((By.XPath(selector))));
}

You can wait for the page to be fully loaded with something like:

        public void WaitForPageToBeFullyLoaded(int timeSpan)
    {
        new WebDriverWait(Driver, TimeSpan.FromSeconds(timeSpan)).Until(
            d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));
    }

You can check for displayed or Enabled element too.


问:
Dynamic SMS API integration php
I have made php system .
in this system user must set his sms api information and system will automatically send sms to his clients

my problem is that  there are many sms api and every api need different info
for example(clickatell api need apiKey to be joined with url, receiver phone number ) but the another api need another information (username, password,to, from )

how can I allow user to integrate his sms api dynamically

答:
I do not know much about your system but generally speaking, in such situations where you have to deal with different forms of such external configuration, I can suggest a pattern.

There will always be a parameter called the $apiType of the SMS API: So you let the user select one of those first. Based on this selection, you ask for the values for selected API.

And of course, when your system needs to support more APIs, you add that to the list of possible values for the $apiType parameter along with corresponding fields.

Hope that works out for you.

Title: Dynamic SMS API integration php


问:
Magnolia JCR get LinkedList Property Items

I am trying to retrieve the node 0's property - tag values, which is a linkedList object property I believe. as you can see it is [****,****]

I wish to retrieve the object value and store into a List<String> object
So I can get the each value out for late use, e.g

```<code>String idA = "542f74fd-bfaf-4377-854a-8e62082edc6c";
string idB = "39aab11f-243f-464c-ae6d-c1f069f17d6c";
</code>```

My attampt is something like below:

```<code>List<String> tagList = new ArrayList<String>();
tagList = componentNode.getProperties(node, "tags");
</code>```

also tried this:

```<code>List<String> tagList = new ArrayList<String>();
tagList = PropertyUtil.getProperty(node, "tags");
</code>```

but none of them works.

Please suggest me with code sample.
Thanks

答:
I believe they are called multi value properties in JCR and is supported via Arrays instead of Lists.

I haven't tested the code myself but I believe it'll work.
This should do the trick:

```<code>  Property property = node.getProperty("tags");
  Value[] tags = property.getValues();
</code>```

and then you can convert/wrap it to List if you really want to.

Hope that helps,

Cheers,

Body:
I am trying to retrieve the node 0's property - tag values, which is a linkedList object property I believe. as you can see it is [****,****]

I wish to retrieve the object value and store into a List<String> object
So I can get the each value out for late use, e.g

String idA = "542f74fd-bfaf-4377-854a-8e62082edc6c";
string idB = "39aab11f-243f-464c-ae6d-c1f069f17d6c";

My attampt is something like below:

List<String> tagList = new ArrayList<String>();
tagList = componentNode.getProperties(node, "tags");

also tried this:

List<String> tagList = new ArrayList<String>();
tagList = PropertyUtil.getProperty(node, "tags");

but none of them works.

Please suggest me with code sample.
Thanks

Body:
I believe they are called multi value properties in JCR and is supported via Arrays instead of Lists.

I haven't tested the code myself but I believe it'll work.
This should do the trick:

  Property property = node.getProperty("tags");
  Value[] tags = property.getValues();

and then you can convert/wrap it to List if you really want to.

Hope that helps,

Cheers,


问:
How do I pass arguments to bash?
So I am writing a bash script which will decrypt a file so I what the syntax of the the command to be decrypt [file.jpg]
 So far this is my script :

```<code>openssl enc -d -aes-256-cbc -in file.jpg > file
 echo "Please make sure you add the correct extension to
the file."
</code>```

Spent a lot time trying to achieve my goal but it doest work so I would like some help. Like suppose the file name is movie.mov I should be able to decrypt it using decrypt movie.mov or any other file.

EDIT: Thanks for all your answer but I found the answer which I approved to be simple and sorry I can't approve multiple answer all the answer give some new information!

答:
How do I pass arguments to bash?

( I suppose You mean '... to a bash script?'. )

You just add the argument after the command name.

Then, in your script, You may use $1 to get the first argument, $2 to get the second argument, and so on.

See here: https://www.gnu.org/software/bash/manual/html_node/Positional-Parameters.html#Positional-Parameters

To solve Your problem You may:

Create a file './decrypt' with the content:

#!/bin/bash
openssl enc -d -aes-256-cbc -in "$1"

Add execution rights to the file:

chmod +x ./decrypt

Then in order to decrypt the file movie.mov:

./decrypt movie.mov > movie.mov.decrypted

IMPORTANT: Remember that doing: decrypt movie.mov > movie.mov will result in an empty file! See here: bash redirect input from file back into same file

You may also want to add Your new script to path, see here: Add a bash script to path

Title: How do I pass arguments to bash?

Body:
So I am writing a bash script which will decrypt a file so I what the syntax of the the command to be decrypt [file.jpg]
 So far this is my script :

openssl enc -d -aes-256-cbc -in file.jpg > file
 echo "Please make sure you add the correct extension to
the file."

Spent a lot time trying to achieve my goal but it doest work so I would like some help. Like suppose the file name is movie.mov I should be able to decrypt it using decrypt movie.mov or any other file.

EDIT: Thanks for all your answer but I found the answer which I approved to be simple and sorry I can't approve multiple answer all the answer give some new information!


问:
When you program in as3, do you usually use classes?
I want other programmers' opinions on this.  When you program in as3, do you usually use classes?  Why?</p>

答: Always, because it makes big projects humanly manageable. Also, classes are reusable in any other projects. Object-oriented Programming was not invented for nothing; big projects would be impossible to manage.</p>


问:
Alfresco SDK Custom REST API without WebScripts
It's possible to expose custom REST services in Alfresco SDK AMP without Alfresco WebScripts but using other methods like Jersey (JAX-RS) or Spring REST Controllers since it has Spring framework support ?

答:
I found a solution using a library provided by Daniel Gradecak
. It provides simple samples which are very helpful. As far I understood, the library provide a Spring MVC wrapper around the WebScripts. You can check out here.</p>


问:
how to access java web application with ip address without entry the port
I'm using glassfish 4.1 server with port 8080.

my apps can access by hit localhost:8080 or using my_ip_address:8080.

now, I want access my apps only with ip address without entry the port, say my ip is 10.1.2.133, so when I hit 10.1.2.133 it's go to my apps.
how to do it?

I've tried changing the port to 80 and it worked so well. but I still want to use port 8080 instead 80.

答:
You can run another server that points to your server on 8080. Your other server would then be running on port 80 as this is the default port.

Config on Apache would be something like this:

```<code><VirtualHost *:80>
    ServerName sample.com

    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    ProxyRequests Off
    ProxyPreserveHost On
    ProxyPass / http://YOUR_IP_HERE:8080/
    ProxyPassReverse / http://YOUR_IP_HERE:8080/
    RewriteEngine On

    <!--other config here-->
</VirtualHost>
</code>```

Body:
You can run another server that points to your server on 8080. Your other server would then be running on port 80 as this is the default port.

Config on Apache would be something like this:

<VirtualHost *:80>
    ServerName sample.com

    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    ProxyRequests Off
    ProxyPreserveHost On
    ProxyPass / http://YOUR_IP_HERE:8080/
    ProxyPassReverse / http://YOUR_IP_HERE:8080/
    RewriteEngine On

    <!--other config here-->
</VirtualHost>


问:
change event is not detecting in angular 4 IE11
I am building a Angular4 project using Angular CLI (1.4.9). change event is detecting in Chrome and firefox but when I tried to use IE11 change event is not detecting only:</p>

答:
First thing to do is check your polyfills as the (change) event should get fired when you focus of the element if it has changed.

I don't know if this will work in your scenario or not but I know this will capture change events in IE11

```<code><input (input)="somefunction($event)" type="text">

someFunction(event) {
  event.target.value // this will be the value of the input
}
</code>```

I hope this helps.

Body:
First thing to do is check your polyfills as the (change) event should get fired when you focus of the element if it has changed.

I don't know if this will work in your scenario or not but I know this will capture change events in IE11

<input (input)="somefunction($event)" type="text">

someFunction(event) {
  event.target.value // this will be the value of the input
}

I hope this helps.


问:
Scala IDE for data science applications (like RStudio / Spyder / Rodeo)
With the rise of Spark, Scala has gained a tremendous momentum as programming language of choice for data science applications.

To increase the efficiency when working on data science applications, specialized IDEs have been released for

R (e.g. RStudio) and

Python (e.g. Spyder or Rodeo, see Is there something like RStudio for Python?).

Is there something similar for Scala?

答: Your best shot (nothing like rstudio but this would be your best shot for scala) is apache zeppelin


问:
How can I verify a plaintext password with a hash algorithm?
I have a question about salts. For example, there is a record in our
database that looks like this:

```<code>Password: YUphoRF70vJEPAOjMmc/9n47hyQ=
Password Format: 1
Password Salt: Vx37L8ItQo3rJzx5gRCxTw==
</code>```

I am trying to verify this password, but the method I am using isn't working.

This is the method:

```<code>public static string EncodePassword(string pass, string salt)
{
    byte[] bytes = Encoding.Unicode.GetBytes(pass);
    byte[] src = Encoding.Unicode.GetBytes(salt);
    byte[] dst = new byte[src.Length + bytes.Length];
    Buffer.BlockCopy(src, 0, dst, 0, src.Length);
    Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
    HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
    byte[] inArray = algorithm.ComputeHash(dst);
    return Convert.ToBase64String(inArray);
}
</code>```

And I pass it like this:

```<code>string encodedPasswd = Cryptography.EncodePassword(ClearTxtPassword, DbPasswordSalt);
</code>```

What comes back does not look like the password in the database.

I am wondering if there is something else I should be doing to the salt? Is
what is stored in the DB what I should be passing to the EncodePassword method or is
there a step in between in which I should be decoding it prior to passing it as a
parameter?

I am just not sure why I am getting a password mismatch. According to the web.config of the site I am working on, it is passwordFormat="Hashed" and the PasswordFormat column in the DB says "1" so I know it is SHA1.

Do you have any ideas why I am not getting the right match or how to get further along in figuring it out?(And yes, I have the right password.)

EDIT:

I have tried the following updated method:

```<code>public static string EncodePassword(string pass, string salt)
{
    byte[] bytes = Encoding.Unicode.GetBytes(pass);
    byte[] src = Convert.FromBase64String(salt);
    byte[] dst = new byte[src.Length + bytes.Length];
    Buffer.BlockCopy(src, 0, dst, 0, src.Length);
    Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
    HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
    byte[] inArray = algorithm.ComputeHash(dst);
    return Convert.ToBase64String(inArray);
}
</code>```

Against my current DB data and it still isn't matching up. For example, I am getting
the following results:

```<code>passwordText = "administrator"
passwordformat: 1 / SHA1
passwordSaltInDb: "zVhahfmXj9MrOQySyPQ1Qw=="
passwordInDb = "YZ5xRJkNG9erGStAkWJA3hID9vE="

encodedPasswordResults = "DWZ6XRtVMy4l+XSUOKoX8usUOJI="
</code>```

Is there any way that somebody could test on in their own environment to see why I am getting such different results?

答: SHA1 isn't readily decryptable, which is one of the reasons it's used to store passwords. Why are you trying to decrypt the passwords?</p>

Body:
I have a question about salts. For example, there is a record in our
database that looks like this:

Password: YUphoRF70vJEPAOjMmc/9n47hyQ=
Password Format: 1
Password Salt: Vx37L8ItQo3rJzx5gRCxTw==

I am trying to verify this password, but the method I am using isn't working.

This is the method:

public static string EncodePassword(string pass, string salt)
{
    byte[] bytes = Encoding.Unicode.GetBytes(pass);
    byte[] src = Encoding.Unicode.GetBytes(salt);
    byte[] dst = new byte[src.Length + bytes.Length];
    Buffer.BlockCopy(src, 0, dst, 0, src.Length);
    Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
    HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
    byte[] inArray = algorithm.ComputeHash(dst);
    return Convert.ToBase64String(inArray);
}

And I pass it like this:

string encodedPasswd = Cryptography.EncodePassword(ClearTxtPassword, DbPasswordSalt);

What comes back does not look like the password in the database.

I am wondering if there is something else I should be doing to the salt? Is
what is stored in the DB what I should be passing to the EncodePassword method or is
there a step in between in which I should be decoding it prior to passing it as a
parameter?

I am just not sure why I am getting a password mismatch. According to the web.config of the site I am working on, it is passwordFormat="Hashed" and the PasswordFormat column in the DB says "1" so I know it is SHA1.

Do you have any ideas why I am not getting the right match or how to get further along in figuring it out?(And yes, I have the right password.)

EDIT:

I have tried the following updated method:

public static string EncodePassword(string pass, string salt)
{
    byte[] bytes = Encoding.Unicode.GetBytes(pass);
    byte[] src = Convert.FromBase64String(salt);
    byte[] dst = new byte[src.Length + bytes.Length];
    Buffer.BlockCopy(src, 0, dst, 0, src.Length);
    Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
    HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
    byte[] inArray = algorithm.ComputeHash(dst);
    return Convert.ToBase64String(inArray);
}

Against my current DB data and it still isn't matching up. For example, I am getting
the following results:

passwordText = "administrator"
passwordformat: 1 / SHA1
passwordSaltInDb: "zVhahfmXj9MrOQySyPQ1Qw=="
passwordInDb = "YZ5xRJkNG9erGStAkWJA3hID9vE="

encodedPasswordResults = "DWZ6XRtVMy4l+XSUOKoX8usUOJI="

Is there any way that somebody could test on in their own environment to see why I am getting such different results?


问:
TFS Online and Visual Studio 2013

I am trying to automate my builds/releases. I'm using VS 2013 for development and I put my team project on VSTS (Visual Studio Team Services). I downloaded "Build and Release Agent" and installed a private agent on my machine. Agent connected successfully and listening for jobs as well. But when I am trying to create a build from Visual Studio Online it doesn't build and fails. The error that I am getting is

Error: Visual Studio 2015 is not found. Try again with a version that exists on your build agent machine

Do I need to get Visual Studio 2015? But I don't have a license for that.

答:
When you register an agent, Visual Studio Team Services (VSTS) scans the machine to determine which tools are installed and can be used for building software. This can be versions of Visual Studio, Java, NPM etc. This makes up the capabilities of your agent. If you navigate to https://.visualstudio.com/_admin/_AgentPool?poolId=1&_a=agents, you can then select your pool and agent (by default, the pool is default and the agent name is your machine name). You can then view the capabilities of the agent like shown here:

Now when you create a build, each task also has a set of demands. When you queue a build, VSTS looks for an agent that has the right set of capabilities to meet the demands of the build definition. When such an agent cannot be found, you get an error like what you're seeing.

So you've probably added a task that requires VS 2015. Some tasks allow you to specify the VS version you want to use. If that's not possible, you could look into using another task or maybe using one of the free Community Editions to upgrade your machine.

Title: TFS Online and Visual Studio 2013


问:
Fill in the blanks won't fill in for repeat letters (Simple Program)
I'm making a program where someone has to fill in the blanks for a word. The correct blank is supposed to be filled in with the given guess, and then that list carries over so that they can keep guessing for 10 tries. It's a relatively simple code.

```<code>word = "nonagon"

wordlist=[]
blanks=[]
for i in word:
    wordlist.append(i)
    blanks.append("-")
attempts = 10

while attempts != 0:
    guess = input("Take a guess: ")
     for i in wordlist:
        if i == guess:
            blanks[wordlist.index(i)]=guess
            attempts-=1

    print(blanks)
</code>```

Basically, my program won't print a letter more than once.

E.g. if I type in "n" it won't print "n" more than once, even though "n" appears 3 times in "nonagon". I'm assuming it sees that first "n" in "nonagon" and only regards that one.

How would I go about making it print letters even if they repeat?

答:
Solution

```<code>word = "nonagon"
guessword = ""
for i in word:
    guessword += "_"
for i in range(10):
    guess = raw_input("Take a guess: ")
    guess = guess[0]
    new_guessword = ""
    j = 0
    for ch in word:
        if guess == ch:
            new_guessword += ch
        else:
            new_guessword += guessword[j]
        j += 1
    guessword = new_guessword
    if word == guessword:
        print("You solved it!!")
    else:
        print(guessword)
</code>```

Body:
I'm making a program where someone has to fill in the blanks for a word. The correct blank is supposed to be filled in with the given guess, and then that list carries over so that they can keep guessing for 10 tries. It's a relatively simple code.

word = "nonagon"

wordlist=[]
blanks=[]
for i in word:
    wordlist.append(i)
    blanks.append("-")
attempts = 10

while attempts != 0:
    guess = input("Take a guess: ")
     for i in wordlist:
        if i == guess:
            blanks[wordlist.index(i)]=guess
            attempts-=1

    print(blanks)

Basically, my program won't print a letter more than once.

E.g. if I type in "n" it won't print "n" more than once, even though "n" appears 3 times in "nonagon". I'm assuming it sees that first "n" in "nonagon" and only regards that one.

How would I go about making it print letters even if they repeat?

Body:
Solution

word = "nonagon"
guessword = ""
for i in word:
    guessword += "_"
for i in range(10):
    guess = raw_input("Take a guess: ")
    guess = guess[0]
    new_guessword = ""
    j = 0
    for ch in word:
        if guess == ch:
            new_guessword += ch
        else:
            new_guessword += guessword[j]
        j += 1
    guessword = new_guessword
    if word == guessword:
        print("You solved it!!")
    else:
        print(guessword)


问:
Return empty table after rollback
Im writing a procedure, I want it to return table if there wasnt any rollbacks, and return empty table / nothing if there was at least 1 rollback.

```<code>DELIMITER $$
CREATE PROCEDURE payment(IN amount int, IN profession varchar(50))
BEGIN
DECLARE done BOOL DEFAULT FALSE;
DECLARE salary INT;
DECLARE pes VARCHAR(11);
DECLARE summary INT DEFAULT 0;

DECLARE employee_cursor CURSOR FOR (SELECT RIGHT(PESEL,3), pensja FROM Pracownicy WHERE zawod=profession);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

DROP TEMPORARY TABLE IF EXISTS tmp1;
CREATE TEMPORARY TABLE tmp1(pesel char(11), status varchar(20) DEFAULT 'wyplacono');

SET AUTOCOMMIT =0;
START TRANSACTION;
    OPEN employee_cursor;
    readLoop : LOOP
        FETCH employee_cursor INTO pes,salary;
        IF done THEN
            LEAVE readLoop;
        END IF;

        SET summary = summary + salary;

        IF( summary > amount ) THEN
            ROLLBACK;
        END IF;

        INSERT INTO tmp1(pesel) VALUES(CONCAT('********',pes));

    END LOOP;
    CLOSE employee_cursor;
    COMMIT;
    SELECT * from tmp1;
END $$
DELIMITER ;
</code>```

As far it works fine when it doesnt rollback, but

```<code>INSERT INTO tmp1(pesel) VALUES(CONCAT('********',pes));
</code>```

seems to ignore transaction :/

答: move the rollback test to outside the loop.</p>

Title: Return empty table after rollback

Body:
Im writing a procedure, I want it to return table if there wasnt any rollbacks, and return empty table / nothing if there was at least 1 rollback.

DELIMITER $$
CREATE PROCEDURE payment(IN amount int, IN profession varchar(50))
BEGIN
DECLARE done BOOL DEFAULT FALSE;
DECLARE salary INT;
DECLARE pes VARCHAR(11);
DECLARE summary INT DEFAULT 0;

DECLARE employee_cursor CURSOR FOR (SELECT RIGHT(PESEL,3), pensja FROM Pracownicy WHERE zawod=profession);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

DROP TEMPORARY TABLE IF EXISTS tmp1;
CREATE TEMPORARY TABLE tmp1(pesel char(11), status varchar(20) DEFAULT 'wyplacono');

SET AUTOCOMMIT =0;
START TRANSACTION;
    OPEN employee_cursor;
    readLoop : LOOP
        FETCH employee_cursor INTO pes,salary;
        IF done THEN
            LEAVE readLoop;
        END IF;

        SET summary = summary + salary;

        IF( summary > amount ) THEN
            ROLLBACK;
        END IF;

        INSERT INTO tmp1(pesel) VALUES(CONCAT('********',pes));

    END LOOP;
    CLOSE employee_cursor;
    COMMIT;
    SELECT * from tmp1;
END $$
DELIMITER ;

As far it works fine when it doesnt rollback, but

INSERT INTO tmp1(pesel) VALUES(CONCAT('********',pes));

seems to ignore transaction :/


问:
jQuery/JS - Count results within DIV
I'm fairly noob with JS, so go easy.

I have a simple search form that searches the entire BODY and highlights the search term after a click function. This is working great.  However, I'd like to add the function to return the number of results found (in addition to the in-place highlight function).  EDIT:  Also, the results are not displayed on the page, they are only highlighted by the JS script by design.  So, essentially, I just need a way to display the number of results that are highlighted after the search is performed.

All I could find was how to do this with data that is in a table. However, my data is NOT in a table.

Also, This can't be a "live" search, I need it to fire only after the click event has been fired.

This closest solution I could find was HERE but, this is a live search in a table.

Here is my form so far:

$('document').ready(function() {

  $('#button').click(function() {
    var searchbox = document.querySelector('#text-search');
    var searchForm = document.querySelector('#search');
  });
});

function highlight() {
  var text = document.getElementById("text-search").value;
  var query = new RegExp("(\\b" + text + "\\b)", "gim");
  var e = document.getElementById("body").innerHTML;
  var enew = e.replace(/(|<\/span>)/igm, "");
  document.getElementById("body").innerHTML = enew;
  var newe = enew.replace(query, "$1");
  document.getElementById("body").innerHTML = newe;
  color = "#f6f";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<body>

  <div id="search" class="Column">
    <form id="searchForm" method="post" action="" onsubmit="highlight(); return false;">
      <input name="text-search" id="text-search" type="text" value="" class="input" placeholder="search & highlight">
      <input id="submit" type="submit" value="Submit" class="button" />
    </form>
    <div class="count">search results: </div>
  </div>

  <div class="slide">
    <div class="expand">
      data
    </div>
  </div>

</body></code>```

UPDATE:

I almost found a solution thanks to a JS wizard who was helping me with another issue.  So the code below IS counting the number of results, however, it's adding +1 for every DIV on the page, even if the searched term does not exist in that DIV. So, if my body looked like the example below and I searched TEST, the result would be 5 (2 search terms + 3 DIVs)

Body:

```<code><div1>
  test
</div>
<div2>
  test
</div>
<div3>
  hai
</div>
</code>```

JS:

```<code>function count() {
  var count =
  $("#body span").length;
  $(".count").text(count);
};
</code>```

So, how can I adjust for the number of DIVs?

https://jsfiddle.net/seanvree/mqyxqfgu/

答:
Your code seems to be wrapping the matches in a span. You could add a class like "match", and count the spans with class match
 Something like this:</p>

```<code>var matches= $('span.match').length;
</code>```

Title: jQuery/JS - Count results within DIV

Body:
I'm fairly noob with JS, so go easy.

I have a simple search form that searches the entire BODY and highlights the search term after a click function. This is working great.  However, I'd like to add the function to return the number of results found (in addition to the in-place highlight function).  EDIT:  Also, the results are not displayed on the page, they are only highlighted by the JS script by design.  So, essentially, I just need a way to display the number of results that are highlighted after the search is performed.

All I could find was how to do this with data that is in a table. However, my data is NOT in a table.

Also, This can't be a "live" search, I need it to fire only after the click event has been fired.

This closest solution I could find was HERE but, this is a live search in a table.

Here is my form so far:

$('document').ready(function() {

  $('#button').click(function() {
    var searchbox = document.querySelector('#text-search');
    var searchForm = document.querySelector('#search');
  });
});

function highlight() {
  var text = document.getElementById("text-search").value;
  var query = new RegExp("(\\b" + text + "\\b)", "gim");
  var e = document.getElementById("body").innerHTML;
  var enew = e.replace(/(|<\/span>)/igm, "");
  document.getElementById("body").innerHTML = enew;
  var newe = enew.replace(query, "$1");
  document.getElementById("body").innerHTML = newe;
  color = "#f6f";
}

    <form id="searchForm" method="post" action="" onsubmit="highlight(); return false;">
      <input name="text-search" id="text-search" type="text" value="" class="input" placeholder="search & highlight">
      <input id="submit" type="submit" value="Submit" class="button" />
    </form>

search results:

      data

UPDATE:

I almost found a solution thanks to a JS wizard who was helping me with another issue.  So the code below IS counting the number of results, however, it's adding +1 for every DIV on the page, even if the searched term does not exist in that DIV. So, if my body looked like the example below and I searched TEST, the result would be 5 (2 search terms + 3 DIVs)

Body:

<div1>
  test

<div2>
  test

<div3>
  hai

JS:

function count() {
  var count =
  $("#body span").length;
  $(".count").text(count);
};

So, how can I adjust for the number of DIVs?

https://jsfiddle.net/seanvree/mqyxqfgu/

Body:
Your code seems to be wrapping the matches in a span. You could add a class like "match", and count the spans with class match
 Something like this:

var matches= $('span.match').length;


问:
android:dither="true" does not dither, what's wrong?
I've been trying to get android to dither the background image of an activity - so far without success. I have no clue what's wrong.

This is what I did:

The root element of my activity layout is a LinearLayout:

```<code><LinearLayout android:id="@+id/AbsoluteLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:gravity="center_horizontal"
android:background="@drawable/background_dither">
</code>```

where I added @drawable/background_dither as the background image.
I put an XML file "background_dither.xml" in drawable-hdpi with the following content:

```<code><?xml version="1.0" encoding="utf-8"?>
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/backimg"
android:src="@drawable/background"
android:dither="true"
android:antialias="true" />
</code>```

which references the actual image background.png in drawable-hdpi. The image, which includes a large color gradient, does show up, but with heavy color banding. From what I've learned from the SDK, this can be mitigated by using the /above proxy image definition together with specifying android:dither="true". This however, has absolutely no effect.

What am I missing to get dithering working?

EDIT: Uploaded the sources here

EDIT2: After none of the suggested methods helped to get rid of color banding, after reading this blog post from Romain Guy  I had the idea to check whether my PNG background has an alpha channel. It didn't. After adding one, android actually seems to use RGB8888, as said in the post and the banding is gone (also for 2.2). Still wondering why the other methods didn't work.

EDIT3: One has to make sure that the PNG not only has an alpha channel, but also at least one pixel that has an alpha value != FF, otherwise the android build tools will again strip that bitmap down to an indexed palette without alpha channel.

答:
Try to put this line

```<code>getWindow().setFormat(PixelFormat.RGBA_8888);
</code>```

just after super.onCreate()  and see if it helps.

Body:
I've been trying to get android to dither the background image of an activity - so far without success. I have no clue what's wrong.

This is what I did:

The root element of my activity layout is a LinearLayout:

<LinearLayout android:id="@+id/AbsoluteLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:gravity="center_horizontal"
android:background="@drawable/background_dither">

where I added @drawable/background_dither as the background image.
I put an XML file "background_dither.xml" in drawable-hdpi with the following content:

<?xml version="1.0" encoding="utf-8"?>
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/backimg"
android:src="@drawable/background"
android:dither="true"
android:antialias="true" />

which references the actual image background.png in drawable-hdpi. The image, which includes a large color gradient, does show up, but with heavy color banding. From what I've learned from the SDK, this can be mitigated by using the /above proxy image definition together with specifying android:dither="true". This however, has absolutely no effect.

What am I missing to get dithering working?

EDIT: Uploaded the sources here

EDIT2: After none of the suggested methods helped to get rid of color banding, after reading this blog post from Romain Guy  I had the idea to check whether my PNG background has an alpha channel. It didn't. After adding one, android actually seems to use RGB8888, as said in the post and the banding is gone (also for 2.2). Still wondering why the other methods didn't work.

EDIT3: One has to make sure that the PNG not only has an alpha channel, but also at least one pixel that has an alpha value != FF, otherwise the android build tools will again strip that bitmap down to an indexed palette without alpha channel.

Body:
Try to put this line

getWindow().setFormat(PixelFormat.RGBA_8888);

just after super.onCreate()  and see if it helps.


问:
iOS MDM Kiosk mode
I have a supervised iPad with few applications installed.
When I push a kiosk mode profile for running only single app, iPad switches to single app mode.

What happens if there is an update available to the app running in the kiosk mode?

答:
iOS doesn’t allow any updates in Kiosk mode. So, as an admin, if one needs to update the app, you would remove the app lock policy, then push the app update, and then re-apply the app lock policy.

This post helped me

Title: iOS MDM Kiosk mode


问:
Dropdown Menu is not overlapping Slick Gallery
I have jQuery Slick Gallery and inside it I have a Dropdown Menu. A button shows the currently selected entry and the menu entries are an unordered list which appear when the button is clicked.

The unordered list is hidden at the bottom edge but should appear above the dots. You can see the problem also on the image below:

An example what I try to do you can find here: http://jsfiddle.net/45cst6nq/

HTML

```<code><section class="slider">
  <div>
    <ul class="list">
      <li>Please select</li>
      <li>Point 1</li>
      <li>Point 2</li>
      <li>Point 3</li>
      <li>Point 4</li>
      <li>Point 5</li>
      <li>Point 6</li>
      <li>Point 7</li>
      <li>Point 8</li>
      <li>Point 9</li>
      <li>Point 10</li>
    </ul>
  </div>
  <div>slide2</div>
  <div>slide3</div>
  <div>slide4</div>
  <div>slide5</div>
  <div>slide6</div>
</section>
</code>```

CSS

```<code>$c1: #3a8999;
$c2: #e84a69;

.slider {
    width: auto;
    margin: 30px 50px 50px;
}

.slick-slide {
    background: $c1;
    color: white;
    padding: 40px 0;
    font-size: 30px;
    font-family: "Arial", "Helvetica";
    text-align: center;
}

.slick-prev:before,
.slick-next:before {
    color: black;
}

.slick-dots {
    bottom: -30px;
}

.slick-slide:nth-child(odd) {
     background: $c2;
}

.list {
  position: absolute;
  top: 0;
}
</code>```

JS

```<code>$(".slider").slick({
    autoplay: false,
    dots: true,
    responsive: [{
        breakpoint: 500,
        settings: {
            dots: false,
            arrows: false,
            infinite: false,
            slidesToShow: 2,
            slidesToScroll: 2
        }
    }]
});
</code>```

This is a simplyfied example to demonstrate the issue. The components I am showing on my customor project are a little bit more complex.

I already tried to fix this with changing z-index and overflows. It looks like it's working when I set overflow-x to visible but than the cloned slides also get visible. Using overflow-y: visible; doesn't work.
Why does only overflow-x: visible shows the list correctly overlapping, but overflow-y: visible; does not? For me this doesn't make sense.

Is there a possibility to solve the issue? I like the slick gallery in general and don't want to write my own for this case.

答:
I'm not sure I understand what you're trying to achieve.

An unordered list can't be a dropdown i.e. a html select element. I forked your fiddle and used a select instead of the ul and everything looks ok.

https://jsfiddle.net/o1prjfcw/2/

```<code><section class="slider">
    <div>
      <select>
        <option value="point1">Point 1</option>
        <option value="point2">Point 2</option>
        <option value="point3">Point 3</option>
        <option value="point4">Point 4</option>
      </select>
    </div>
    <div>slide2</div>
...
</code>```

You can obviously stile your select element to something that fits the rest of your page.

Body:
I have jQuery Slick Gallery and inside it I have a Dropdown Menu. A button shows the currently selected entry and the menu entries are an unordered list which appear when the button is clicked.

The unordered list is hidden at the bottom edge but should appear above the dots. You can see the problem also on the image below:

An example what I try to do you can find here: http://jsfiddle.net/45cst6nq/

HTML

Please select

Point 1

Point 2

Point 3

Point 4

Point 5

Point 6

Point 7

Point 8

Point 9

Point 10

slide2

slide3

slide4

slide5

slide6

CSS

$c1: #3a8999;
$c2: #e84a69;

.slider {
    width: auto;
    margin: 30px 50px 50px;
}

.slick-slide {
    background: $c1;
    color: white;
    padding: 40px 0;
    font-size: 30px;
    font-family: "Arial", "Helvetica";
    text-align: center;
}

.slick-prev:before,
.slick-next:before {
    color: black;
}

.slick-dots {
    bottom: -30px;
}

.slick-slide:nth-child(odd) {
     background: $c2;
}

.list {
  position: absolute;
  top: 0;
}

JS

$(".slider").slick({
    autoplay: false,
    dots: true,
    responsive: [{
        breakpoint: 500,
        settings: {
            dots: false,
            arrows: false,
            infinite: false,
            slidesToShow: 2,
            slidesToScroll: 2
        }
    }]
});

This is a simplyfied example to demonstrate the issue. The components I am showing on my customor project are a little bit more complex.

I already tried to fix this with changing z-index and overflows. It looks like it's working when I set overflow-x to visible but than the cloned slides also get visible. Using overflow-y: visible; doesn't work.
Why does only overflow-x: visible shows the list correctly overlapping, but overflow-y: visible; does not? For me this doesn't make sense.

Is there a possibility to solve the issue? I like the slick gallery in general and don't want to write my own for this case.

Body:
I'm not sure I understand what you're trying to achieve.

An unordered list can't be a dropdown i.e. a html select element. I forked your fiddle and used a select instead of the ul and everything looks ok.

https://jsfiddle.net/o1prjfcw/2/

<section class="slider">
    <div>
      <select>
        <option value="point1">Point 1</option>
        <option value="point2">Point 2</option>
        <option value="point3">Point 3</option>
        <option value="point4">Point 4</option>
      </select>
    </div>
    <div>slide2</div>
...

You can obviously stile your select element to something that fits the rest of your page.


问:
In Anaconda, RStudio bash does not find Git

I have installed both RStudio v1.1.383 and Git 2.15.0 using the Anaconda platform on Windows 10.

In RStudio global config, I have already provided the path to git.exe, provided a RSA key, checked "Enable version control interface for RStudio projects", and new terminals open with "Git bash".

In project options, VCS is set to Git.

I have successfully commited files to my local git, but I need to access the Shell to push them to GitHub.

The problem is: when I open RStudio's Shell, it doesn't find Git.

```<code>bash-4.3$ git
bash: git: command not found
</code>```

How can I solve this?

答:
I reinstalled Git using the conda-forge version and now it works as expected.</p>

```<code>conda install -c conda-forge git
</code>```

Body:
I have installed both RStudio v1.1.383 and Git 2.15.0 using the Anaconda platform on Windows 10.

In RStudio global config, I have already provided the path to git.exe, provided a RSA key, checked "Enable version control interface for RStudio projects", and new terminals open with "Git bash".

In project options, VCS is set to Git.

I have successfully commited files to my local git, but I need to access the Shell to push them to GitHub.

The problem is: when I open RStudio's Shell, it doesn't find Git.

bash-4.3$ git
bash: git: command not found

How can I solve this?

Body:
I reinstalled Git using the conda-forge version and now it works as expected.

conda install -c conda-forge git


问:
Setting a max-width for flex items?
I'm trying to create a filter section on my site, the content is all generated dynamically (so I can't add extra parents to it), and our styleguide creates them using flex items. I'd like to keep this functionality for the most part.

I want my 3 flex items to have a max-width and be floated left, leaving my non flex item floated right, in the overall container that is set to a max width of 1080px sort of like this:

```<code>Option 1    Option 2    Option 3                                    Non-flex Item
</code>```

I've tried setting the flex-align values and following this answer, but that doesn't seem to work for this.

As of right now, this is the code that I am working with:

One

Three

Three

       I'm not a flex item

```
<pre class="lang-css prettyprint-override"><code>.container {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-direction: row;
    flex-direction: row;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    position: relative;
    max-width: 1080px;
    margin: 0 auto;
    padding: 0 20px;
    box-sizing: content-box;
}

.child {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-direction: row;
    flex-direction: row;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    position: relative;
}
</code>```

I also made a Fiddle for you all to play around.

答:
I would apply a width or min-width to the .child items (or left/right padding that creates the distance between them) and margin-left: auto to the last item, which moves it right, independently from the others:

https://jsfiddle.net/6vwny6bz/2/

.container {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
  position: relative;
  max-width: 1080px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: content-box;
}

.child {
  list-style: none;
  min-width: 80px;
  padding: 10px 0;
}

.non-flex {
  margin-left: auto;
  padding: 10px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="container">
  <li class="child">One</li>
  <li class="child">Three</li>
  <li class="child">Three</li>
  <div class="non-flex">
    I'm not a flex item
  </div>
</ul></code>```

ContentLicense: CC BY-SA 4.0

Title: Setting a max-width for flex items?

Body:
I'm trying to create a filter section on my site, the content is all generated dynamically (so I can't add extra parents to it), and our styleguide creates them using flex items. I'd like to keep this functionality for the most part.

I want my 3 flex items to have a max-width and be floated left, leaving my non flex item floated right, in the overall container that is set to a max width of 1080px sort of like this:

Option 1    Option 2    Option 3                                    Non-flex Item

I've tried setting the flex-align values and following this answer, but that doesn't seem to work for this.

As of right now, this is the code that I am working with:

One

Three

Three

       I'm not a flex item

.container {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-direction: row;
    flex-direction: row;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    position: relative;
    max-width: 1080px;
    margin: 0 auto;
    padding: 0 20px;
    box-sizing: content-box;
}

.child {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-direction: row;
    flex-direction: row;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    position: relative;
}

I also made a Fiddle for you all to play around.

Body:
I would apply a width or min-width to the .child items (or left/right padding that creates the distance between them) and margin-left: auto to the last item, which moves it right, independently from the others:

https://jsfiddle.net/6vwny6bz/2/

.container {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
  position: relative;
  max-width: 1080px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: content-box;
}

.child {
  list-style: none;
  min-width: 80px;
  padding: 10px 0;
}

.non-flex {
  margin-left: auto;
  padding: 10px 0;
}

<ul class="container">
  <li class="child">One</li>
  <li class="child">Three</li>
  <li class="child">Three</li>
  <div class="non-flex">
    I'm not a flex item
  </div>
</ul>


问:
Node.js issues with exporting functions
I have a few questions about the nature of exporting functions in NodeJS:

Firstly this is an acceptable way to export a function:

```<code>exports.bread = function bread() {
  return 'bread: 2';
};
</code>```

However, it is not possible (maybe?) to export a function using this method:

```<code>function pullData(pair) {
  console.log(pair);
}

module.exports = pullData;
</code>```

The only problem with this second method is that the function is not hoisted and limits its' use elsewhere?

Another method for exporting variables is to include the variables within an object and export that object. However, in this case, the functions within the module have a limited scope...

So is there any easy way to export declarative functions and use them, or is doing so not something I should strive to achieve?

Screenshots from project:

答:
When you write module.exports = something you are exporting only one thing. So your code should look like this

```<code>var pullData = require('./getTicker')
pullData('TEST')
</code>```

If you want to write it the way you have done so then you need to export it differently, as only part of the module.exports object.
You can do this by writing
exports.pullData = pullData in your getTicker file.

Then you can import it and use it like you did:

```<code>var trackData = require('./getTicker')
trackData.pullData('TEST')
</code>```

Title: Node.js issues with exporting functions

Body:
I have a few questions about the nature of exporting functions in NodeJS:

Firstly this is an acceptable way to export a function:

exports.bread = function bread() {
  return 'bread: 2';
};

However, it is not possible (maybe?) to export a function using this method:

function pullData(pair) {
  console.log(pair);
}

module.exports = pullData;

The only problem with this second method is that the function is not hoisted and limits its' use elsewhere?

Another method for exporting variables is to include the variables within an object and export that object. However, in this case, the functions within the module have a limited scope...

So is there any easy way to export declarative functions and use them, or is doing so not something I should strive to achieve?

Screenshots from project:

Body:
When you write module.exports = something you are exporting only one thing. So your code should look like this

var pullData = require('./getTicker')
pullData('TEST')

If you want to write it the way you have done so then you need to export it differently, as only part of the module.exports object.
You can do this by writing
exports.pullData = pullData in your getTicker file.

Then you can import it and use it like you did:

var trackData = require('./getTicker')
trackData.pullData('TEST')


问:
Determining the polarity of emoticons for twitter sentiment analysis
I am trying doing a sentiment analysis on twitter data and want to take the emoticons into account. Say I have the unicode of an emoticon  (in this case U+1F600). I would like to get some kind of positive, negative or neutral polarity score. I have done some research but have been unsuccessful in finding an existing lexicon that I could use. Basically I would like to use an existing lexicon if there is one available instead of going through all emoticons manually and assigning a score. Any suggestions?

I am using Python if it makes any difference.

答: A full lexicon containing emojis and their corresponding Unicode can be downloaded from http://unicode.org/emoji/charts/emoji-list.html .</p>


问:
Convert a JSON into CSV using jq
I have a json file, which is stored in an environment variable temp.

{
  "users": [
    {
      "username": "jack",
      "email": "jack@somewhere.com",
      "total running apps": "1",
      "api-mock-app": "0",
      "flogo": "1",
      "ipaas": "0",
      "nodejs-app": "0"
    },
    {
      "username": "jill",
      "email": "jill@somewhere.com",
      "total running apps": "1",
      "api-mock-app": "0",
      "flogo": "1",
      "ipaas": "0",
      "nodejs-app": "0"
    }
  ]
}

When i am converting this JSON into CSV using this command

```<code>jq -r '.users[] | [.username, .email, .total running apps, .api-mock-app, .flogo, .ipaas, .nodejs-app] | @csv' <<< $temp
</code>```

I am getting following error.

jq: error: syntax error, unexpected IDENT (Unix shell quoting issues?) at , line 1:
.users[] | [.username, .email, .total running apps, .api-mock-app, .flogo, .ipaas, .nodejs-app] | @csv

jq: 1 compile error

Any help Please?

答:
i got this working code click here

    <title>Demo - Covnert JSON to CSV</title>

        JSON

```
    <h1>
        CSV</h1>
    <pre id="csv">```

```

check out this link

Title: Convert a JSON into CSV using jq

Body:
I have a json file, which is stored in an environment variable temp.

{
  "users": [
    {
      "username": "jack",
      "email": "jack@somewhere.com",
      "total running apps": "1",
      "api-mock-app": "0",
      "flogo": "1",
      "ipaas": "0",
      "nodejs-app": "0"
    },
    {
      "username": "jill",
      "email": "jill@somewhere.com",
      "total running apps": "1",
      "api-mock-app": "0",
      "flogo": "1",
      "ipaas": "0",
      "nodejs-app": "0"
    }
  ]
}

When i am converting this JSON into CSV using this command

jq -r '.users[] | [.username, .email, .total running apps, .api-mock-app, .flogo, .ipaas, .nodejs-app] | @csv' <<< $temp

I am getting following error.

jq: error: syntax error, unexpected IDENT (Unix shell quoting issues?) at , line 1:
.users[] | [.username, .email, .total running apps, .api-mock-app, .flogo, .ipaas, .nodejs-app] | @csv

jq: 1 compile error

Any help Please?

Body:
i got this working code click here

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<html>
<head>
    <title>Demo - Covnert JSON to CSV</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>

    <script type="text/javascript">
        // JSON to CSV Converter
        function ConvertToCSV(objArray) {
            var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
            var str = '';

            for (var i = 0; i < array.length; i++) {
                var line = '';
                for (var index in array[i]) {
                    if (line != '') line += ','

                    line += array[i][index];
                }

                str += line + '\r\n';
            }

            return str;
        }

        // Example
        $(document).ready(function () {

            // Create Object
            var items = [
                  { name: "Item 1", color: "Green", size: "X-Large" },
                  { name: "Item 2", color: "Green", size: "X-Large" },
                  { name: "Item 3", color: "Green", size: "X-Large" }];

            // Convert Object to JSON
            var jsonObject = JSON.stringify(items);

            // Display JSON
            $('#json').text(jsonObject);

            // Convert JSON to CSV & Display CSV
            $('#csv').text(ConvertToCSV(jsonObject));
        });
    </script>
</head>
<body>
    <h1>
        JSON</h1>
    <pre id="json"></pre>
    <h1>
        CSV</h1>
    <pre id="csv"></pre>
</body>
</html>

check out this link


问:
How to change pylint message template in VS Code linter?
My goal is to change the pylint message template for the linter messages in VS Code. I'm using the standard "Python" extension for VS Code from Don Jayamanne, that is now maintained directly by Microsoft. By default the message format reads as follows (with a simple whitespace message as an example):

[pylint] C0303:Trailing whitespace

I would like the message instead to read with the pylint message symbol instead of the code (example "C0303"). I prefer the human-readable symbols over the codes. In my opinion easier to work with when disabling certain messages, etc. So, something like this would be preferred:

[pylint] Trailing whitespace (trailing-whitespace)

Here are a few things I have tried so far that haven't worked.

Using .pylintrc file to modify the msg-template= line

I set this line in my .pylintrc file:

```<code>msg-template='{msg} ({symbol})'
</code>```

My changes were reflected when running pylint through a separate terminal outside of VS Code, but not in VS Code. I tried reloading the VS Code window, also, and this had no effect.

Specifying python.linting.pylintArgs in User Settings:

The next thing I tried was setting the option for pylint in VS Code user settings, also with no effect:

```<code>"python.linting.pylintArgs": [
    "--msg-template='{msg} ({symbol})'"
]
</code>```

Ensuring the correct pylint was being used

Finally, I double checked to make sure I didn't have anything strange going on with the path where VS Code was looking for pylint. I did not see anything out of order, as my setting had not been changed from the default:

```<code>"python.linting.pylintPath": "pylint",
</code>```

Any ideas would be appreciated. VS Code is a newer editor for me, and I wasn't sure what my next step might be in troubleshooting this. Thank you!

答:
Looking at the source for vscode-python at 0.7.0, on line 30. The message template argument is explicitly overridden.

The purpose for this is to keep a consistent API for the result of every specific linter implementation. See the abstract BaseLinter class for this.

```<code>public runLinter(document: TextDocument, cancellation: CancellationToken): Promise<baseLinter.ILintMessage[]> {
        ...

            this.run(pylintPath, pylintArgs.concat(['--msg-template=\'{line},{column},{category},{msg_id}:{msg}\'', '--reports=n', '--output-format=text', document.uri.fsPath]), document, this.workspaceRootPath, cancellation).then(messages => {
                messages.forEach(msg => {
                    msg.severity = this.parseMessagesSeverity(msg.type, this.pythonSettings.linting.pylintCategorySeverity);
                });

                resolve(messages);
            }, reject);
        });
    }
</code>```

Next Steps here:

Write an issue on the repository.

Fix the implementation to use pylintArgs over the default.

Body:
My goal is to change the pylint message template for the linter messages in VS Code. I'm using the standard "Python" extension for VS Code from Don Jayamanne, that is now maintained directly by Microsoft. By default the message format reads as follows (with a simple whitespace message as an example):

[pylint] C0303:Trailing whitespace

I would like the message instead to read with the pylint message symbol instead of the code (example "C0303"). I prefer the human-readable symbols over the codes. In my opinion easier to work with when disabling certain messages, etc. So, something like this would be preferred:

[pylint] Trailing whitespace (trailing-whitespace)

Here are a few things I have tried so far that haven't worked.

Using .pylintrc file to modify the msg-template= line

I set this line in my .pylintrc file:

msg-template='{msg} ({symbol})'

My changes were reflected when running pylint through a separate terminal outside of VS Code, but not in VS Code. I tried reloading the VS Code window, also, and this had no effect.

Specifying python.linting.pylintArgs in User Settings:

The next thing I tried was setting the option for pylint in VS Code user settings, also with no effect:

"python.linting.pylintArgs": [
    "--msg-template='{msg} ({symbol})'"
]

Ensuring the correct pylint was being used

Finally, I double checked to make sure I didn't have anything strange going on with the path where VS Code was looking for pylint. I did not see anything out of order, as my setting had not been changed from the default:

"python.linting.pylintPath": "pylint",

Any ideas would be appreciated. VS Code is a newer editor for me, and I wasn't sure what my next step might be in troubleshooting this. Thank you!

Body:
Looking at the source for vscode-python at 0.7.0, on line 30. The message template argument is explicitly overridden.

The purpose for this is to keep a consistent API for the result of every specific linter implementation. See the abstract BaseLinter class for this.

public runLinter(document: TextDocument, cancellation: CancellationToken): Promise<baseLinter.ILintMessage[]> {
        ...

            this.run(pylintPath, pylintArgs.concat(['--msg-template=\'{line},{column},{category},{msg_id}:{msg}\'', '--reports=n', '--output-format=text', document.uri.fsPath]), document, this.workspaceRootPath, cancellation).then(messages => {
                messages.forEach(msg => {
                    msg.severity = this.parseMessagesSeverity(msg.type, this.pythonSettings.linting.pylintCategorySeverity);
                });

                resolve(messages);
            }, reject);
        });
    }

Next Steps here:

Write an issue on the repository.

Fix the implementation to use pylintArgs over the default.


问:
Empty string variable matching to LIKE conditions in SQL
I have a SQL Server table containing a nvarchar(max) column. I ran a query to select every row where this column contains the string 'remove'. Amongst the results, I have several rows where this column is populated with an empty string and I don't understand why these values have been returned.

I tried to investigate further, on one of the empty string values returned. I found that the empty string value would match to certain LIKE conditions, but not others. For instance, it will match to %remove% and %x%, but it won't match to %q%.

Within the results grid on SQL Server Management Studio, the nvarchar field is displayed as an empty field (it is not null). However, if I apply the len() function to this field, it returns the value of 649. When I export the results table from SQL Server Management Studio into Excel, the nvarchar(max) field is empty.

Assuming that there must be a bunch of whitespace characters populating the field, I tried to select the field after concatenating 'x' to either end of the value returned. In the results, the leading 'x' appears at the beginning of the string, but the 'x' concatenated onto the end is not displayed.

I'm totally confused as to what is going on. I can provide more information upon request.

```<code>select itemid, content
from objects
where itemid = 100 and content like '%remove%'

----------------

itemid  |  content
100     |
</code>```

```<code>select itemid, 'x' + content + 'x' as 'content'
from objects
where itemid = 100 and content like '%remove%'

----------------

itemid  |  content
100     |  x
</code>```

EDIT:

Trimming the field doesn't change the character count. However, when I do use substring to select the last character in the concatenated output, the character returned is 'x', which suggests that it just isn't visible in the GUI output due to the length of the string. I still can't see this trailing 'x' character when exporting the content into Excel though. I think that there are maybe unsupported characters present within the nvarchar variable.

```<code>select itemid, 'x' + ltrim(rtrim(content)) + 'x' as 'content'
from objects
where itemid = 100 and content like '%remove%'

----------------

itemid  |  content
100     |  x
</code>```

答:
I think, you should trim the column;</p>

```<code>select itemid, LTRIM(RTRIM(content))
from objects
where itemid = 100 and content like '%remove%'
</code>```

Body:
I have a SQL Server table containing a nvarchar(max) column. I ran a query to select every row where this column contains the string 'remove'. Amongst the results, I have several rows where this column is populated with an empty string and I don't understand why these values have been returned.

I tried to investigate further, on one of the empty string values returned. I found that the empty string value would match to certain LIKE conditions, but not others. For instance, it will match to %remove% and %x%, but it won't match to %q%.

Within the results grid on SQL Server Management Studio, the nvarchar field is displayed as an empty field (it is not null). However, if I apply the len() function to this field, it returns the value of 649. When I export the results table from SQL Server Management Studio into Excel, the nvarchar(max) field is empty.

Assuming that there must be a bunch of whitespace characters populating the field, I tried to select the field after concatenating 'x' to either end of the value returned. In the results, the leading 'x' appears at the beginning of the string, but the 'x' concatenated onto the end is not displayed.

I'm totally confused as to what is going on. I can provide more information upon request.

select itemid, content
from objects
where itemid = 100 and content like '%remove%'

----------------

itemid  |  content
100     |

select itemid, 'x' + content + 'x' as 'content'
from objects
where itemid = 100 and content like '%remove%'

----------------

itemid  |  content
100     |  x

EDIT:

Trimming the field doesn't change the character count. However, when I do use substring to select the last character in the concatenated output, the character returned is 'x', which suggests that it just isn't visible in the GUI output due to the length of the string. I still can't see this trailing 'x' character when exporting the content into Excel though. I think that there are maybe unsupported characters present within the nvarchar variable.

select itemid, 'x' + ltrim(rtrim(content)) + 'x' as 'content'
from objects
where itemid = 100 and content like '%remove%'

----------------

itemid  |  content
100     |  x

Body:
I think, you should trim the column;

select itemid, LTRIM(RTRIM(content))
from objects
where itemid = 100 and content like '%remove%'


问:
Plugins for Eclipse/PyDev
I started learning python recently, it seems fun and interesting. After comparing some IDEs, i concluded with Eclipse+PyDev, because i am already familiar with it from Java.

1) Can i use my favorite plugins(FindBugs, Log4E, Metrics) within the PyDev Perspective?

2) Which plugins do you use for python development in this environment?

Thanks in advance.

答:
No, none of those plugins will work for Python; they're all designed exclusively for Java.

To answer your second question, when I was using PyDev the only plugins that I used for Python were version control -- Subclipse, EGit, MercurialEclipse, that kind of stuff. Most all of the plugins won't do anything for PyDev because they're designed around Java.

You'll find quickly that in Eclipse, Python is definitely not a first class citizen.

Title: Plugins for Eclipse/PyDev


问:
Change datatype from string to integer in MongoDB PHP
I have a set of documents where some of product_id are stored in string

```<code>[
  {
    "_id": ObjectId("foobar1"),
    "product_id": "1"
  },
  {
    "_id": ObjectId("foobar2"),
    "product_id": 2
  }
]
</code>```

Is there any way to convert product_id to integer for all the documents using MongoDB PHP ?

答:
You can also search for the specific type. Check out the documentation of $type. Strings are $type: 2

```<code>db.collection.find({
    product_id: {
        $type: 2
    }
}).forEach(function(doc) {
    doc.product_id = new NumberInt(doc.product_id);
    db.product.save(doc);
});
</code>```

Body:
I have a set of documents where some of product_id are stored in string

[
  {
    "_id": ObjectId("foobar1"),
    "product_id": "1"
  },
  {
    "_id": ObjectId("foobar2"),
    "product_id": 2
  }
]

Is there any way to convert product_id to integer for all the documents using MongoDB PHP ?

Body:
You can also search for the specific type. Check out the documentation of $type. Strings are $type: 2

db.collection.find({
    product_id: {
        $type: 2
    }
}).forEach(function(doc) {
    doc.product_id = new NumberInt(doc.product_id);
    db.product.save(doc);
});