问:
Android M Webview (with multiwindow support enabled) not opening anchor tag when link type is "noreferrer"
I have a webview which loads a website which contains some anchor tag. This anchor tag has the type of "noreferrer" and opens a page in new tab (using target = "_blank"). Now the issue is when I don't enable multi-window support in webview, it works fine on all devices.

But when I enable multi-window support it doesn't work in Marshmallow device but It works fine in all other devices. I have created a demo project to reproduce it. It works fine in all cases when I remove rel="noreferrer" from anchor tag.

My Activity code is here

```<code>public class MainActivity extends AppCompatActivity {

    private RelativeLayout mContainer;
    private WebView mWebView;
    private WebView mNewWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContainer = (RelativeLayout) findViewById(R.id.container);
        mWebView = (WebView) findViewById(R.id.webview);

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setSupportMultipleWindows(true);

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                mNewWebView = new WebView(MainActivity.this);
                mNewWebView.setLayoutParams(new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,
                    RelativeLayout.LayoutParams.MATCH_PARENT
                ));

                WebSettings webSettings = mNewWebView.getSettings();
                webSettings.setJavaScriptEnabled(true);
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

                mNewWebView.setWebViewClient(new WebViewClient() {
                    @Override
                    public void onPageFinished(WebView view, String url) {
                        super.onPageFinished(view, url);
                        view.clearHistory();
                    }
                });
                mContainer.addView(mNewWebView);

                ((WebView.WebViewTransport) resultMsg.obj).setWebView(mNewWebView);
                resultMsg.sendToTarget();

                return true;
            }
        });
        mWebView.setWebViewClient(new WebViewClient());

        mWebView.loadData("<a href=\"https://example.com\" target=\"_blank\" rel=\"noreferrer\">open new window</a>",
            "text/html", "utf-8");
    }

    @Override
    public void onBackPressed() {
        if (mNewWebView != null) {
            if (mNewWebView.canGoBack()) {
                mNewWebView.goBack();
            } else {
                mNewWebView.destroy();
                mContainer.removeViewAt(1);
                mNewWebView = null;
            }
        } else if (mWebView != null && mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}
</code>```

My Layout file

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.treebo.test.MainActivity">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
</code>```

Few pointers:

Multi-window support is enabled using webview.getSettings().setSupportMultipleWindows(true). I am doing this one the webview defined a the layout file.

When I click the anchor, it opens a new page and onCreateWindow() is called where I create a new webview and add it in view hierarchy.

Edit 1

Observed the same issue on android 5.0.2

Edit 2

Some clarification on this: I have some use case which opens a web page in a separate tab in the browser (basically payment related page). When I run the same website in the web view, it opens the new tab in same web view (which I don't want. I want to open it in the new web view). That is why I am using multiwindow support. Hope it clears why I am using multiwindow support.

答:
You say

This anchor tag has the type of "noreferrer" and opens a page in new tab (using target = "_blank").

Is that a HTML tag? Are you trying to open a new HTML page or a new fragement in android? Because I don't understand what you mean with it?

You can find more info about Multi-Window Support for api level 23 or lower here: https://developer.android.com/guide/topics/ui/multi-window.html#testing

If your app targets API level 23 or lower
  If your app targets API level 23 or lower and the user attempts to use the app in multi-window mode, the system forcibly resizes the app unless the app declares a fixed orientation.

If your app does not declare a fixed orientation, you should launch
  your app on a device running Android 7.0 or higher and attempt to put
  the app in split-screen mode. Verify that the user experience is
  acceptable when the app is forcibly resized.

If the app declares a fixed orientation, you should attempt to put the
  app in multi-window mode. Verify that when you do so, the app remains
  in full-screen mode

Body:
I have a webview which loads a website which contains some anchor tag. This anchor tag has the type of "noreferrer" and opens a page in new tab (using target = "_blank"). Now the issue is when I don't enable multi-window support in webview, it works fine on all devices.

But when I enable multi-window support it doesn't work in Marshmallow device but It works fine in all other devices. I have created a demo project to reproduce it. It works fine in all cases when I remove rel="noreferrer" from anchor tag.

My Activity code is here

public class MainActivity extends AppCompatActivity {

    private RelativeLayout mContainer;
    private WebView mWebView;
    private WebView mNewWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContainer = (RelativeLayout) findViewById(R.id.container);
        mWebView = (WebView) findViewById(R.id.webview);

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setSupportMultipleWindows(true);

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                mNewWebView = new WebView(MainActivity.this);
                mNewWebView.setLayoutParams(new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,
                    RelativeLayout.LayoutParams.MATCH_PARENT
                ));

                WebSettings webSettings = mNewWebView.getSettings();
                webSettings.setJavaScriptEnabled(true);
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

                mNewWebView.setWebViewClient(new WebViewClient() {
                    @Override
                    public void onPageFinished(WebView view, String url) {
                        super.onPageFinished(view, url);
                        view.clearHistory();
                    }
                });
                mContainer.addView(mNewWebView);

                ((WebView.WebViewTransport) resultMsg.obj).setWebView(mNewWebView);
                resultMsg.sendToTarget();

                return true;
            }
        });
        mWebView.setWebViewClient(new WebViewClient());

        mWebView.loadData("open new window",
            "text/html", "utf-8");
    }

    @Override
    public void onBackPressed() {
        if (mNewWebView != null) {
            if (mNewWebView.canGoBack()) {
                mNewWebView.goBack();
            } else {
                mNewWebView.destroy();
                mContainer.removeViewAt(1);
                mNewWebView = null;
            }
        } else if (mWebView != null && mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

My Layout file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.treebo.test.MainActivity">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Few pointers:

Multi-window support is enabled using webview.getSettings().setSupportMultipleWindows(true). I am doing this one the webview defined a the layout file.

When I click the anchor, it opens a new page and onCreateWindow() is called where I create a new webview and add it in view hierarchy.

Edit 1

Observed the same issue on android 5.0.2

Edit 2

Some clarification on this: I have some use case which opens a web page in a separate tab in the browser (basically payment related page). When I run the same website in the web view, it opens the new tab in same web view (which I don't want. I want to open it in the new web view). That is why I am using multiwindow support. Hope it clears why I am using multiwindow support.


来源: stackexchange

问:
Double free or corruption (!prev) error when working with threads and mutex
I've got simple c++ code that firstly creates 4 threads and then sends 1000 times number 1 to the c++ queue followed by four 0. Each of these threads tries to read from that queue and when any thread reads 0, it terminates and prints its local sum. If it reads 1 then it simply adds 1 to the sum. The reading is protected with mutex. Code works as intended in 4 out of 5 times, but sometimes I get double free or corruption (!prev) error... ...Abort core dumped. I've also debugged the code with gdb but only got received signal SIGABRT, Aborted ... ...at raise.c: No such file or directory". I'm not explicitly allocating or deallocating any memory. What could be causing the problem?

```<code>#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <queue>

std::queue<int> my_queue;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *process(void *arg){
    int sum = 0;
    while(1){
        if(!my_queue.empty()){
            pthread_mutex_lock(&mutex);
            if (my_queue.front() == 1){
                sum += 1;
                my_queue.pop();
                pthread_mutex_unlock(&mutex);
            }
            else{
                my_queue.pop();
                printf("Sum: %d\n", sum);
                pthread_mutex_unlock(&mutex);
                break;
            }
        }
    }
    return arg;
}

int main(void){
    pthread_t id[4];
    for(int i = 0; i < 4; i++){
        if (pthread_create(&id[i], NULL, process, NULL) != 0){
            fprintf(stderr, "%s\n", "Error creating thread!");
            exit(EXIT_FAILURE);
        }
    }
    for (int i = 0; i < 1000; i++){
        my_queue.push(1);
    }
    for (int i = 0; i < 4; i++){
        my_queue.push(0);
    }
    for (int i = 0; i < 4; i++){
        pthread_join(id[i], NULL);
    }
    return EXIT_SUCCESS;
}
</code>```

答:
You have two problems:

Firstly you are pushing onto the queue without holding the lock, secondly you are testing if the queue is empty without holding the lock.

```<code>#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <queue>

std::queue<int> my_queue;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *process(void *arg){
    int sum = 0;
    bool keep_going = true;
    while(keep_going){
        pthread_mutex_lock(&mutex);
        if(!my_queue.empty()){
            if (my_queue.front() == 1){
                sum += 1;
            }
            else{
                keep_going=false;
            }
        }
        my_queue.pop();
        pthread_mutex_unlock(&mutex);
    }
    printf("Sum: %d\n", sum); // Don't do IO while holding a lock!
    return arg;
}

int main(void){
    pthread_t id[4];
    // Initialize queue *before* creating threads.
    for (int i = 0; i < 1000; i++){
        my_queue.push(1);
    }
    for (int i = 0; i < 4; i++){
        my_queue.push(0);
    }
    // Create threads
    for(int i = 0; i < 4; i++){
        if (pthread_create(&id[i], NULL, process, NULL) != 0){
            fprintf(stderr, "%s\n", "Error creating thread!");
            exit(EXIT_FAILURE);
        }
    }
    // Join them.
    for (int i = 0; i < 4; i++){
        pthread_join(id[i], NULL);
    }
    return EXIT_SUCCESS;
}
</code>```

If you want to add to the queue after creating the threads, you need something like:

```<code>    pthread_mutex_lock(&mutex);
    my_queue.push(value);
    pthread_mutex_unlock(&mutex);
</code>```

Inside the for-loops.  Also, there is then a real chance of the queue emptying before you get to the zeros.  Either do it properly by waiting on semaphores, or the queue loop needs to becomes something like:

```<code>        pthread_mutex_lock(&mutex);
        if(my_queue.empty()){
            pthread_mutex_unlock(&mutex);
            usleep(1);
            pthread_mutex_lock(&mutex);
        } else {
</code>```

Where the thread will briefly sleep to let the queue fill up.

Also, you are writing in C++.  Learn to write a RAII class to call pthread_mutex_lock and unlock.

ContentLicense: CC BY-SA 3.0

Body:
I've got simple c++ code that firstly creates 4 threads and then sends 1000 times number 1 to the c++ queue followed by four 0. Each of these threads tries to read from that queue and when any thread reads 0, it terminates and prints its local sum. If it reads 1 then it simply adds 1 to the sum. The reading is protected with mutex. Code works as intended in 4 out of 5 times, but sometimes I get double free or corruption (!prev) error... ...Abort core dumped. I've also debugged the code with gdb but only got received signal SIGABRT, Aborted ... ...at raise.c: No such file or directory". I'm not explicitly allocating or deallocating any memory. What could be causing the problem?

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <queue>

std::queue<int> my_queue;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *process(void *arg){
    int sum = 0;
    while(1){
        if(!my_queue.empty()){
            pthread_mutex_lock(&mutex);
            if (my_queue.front() == 1){
                sum += 1;
                my_queue.pop();
                pthread_mutex_unlock(&mutex);
            }
            else{
                my_queue.pop();
                printf("Sum: %d\n", sum);
                pthread_mutex_unlock(&mutex);
                break;
            }
        }
    }
    return arg;
}

int main(void){
    pthread_t id[4];
    for(int i = 0; i < 4; i++){
        if (pthread_create(&id[i], NULL, process, NULL) != 0){
            fprintf(stderr, "%s\n", "Error creating thread!");
            exit(EXIT_FAILURE);
        }
    }
    for (int i = 0; i < 1000; i++){
        my_queue.push(1);
    }
    for (int i = 0; i < 4; i++){
        my_queue.push(0);
    }
    for (int i = 0; i < 4; i++){
        pthread_join(id[i], NULL);
    }
    return EXIT_SUCCESS;
}

Body:
You have two problems:

Firstly you are pushing onto the queue without holding the lock, secondly you are testing if the queue is empty without holding the lock.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <queue>

std::queue<int> my_queue;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *process(void *arg){
    int sum = 0;
    bool keep_going = true;
    while(keep_going){
        pthread_mutex_lock(&mutex);
        if(!my_queue.empty()){
            if (my_queue.front() == 1){
                sum += 1;
            }
            else{
                keep_going=false;
            }
        }
        my_queue.pop();
        pthread_mutex_unlock(&mutex);
    }
    printf("Sum: %d\n", sum); // Don't do IO while holding a lock!
    return arg;
}

int main(void){
    pthread_t id[4];
    // Initialize queue *before* creating threads.
    for (int i = 0; i < 1000; i++){
        my_queue.push(1);
    }
    for (int i = 0; i < 4; i++){
        my_queue.push(0);
    }
    // Create threads
    for(int i = 0; i < 4; i++){
        if (pthread_create(&id[i], NULL, process, NULL) != 0){
            fprintf(stderr, "%s\n", "Error creating thread!");
            exit(EXIT_FAILURE);
        }
    }
    // Join them.
    for (int i = 0; i < 4; i++){
        pthread_join(id[i], NULL);
    }
    return EXIT_SUCCESS;
}

If you want to add to the queue after creating the threads, you need something like:

    pthread_mutex_lock(&mutex);
    my_queue.push(value);
    pthread_mutex_unlock(&mutex);

Inside the for-loops.  Also, there is then a real chance of the queue emptying before you get to the zeros.  Either do it properly by waiting on semaphores, or the queue loop needs to becomes something like:

        pthread_mutex_lock(&mutex);
        if(my_queue.empty()){
            pthread_mutex_unlock(&mutex);
            usleep(1);
            pthread_mutex_lock(&mutex);
        } else {

Where the thread will briefly sleep to let the queue fill up.

Also, you are writing in C++.  Learn to write a RAII class to call pthread_mutex_lock and unlock.


问:
How to delete a Task (Row) with Interop.MSProject
I'm trying to use Interop.MSProject with C# to do something that conceptually, should be the simiplest thing in the world to do.  However, I am having some trouble with it's cryptic api which has minimal documentation.  All I wish to do is to find a row that contains a specific string in one of it's columns (cell) and remove that row.  After I've done that, I just want to display the modified project file so that the user has the option to save it.  Here is what I've tried:

```<code>MSProject.Application app = new MSProject.Application();
app.FileOpenEx(
    filePath,
    false,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    MSProject.PjPoolOpen.pjPoolReadWrite,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing);

foreach(MSProject.Task task in proj.Tasks)
{
    if (task == null) continue;
    string cellValue = task.OutlineCode3;
    if (cellValue == searchString)
       task.Delete();
}

app.Visible = true;
</code>```

It seems as though task.Delete is not working.  I've even tried to generalize this code to the following:

```<code>foreach (MSProject.Task task in proj.Tasks)
   task.Delete()
</code>```

and this did not work either.  Does anyone know a way that I can remove a task or a row base on a value in one of the rows cells?

答:
I faced the same conundrum yesterday.

Your approach is correct but it doesn't work because the tasks are Index-based. This is more obvious in a straight for loop.

If you have 10 tasks and delete one, let's say number 5, now the next task (6) is now 5 but your loop will try to delete 6 which is now 7. This will mess everything up.

If you want to delete all tasks you should do something like:

```<code>// Task Indexes are 1-based not 0-based
for(int i = 1; i <= proj.Tasks.Count; i++) {
    proj.Tasks[i].Delete();
    i--;
}
</code>```

Following this train of thought let's apply this to a foreach loop

```<code>foreach(Task t in tasksToDelete) {
    proj.Tasks[proj.GetTaskIndexByGuid(t.Guid)].Delete();
}
</code>```

Why am I using GetTaskIndexByGuid? It seems that the Index property of each task if not properly (or immeadiately) updated when you delete a task but I found that using GetTaskIndexByGuid always returns the correct index.

Hope it helps

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to use Interop.MSProject with C# to do something that conceptually, should be the simiplest thing in the world to do.  However, I am having some trouble with it's cryptic api which has minimal documentation.  All I wish to do is to find a row that contains a specific string in one of it's columns (cell) and remove that row.  After I've done that, I just want to display the modified project file so that the user has the option to save it.  Here is what I've tried:

MSProject.Application app = new MSProject.Application();
app.FileOpenEx(
    filePath,
    false,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    MSProject.PjPoolOpen.pjPoolReadWrite,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing,
    Type.Missing);

foreach(MSProject.Task task in proj.Tasks)
{
    if (task == null) continue;
    string cellValue = task.OutlineCode3;
    if (cellValue == searchString)
       task.Delete();
}

app.Visible = true;

It seems as though task.Delete is not working.  I've even tried to generalize this code to the following:

foreach (MSProject.Task task in proj.Tasks)
   task.Delete()

and this did not work either.  Does anyone know a way that I can remove a task or a row base on a value in one of the rows cells?

Body:
I faced the same conundrum yesterday.

Your approach is correct but it doesn't work because the tasks are Index-based. This is more obvious in a straight for loop.

If you have 10 tasks and delete one, let's say number 5, now the next task (6) is now 5 but your loop will try to delete 6 which is now 7. This will mess everything up.

If you want to delete all tasks you should do something like:

// Task Indexes are 1-based not 0-based
for(int i = 1; i <= proj.Tasks.Count; i++) {
    proj.Tasks[i].Delete();
    i--;
}

Following this train of thought let's apply this to a foreach loop

foreach(Task t in tasksToDelete) {
    proj.Tasks[proj.GetTaskIndexByGuid(t.Guid)].Delete();
}

Why am I using GetTaskIndexByGuid? It seems that the Index property of each task if not properly (or immeadiately) updated when you delete a task but I found that using GetTaskIndexByGuid always returns the correct index.

Hope it helps


问:
Group and count values in an array
I have an array with objects, like the following.

```<code>b = {
  "issues": [{
    "fields": {
      "status": {
        "id": "200",
        "name": "Backlog"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "202",
        "name": "close"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "201",
        "name": "close"
      }
    }
  }]
};
</code>```

I want to count how many issues have status close, and how many have backlog. I'd like to save the count in a new array as follows.

```<code>a = [
  {Name: 'Backlog', count: 1},
  {Name: 'close', count: 2}
];
</code>```

I have tried the following.

```<code>b.issues.forEach(function(i) {
  var statusName = i.fields.status.name;

  if (statusName in a.Name) {
    a.count = +1;
  } else {
    a.push({
      Name: statusName,
      count: 1
    });
  }
});
</code>```

That however doesn't seem to be working. How should I implement this?

答:
Something like this should do the trick. Simply iterate over your data, keep 2 counters with the number of each type of issue, and create the data format you want in the end. Try it live on jsfiddle.</p>

```<code>var b = {
    "issues": [{
        "fields": {
            "status": {
                "id": "200",
                "name": "Backlog"
            }
        }
    }, {
        "fields": {
            "status": {
                "id": "202",
                "name": "close"
            }
        }
    }, {
        "fields": {
            "status": {
                "id": "201",
                "name": "close"
            }
        }
    }]
};

var data = [];
for(var issue of b.issues){
    var entryFound = false;
    var tempObj = {
        name: issue.fields.status.name,
        count: 1
    };

    for(var item of data){
        if(item.name === tempObj.name){
        item.count++;
        entryFound = true;
        break;
      }
    }

    if(!entryFound){
        data.push(tempObj);
    }
}
console.log(data);
</code>```

Title: Group and count values in an array

Body:
I have an array with objects, like the following.

b = {
  "issues": [{
    "fields": {
      "status": {
        "id": "200",
        "name": "Backlog"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "202",
        "name": "close"
      }
    }
  }, {
    "fields": {
      "status": {
        "id": "201",
        "name": "close"
      }
    }
  }]
};

I want to count how many issues have status close, and how many have backlog. I'd like to save the count in a new array as follows.

a = [
  {Name: 'Backlog', count: 1},
  {Name: 'close', count: 2}
];

I have tried the following.

b.issues.forEach(function(i) {
  var statusName = i.fields.status.name;

  if (statusName in a.Name) {
    a.count = +1;
  } else {
    a.push({
      Name: statusName,
      count: 1
    });
  }
});

That however doesn't seem to be working. How should I implement this?

Body:
Something like this should do the trick. Simply iterate over your data, keep 2 counters with the number of each type of issue, and create the data format you want in the end. Try it live on jsfiddle.

var b = {
    "issues": [{
        "fields": {
            "status": {
                "id": "200",
                "name": "Backlog"
            }
        }
    }, {
        "fields": {
            "status": {
                "id": "202",
                "name": "close"
            }
        }
    }, {
        "fields": {
            "status": {
                "id": "201",
                "name": "close"
            }
        }
    }]
};

var data = [];
for(var issue of b.issues){
    var entryFound = false;
    var tempObj = {
        name: issue.fields.status.name,
        count: 1
    };

    for(var item of data){
        if(item.name === tempObj.name){
        item.count++;
        entryFound = true;
        break;
      }
    }

    if(!entryFound){
        data.push(tempObj);
    }
}
console.log(data);


问:
Extract text between brackets using google spreadsheets
I want to extract the text between brackets in a cell (X3), but the usual excel formulas give a parse error in google spreadsheets.

For example:

```<code>=MID(X3,FIND("[",X3)+1,FIND("]",X3)-FIND("[",X3)-1)
</code>```

How to fix this parse error?

Thanks in advance.

答:
You have regular brackets so use:

```<code>=REGEXEXTRACT(X3,"\((.*)\)")
</code>```

Or change your formula to

```<code>=MID(X3,FIND("(",X3)+1,FIND(")",X3)-FIND("(",X3)-1)
</code>```

If you have both () and [] in your data you can use:

```<code>=REGEXEXTRACT(X3,"[\[\(](.*)[\)\]]")
</code>```

Body:
I want to extract the text between brackets in a cell (X3), but the usual excel formulas give a parse error in google spreadsheets.

For example:

=MID(X3,FIND("[",X3)+1,FIND("]",X3)-FIND("[",X3)-1)

How to fix this parse error?

Thanks in advance.

Body:
You have regular brackets so use:

=REGEXEXTRACT(X3,"\((.*)\)")

Or change your formula to

=MID(X3,FIND("(",X3)+1,FIND(")",X3)-FIND("(",X3)-1)

If you have both () and [] in your data you can use:

=REGEXEXTRACT(X3,"[\[\(](.*)[\)\]]")


问:
TestNG + Selenium + Maven + Jenkins ! Not generating testNG reports for current build

I have created Maven project in eclipse with Selenium & TestNG to create automation test scripts which I want to execute from Jenkins.

I have added testNG dependency and all other required dependencies in pom.xml to create the TestNG report.

In Jenkins I have added the TestNG plugin to publish the TestNG report and set the pattern as mention below. But testNG report is not getting generated in jenkins.

Even TestNG report is being generated while running script from eclipse but not for the current build or for recently executed test. It shows the different reports than current test execution(I guess it shows reports of previous build)

I'm getting the two below mentioned issues.

1.
TestNG Reports Processing: START
Looking for TestNG results report in workspace using pattern:
D:/Repository/cellma_robust-automation/CellmaAutomationFramework/target/surefire-reports/testng-results.xml
Did not find any matching files.
Finished: SUCCESS

2.
TestNG Reports Processing: START
Looking for TestNG results report in workspace using pattern: ** /testng-results.xml
testng-results.xml was last modified before this build started. Ignoring it.
Saving reports...
Found matching files but did not find any TestNG results.
Finished: SUCCESS

Actual path of the TestNG report file: D:\Repository\cellma_robust-automation\CellmaAutomationFramework\target\surefire-reports\testng-results.xml

I have tried the following options but didn't work out for me.

Tried giving the full path of the TestNG report. Forward ans backward slash in the pattern.

I have tried different other options by changing the TestNG result file path but this is also not working.

Please share some inputs on how to resolve this issue.

"testng-results.xml" file is available in workspace. But it's failed to display the report.

Note: I am using Jenkins 2.46.2 in Windows 10.

I have attached screenshot of Jenkins Console Output.
ConsoleOutput_Jenkins

Please do the helpful. Let me know whats going wrong with this configuration or m i missing some desired configuration.

答:
go to the job and click on workspace

Navigate to the generated testng xml file.

copy the path and put that in job config. use *.xml or other wild card pattern.

make sure you are running mvn clean test which will delete the old reports.


问:
Counting unique characters in a String given by the user
I have to write a program that counts the uniques characters in a String given by the user. For example "abc" returns 3 and "aabbccd" returns 4. I am not allow to use  advanced Java classes like Map, Set, etc. I can only use arrays, Strings, for loops, while loops, if statements. I am trying to use a nested loop but am getting confused about how to write the algorithm for the second for loop.</p>

```<code>public static int countUniqueCharacters(String input){

String orgInput = input.toLowerCase();
        int count = 0;
        int stringLength = input.length();
        for( int i = 0; i<stringLength; i++){
            for(int j = 2; j > j-i-1; j--){
                char temp = orgInput.charAt(i);
                if (temp == orgInput.charAt(j)){
                    count++;
</code>```

答:
You can use HashSet collections for counting the unique elements in a string. It allow only unique element.

Code Snippet

```<code>public static int uniqueCount(String str)
{
   HashSet<Character> al = new HashSet<Character>();
   char[] arr= str.toCharArray();
   for (int i=0; i<arr.length; i++)
   {
      al.add(arr[i]);
   }
   return al.size() ;
}
</code>```

Refer this link to get full code: ideone

Body:
I have to write a program that counts the uniques characters in a String given by the user. For example "abc" returns 3 and "aabbccd" returns 4. I am not allow to use  advanced Java classes like Map, Set, etc. I can only use arrays, Strings, for loops, while loops, if statements. I am trying to use a nested loop but am getting confused about how to write the algorithm for the second for loop.

public static int countUniqueCharacters(String input){

String orgInput = input.toLowerCase();
        int count = 0;
        int stringLength = input.length();
        for( int i = 0; i<stringLength; i++){
            for(int j = 2; j > j-i-1; j--){
                char temp = orgInput.charAt(i);
                if (temp == orgInput.charAt(j)){
                    count++;

Body:
You can use HashSet collections for counting the unique elements in a string. It allow only unique element.

Code Snippet

public static int uniqueCount(String str)
{
   HashSet<Character> al = new HashSet<Character>();
   char[] arr= str.toCharArray();
   for (int i=0; i<arr.length; i++)
   {
      al.add(arr[i]);
   }
   return al.size() ;
}

Refer this link to get full code: ideone


问:
Reading data from columns in Excel
I am working on a python script to read data from columns in an Excel file and using that data to execute commands on a Cisco switch.

For example, I have below 2 columns

```<code>Switch        MAC
aaa.com      mac.aaa.000
bbb.com      mac.bbb.000
ccc.com      mac.ccc.000
.....        .....
</code>```

The python will now go to switch aaa and will set port security with mac mac.aaa.000 as sticky.

This is the command:

```<code>switchport port-security **<mac-address>** sticky
</code>```

Now I have login part done and I can execute commands. I need help with the part which reads 2 columns from file and know to login to switch a and sticky macaaa on corresponding column.

Here is how I am logging in and executing commands on switch:

```<code>term_len = "term len 0"
# Need a loop here that gets switchname from coulmn A and assign it to variable host and also corresponding MAC address and assigns it to variable MAC
host = ""
MAC = ""
session = telnetlib.Telnet(host)
session.write(cred.username + '\n')
session.read_until('Password: ')
session.write(cred.password + '\n')
session.read_until('>')
session.write(cred.en + '\n')
session.read_until('Password: ')
session.write(cred.en_pass + '\n')
session.read_until('#')
session.write(term_len + '\n')
session.write(switchport port-security **MAC** sticky + '\n')
</code>```

Please help. The loop will read all switches and MAC from files and executes the sticky command.

答:
You can use xlrd, This script allows you to transform an excel data table to a list of dictionaries:

```<code>import xlrd

workbook = xlrd.open_workbook('foo.xls')
workbook = xlrd.open_workbook('foo.xls', on_demand = True)
worksheet = workbook.sheet_by_index(0)
first_row = [] # The row where we stock the name of the column
for col in range(worksheet.ncols):
    first_row.append( worksheet.cell_value(0,col) )
# transform the workbook to a list of dictionaries
data =[]
for row in range(1, worksheet.nrows):
    elm = {}
    for col in range(worksheet.ncols):
        elm[first_row[col]]=worksheet.cell_value(row,col)
    data.append(elm)
print data
</code>```

You can also use Pandas

```<code>from pandas import *
xls = ExcelFile('foo.xls')
df = xls.parse(xls.sheet_names[0])
print df.to_dict()
</code>```

Title: Reading data from columns in Excel

Body:
I am working on a python script to read data from columns in an Excel file and using that data to execute commands on a Cisco switch.

For example, I have below 2 columns

Switch        MAC
aaa.com      mac.aaa.000
bbb.com      mac.bbb.000
ccc.com      mac.ccc.000
.....        .....

The python will now go to switch aaa and will set port security with mac mac.aaa.000 as sticky.

This is the command:

switchport port-security **<mac-address>** sticky

Now I have login part done and I can execute commands. I need help with the part which reads 2 columns from file and know to login to switch a and sticky macaaa on corresponding column.

Here is how I am logging in and executing commands on switch:

term_len = "term len 0"
# Need a loop here that gets switchname from coulmn A and assign it to variable host and also corresponding MAC address and assigns it to variable MAC
host = ""
MAC = ""
session = telnetlib.Telnet(host)
session.write(cred.username + '\n')
session.read_until('Password: ')
session.write(cred.password + '\n')
session.read_until('>')
session.write(cred.en + '\n')
session.read_until('Password: ')
session.write(cred.en_pass + '\n')
session.read_until('#')
session.write(term_len + '\n')
session.write(switchport port-security **MAC** sticky + '\n')

Please help. The loop will read all switches and MAC from files and executes the sticky command.

Body:
You can use xlrd, This script allows you to transform an excel data table to a list of dictionaries:

import xlrd

workbook = xlrd.open_workbook('foo.xls')
workbook = xlrd.open_workbook('foo.xls', on_demand = True)
worksheet = workbook.sheet_by_index(0)
first_row = [] # The row where we stock the name of the column
for col in range(worksheet.ncols):
    first_row.append( worksheet.cell_value(0,col) )
# transform the workbook to a list of dictionaries
data =[]
for row in range(1, worksheet.nrows):
    elm = {}
    for col in range(worksheet.ncols):
        elm[first_row[col]]=worksheet.cell_value(row,col)
    data.append(elm)
print data

You can also use Pandas

from pandas import *
xls = ExcelFile('foo.xls')
df = xls.parse(xls.sheet_names[0])
print df.to_dict()


问:
space auto add in input php
I have made a form to modify the data with the framework laravel 5.1, everything is ok, but when I submit the form, there are two input are added a space automatically

like this screenshot

there is my form

```<code><form method="post">
 <input type="hidden" name="_token" value="{{csrf_token()}}">
<input type="hidden" name="id_article" value="{!!$opusdef->id_article !!}">
<div class="td w10">
<input type="text" name="code_article" value="{!!$opusdef->code_article  !!}"  required/></div>
<div class="td w5">
<input type="text" name="num_activité" value="{!!$opusdef->num_activité !!}" required/>  </div>
<div class="td w15">
<input type="text" name="libellé_activité" value="{!! $opusdef->libellé_activité !!}" required/> </div>
<div class="td w5">
<input type="text" name="domaine" value=" {{$opusdef->domaine}}" required/></div>
<div class="td w10">
<input type="text" name="s_domaine" value=" {!!$opusdef->s_domaine!!}" required/></div>
</code>```

my controller

```<code> protected function  postAllOpusDef(Request $request){
   $data=$request->except('_token');

    $opusDefs=OpusDefs::where('id_article',$data['id_article']);
    if($opusDefs->update($data)){
        return redirect()->back()->with('status','donnée modifiée');
    };
}
</code>```

答:
You have a space in your value attribute.

Change:

```<code><input type="text" name="domaine" value=" {{$opusdef->domaine}}" required/></div>
<div class="td w10">
<input type="text" name="s_domaine" value=" {!!$opusdef->s_domaine!!}" required/></div>
</code>```

To

```<code><input type="text" name="domaine" value="{{$opusdef->domaine}}" required/></div>
<div class="td w10">
<input type="text" name="s_domaine" value="{!!$opusdef->s_domaine!!}" required/></div>
</code>```

Besides that, the user might still post a space? So you probably want to sanitize the user input prior to storing your data in the database.

Optionally you can create a middleware to transform the post data, much like how Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull works.

Title: space auto add in input php

Body:
I have made a form to modify the data with the framework laravel 5.1, everything is ok, but when I submit the form, there are two input are added a space automatically

like this screenshot

there is my form

<form method="post">
 <input type="hidden" name="_token" value="{{csrf_token()}}">
<input type="hidden" name="id_article" value="{!!$opusdef->id_article !!}">

<input type="text" name="code_article" value="{!!$opusdef->code_article  !!}"  required/>

<input type="text" name="num_activité" value="{!!$opusdef->num_activité !!}" required/>

<input type="text" name="libellé_activité" value="{!! $opusdef->libellé_activité !!}" required/>

<input type="text" name="domaine" value=" {{$opusdef->domaine}}" required/>

<input type="text" name="s_domaine" value=" {!!$opusdef->s_domaine!!}" required/>

my controller

 protected function  postAllOpusDef(Request $request){
   $data=$request->except('_token');

    $opusDefs=OpusDefs::where('id_article',$data['id_article']);
    if($opusDefs->update($data)){
        return redirect()->back()->with('status','donnée modifiée');
    };
}

Body:
You have a space in your value attribute.

Change:

<input type="text" name="domaine" value=" {{$opusdef->domaine}}" required/></div>
<div class="td w10">
<input type="text" name="s_domaine" value=" {!!$opusdef->s_domaine!!}" required/></div>

To

<input type="text" name="domaine" value="{{$opusdef->domaine}}" required/></div>
<div class="td w10">
<input type="text" name="s_domaine" value="{!!$opusdef->s_domaine!!}" required/></div>

Besides that, the user might still post a space? So you probably want to sanitize the user input prior to storing your data in the database.

Optionally you can create a middleware to transform the post data, much like how Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull works.


问:
CORDOVA: Missing 'name' key attribute
I'm trying to create a simple Cordova plugin but when I try to BUILD it I get this error:

Missing 'name' key attribute on element uses-permission at
  AndroidManifest.xml:14:5-84
  Missing 'name' key attribute on element uses-permission at AndroidManifest.xml:15:5-78
  Missing 'name' key attribute on element uses-permission at AndroidManifest.xml:16:5-90
  FAILURE: Build failed with an exception.

What went wrong: Execution failed for task ':processDebugManifest'.

Manifest merger failed with multiple errors, see logs

This is my plugin's AndroidManifest.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
    xmlns:android="http://schemas.android.com/apk/res/android"
    id="cordova-plugin-pluginTest"
    version="1.0.0">

  <description>
    Cordova Plugin
  </description>

    <license>MIT</license>

    <engines>
    <engine name="cordova" version=">=6.0" />
    </engines>

    <js-module src="www/index.js" name="index">
      <clobbers target="window.plugins.pluginTest" />
    </js-module><!--  -->

    <!-- android -->
    <platform name="android">
      <config-file target="res/xml/config.xml" parent="/*">
        <feature name="pluginTest">
          <param name="android-package" value="pluginTest.plugin.cordova.pluginTest"/>
        </feature>
      </config-file>
      <config-file target="AndroidManifest.xml" parent="/*">
        <uses-permission name="android.permission.WRITE_SETTINGS" platform="android"/>
        <uses-permission name="android.permission.INTERNET" platform="android"/>
        <uses-permission name="android.permission.ACCESS_NETWORK_STATE" platform="android"/>
        <uses-permission name="android.permission.CHANGE_NETWORK_STATE" platform="android"/>
        <uses-permission name="android.permission.ACCESS_WIFI_STATE" platform="android"/>
        <uses-permission name="android.permission.CHANGE_WIFI_STATE" platform="android"/>
      </config-file>

      <source-file src="src/android/pluginTest.java" target-dir="src/pluginTest/plugin/cordova"/>
    </platform>

</plugin>
</code>```

What I'm doing wrong? Any suggestions?

答:
You need to prefix the attribute name with the android: namespace. You can also get rid of platform="android" as it's unnecessary:

```<code>  <config-file target="AndroidManifest.xml" parent="/*">
    <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
  </config-file>
</code>```

Title: CORDOVA: Missing 'name' key attribute

Body:
I'm trying to create a simple Cordova plugin but when I try to BUILD it I get this error:

Missing 'name' key attribute on element uses-permission at
  AndroidManifest.xml:14:5-84
  Missing 'name' key attribute on element uses-permission at AndroidManifest.xml:15:5-78
  Missing 'name' key attribute on element uses-permission at AndroidManifest.xml:16:5-90
  FAILURE: Build failed with an exception.

What went wrong: Execution failed for task ':processDebugManifest'.

Manifest merger failed with multiple errors, see logs

This is my plugin's AndroidManifest.xml:

<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
    xmlns:android="http://schemas.android.com/apk/res/android"
    id="cordova-plugin-pluginTest"
    version="1.0.0">

  <description>
    Cordova Plugin
  </description>

    <license>MIT</license>

    <engines>
    <engine name="cordova" version=">=6.0" />
    </engines>

    <js-module src="www/index.js" name="index">
      <clobbers target="window.plugins.pluginTest" />
    </js-module>

    <platform name="android">
      <config-file target="res/xml/config.xml" parent="/*">
        <feature name="pluginTest">
          <param name="android-package" value="pluginTest.plugin.cordova.pluginTest"/>
        </feature>
      </config-file>
      <config-file target="AndroidManifest.xml" parent="/*">
        <uses-permission name="android.permission.WRITE_SETTINGS" platform="android"/>
        <uses-permission name="android.permission.INTERNET" platform="android"/>
        <uses-permission name="android.permission.ACCESS_NETWORK_STATE" platform="android"/>
        <uses-permission name="android.permission.CHANGE_NETWORK_STATE" platform="android"/>
        <uses-permission name="android.permission.ACCESS_WIFI_STATE" platform="android"/>
        <uses-permission name="android.permission.CHANGE_WIFI_STATE" platform="android"/>
      </config-file>

      <source-file src="src/android/pluginTest.java" target-dir="src/pluginTest/plugin/cordova"/>
    </platform>

</plugin>

What I'm doing wrong? Any suggestions?

Body:
You need to prefix the attribute name with the android: namespace. You can also get rid of platform="android" as it's unnecessary:

  <config-file target="AndroidManifest.xml" parent="/*">
    <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
  </config-file>


问:
Deserializing a JSON file with c#
My problem is
i have this JSON file:

and i have to save it in a list but when i try to print the first element of the list I get a System.ArgumentOutOfRangeException, as if my list is empty. this is my code:

```<code>JavaScriptSerializer ser = new JavaScriptSerializer();
        Causali o = new Causali();
        List<CausaliList> lista = new List<CausaliList>();
        WebRequest causali = (HttpWebRequest)WebRequest.Create("http://trackrest.cgestmobile.it/causali");
        WebResponse risposta = (HttpWebResponse)CreateCausaliRequest(causali).GetResponse();
        Stream data = risposta.GetResponseStream();
        StreamReader Leggi = new StreamReader(data);
        string output = Leggi.ReadToEnd();
        lista = ser.Deserialize<List<CausaliList>>(output);
        lst2.Items.Add(lista[0]);
</code>```

and these are my two class for the saves:

```<code>class Causali
    {
        public int id;
        public string causaliname;
        public string identificationcode;
        public string expired;
    }
</code>```

and

```<code>class CausaliList
    {
        public Causali causali;
    }
</code>```

can you help me solve it?

答:
please try this as your root object:

```<code>public class CausaliList
{
    public List<Causali> causali { get; set; }
}
</code>```

then deserilize your object like this:

```<code>lista = ser.Deserialize<CausaliList>(output);
</code>```

finally you can access to list like this:

```<code>lst2.Items.Add(lista.causali[0]);
</code>```

Note: i strongly recommend to use json.NET.

Title: Deserializing a JSON file with c#

Body:
My problem is
i have this JSON file:

and i have to save it in a list but when i try to print the first element of the list I get a System.ArgumentOutOfRangeException, as if my list is empty. this is my code:

JavaScriptSerializer ser = new JavaScriptSerializer();
        Causali o = new Causali();
        List<CausaliList> lista = new List<CausaliList>();
        WebRequest causali = (HttpWebRequest)WebRequest.Create("http://trackrest.cgestmobile.it/causali");
        WebResponse risposta = (HttpWebResponse)CreateCausaliRequest(causali).GetResponse();
        Stream data = risposta.GetResponseStream();
        StreamReader Leggi = new StreamReader(data);
        string output = Leggi.ReadToEnd();
        lista = ser.Deserialize<List<CausaliList>>(output);
        lst2.Items.Add(lista[0]);

and these are my two class for the saves:

class Causali
    {
        public int id;
        public string causaliname;
        public string identificationcode;
        public string expired;
    }

and

class CausaliList
    {
        public Causali causali;
    }

can you help me solve it?

Body:
please try this as your root object:

public class CausaliList
{
    public List<Causali> causali { get; set; }
}

then deserilize your object like this:

lista = ser.Deserialize<CausaliList>(output);

finally you can access to list like this:

lst2.Items.Add(lista.causali[0]);

Note: i strongly recommend to use json.NET.


问:
Page have reloaded all time when I try to get her via cURL
So, I need to parse some content from http://israelbar.org.il, and using for this cURL, but when I run script - tab in browser all time reload, and nothing showed.

```<code>$browser = curl_init();
curl_setopt($browser, CURLOPT_URL, $url);
curl_setopt($browser, CURLOPT_REFERER, $referer);
curl_setopt($browser, CURLOPT_USERAGENT, $agent);
curl_setopt($browser, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($browser, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($browser, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($browser, CURLOPT_CONNECTTIMEOUT, 10); //times out after 11s
curl_setopt($browser, CURLOPT_TIMEOUT, 50); //times out after 51s
curl_setopt($browser, CURLOPT_COOKIEJAR, $cookie_file_path);
curl_setopt($browser, CURLOPT_COOKIEFILE, $cookie_file_path);
$retVal = curl_exec ($browser);
curl_close ($browser);
unset($browser);
return $retVal;
</code>```

Also, I try NodeJS, and get some, unknown for me listing of JS code in console.

I think, that main problem - it's different headers, and I must send the same headers via cURL, like a browser.

答:
Have you tried capturing the working browser request with a tool like Fiddler? (http://www.telerik.com/fiddler). Also, can you clarify the language and set up you are using (looks like PHP?) And which 'tab' is reloading (is it your own site's?)

Other things to try:
 - Call a site you know will work first -- to ensure your code is correct
 - Adjust the timeout values to much larger values when testing

Body:
So, I need to parse some content from http://israelbar.org.il, and using for this cURL, but when I run script - tab in browser all time reload, and nothing showed.

$browser = curl_init();
curl_setopt($browser, CURLOPT_URL, $url);
curl_setopt($browser, CURLOPT_REFERER, $referer);
curl_setopt($browser, CURLOPT_USERAGENT, $agent);
curl_setopt($browser, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($browser, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($browser, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($browser, CURLOPT_CONNECTTIMEOUT, 10); //times out after 11s
curl_setopt($browser, CURLOPT_TIMEOUT, 50); //times out after 51s
curl_setopt($browser, CURLOPT_COOKIEJAR, $cookie_file_path);
curl_setopt($browser, CURLOPT_COOKIEFILE, $cookie_file_path);
$retVal = curl_exec ($browser);
curl_close ($browser);
unset($browser);
return $retVal;

Also, I try NodeJS, and get some, unknown for me listing of JS code in console.

I think, that main problem - it's different headers, and I must send the same headers via cURL, like a browser.


问:
Vagrant install docker with puppet
I am trying to install docker on the trusty64 vagrant image:

Vagrantfile

```<code># -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/trusty64"
  config.vm.hostname = "apps.local"
  config.vm.provision "shell", inline: <<-SHELL
    puppet module install garethr-docker
  SHELL

  config.vm.provision "puppet"
end
</code>```

manifests/default.pp

```<code>include 'docker'

docker::image { 'ubuntu':
  image_tag => 'trusty'
}
</code>```

And the output of vagrant up :

```<code>==> default: Running provisioner: shell...
    default: Running: inline script
==> default: Notice: Preparing to install into /etc/puppet/modules ...
==> default: Notice: Downloading from https://forge.puppetlabs.com ...
==> default: Notice: Installing -- do not interrupt ...
==> default: /etc/puppet/modules
==> default: └─┬ garethr-docker (v5.3.0)
==> default:   ├── puppetlabs-apt (v3.0.0)
==> default:   ├── puppetlabs-stdlib (v4.17.0)
==> default:   └── stahnma-epel (v1.2.2)
==> default: Running provisioner: puppet...
==> default: Running Puppet with default.pp...
==> default: Warning: Config file /etc/puppet/hiera.yaml not found, using Hiera defaults
==> default: Error: Syntax error at 'Variant'; expected ')' at /etc/puppet/modules/apt/manifests/init.pp:6 on node carcosa.local
==> default: Error: Syntax error at 'Variant'; expected ')' at /etc/puppet/modules/apt/manifests/init.pp:6 on node carcosa.local
The SSH command responded with a non-zero exit status. Vagrant
assumes that this means the command failed. The output for this command
should be in the log above. Please read the output to determine what
went wrong.
</code>```

Can someone tell me what am I doing wrong ?

答:
The latest version of puppetlabs-apt module supports only the latest version of puppet

```<code>Latest version is compatible with:
 - Puppet Enterprise 2016.5.x, 2016.4.x
 - Puppet >= 4.7.0 < 5.0.0
 - Ubuntu, Debian
</code>```

If you want to make if work in your example you need to force the installation of a version supported by puppet 3.x (see https://forge.puppet.com/puppetlabs/apt/1.6.0/changelog)

The following Vagrantfile will do the work

```<code># -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/trusty64"
  #config.vm.provision "docker"

  config.vm.hostname = "apps.local"
  config.vm.provision "shell", inline: <<-SHELL
    puppet module install puppetlabs-apt --version 2.4.0
    puppet module install garethr-docker
  SHELL

  config.vm.provision "puppet"
end
</code>```

Title: Vagrant install docker with puppet

Body:
I am trying to install docker on the trusty64 vagrant image:

Vagrantfile

# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/trusty64"
  config.vm.hostname = "apps.local"
  config.vm.provision "shell", inline: <<-SHELL
    puppet module install garethr-docker
  SHELL

  config.vm.provision "puppet"
end

manifests/default.pp

include 'docker'

docker::image { 'ubuntu':
  image_tag => 'trusty'
}

And the output of vagrant up :

==> default: Running provisioner: shell...
    default: Running: inline script
==> default: Notice: Preparing to install into /etc/puppet/modules ...
==> default: Notice: Downloading from https://forge.puppetlabs.com ...
==> default: Notice: Installing -- do not interrupt ...
==> default: /etc/puppet/modules
==> default: └─┬ garethr-docker (v5.3.0)
==> default:   ├── puppetlabs-apt (v3.0.0)
==> default:   ├── puppetlabs-stdlib (v4.17.0)
==> default:   └── stahnma-epel (v1.2.2)
==> default: Running provisioner: puppet...
==> default: Running Puppet with default.pp...
==> default: Warning: Config file /etc/puppet/hiera.yaml not found, using Hiera defaults
==> default: Error: Syntax error at 'Variant'; expected ')' at /etc/puppet/modules/apt/manifests/init.pp:6 on node carcosa.local
==> default: Error: Syntax error at 'Variant'; expected ')' at /etc/puppet/modules/apt/manifests/init.pp:6 on node carcosa.local
The SSH command responded with a non-zero exit status. Vagrant
assumes that this means the command failed. The output for this command
should be in the log above. Please read the output to determine what
went wrong.

Can someone tell me what am I doing wrong ?

Body:
The latest version of puppetlabs-apt module supports only the latest version of puppet

Latest version is compatible with:
 - Puppet Enterprise 2016.5.x, 2016.4.x
 - Puppet >= 4.7.0 < 5.0.0
 - Ubuntu, Debian

If you want to make if work in your example you need to force the installation of a version supported by puppet 3.x (see https://forge.puppet.com/puppetlabs/apt/1.6.0/changelog)

The following Vagrantfile will do the work

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/trusty64"
  #config.vm.provision "docker"

  config.vm.hostname = "apps.local"
  config.vm.provision "shell", inline: <<-SHELL
    puppet module install puppetlabs-apt --version 2.4.0
    puppet module install garethr-docker
  SHELL

  config.vm.provision "puppet"
end


问:
Is there a way to remove private members from Content Assist in Eclipse
I'm in Eclipse writing Java. I come from Visual Studio with Resharper writing C#.

When Content Assist comes up, I see all the private members of a class, even though I'm not editing that class. Is there a way I can turn that off?

It's really distracting.

答: If you do not explicitly write a method's access level (public, protected, or private), then it will default to package-private, and these methods will probably been shown in Content Assist.</p>

OwnerDisplayName: ageektrapped

OwnerDisplayName: axelclk


问:
Adding perspective to HTML for global Parallax - Pure CSS
I have been following Keith Clark's guide to CSS Parallax. His concept it like so:

HTML:

```<code><div class="container”>
  <div class="parallax-child”></div>
</div>
</code>```

CSS:

```<code>.container {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow-y: scroll;
  perspective: 1px;
  perspective-origin: 0 0;
}

.parallax-child {
  transform-origin: 0 0;
  transform: translateZ(-2px) scale(3);
}
</code>```

This works perfect for the most part, for example on my development website. However I need to add this effect to another website where I can't control the HTML structure much at all, below is the basic structure tree, added comments to where I can edit.

```<code><html>
  <body>
    <div itemscope itemtype="http://schema.org/AutoDealer">
      <div id="main-wrap">
        <div class="row">
          <div class="main twelvecol">

            <!-- Editable -->
            <div>
              <div class="row-block finance parallax__group">
                <div class="parallax__layer--back parallax__layer">
                  <p>Content in here scrolls slower than everything else</p>
                </div>
                <div class="wrapper">
                  <div class="container">
                    <div class="parallax__layer--base parallax__layer">
                      <p>This is all of the top level content</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- END Editable -->

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

I can add any styles I want, just can't edit the HTML structure apart from where stated in the comments.

My issue is I can't seem to get the parallax effect to work, if I put the example container styles for the parallax effect (at the top of this post) on the body the parallax effect works...

From what I have read I would need to add the transform-style: preserve-3d; style onto elements between the container and the children, however this doesn't appear to work.

Anyone know what's going wrong?

Edit:

Codepen of the working CSS on the body.

Codepen of the non-working CSS on the HTML.

Edit:
Due to more complications with fixed positions and detecting body scroll (not possible it seems), I really need to get this working by using the HTML element.

What is strange, is that is sort of works. Follow this link and click and drag the slider left/right, the parallax effect is there, just not when you scroll down...

Not too sure why this effect doesn't work when you scroll down...

答:
Guessing no one knows the answer to this, so thought I may as well post what I did.

It appears that you simply can't use the HTML tag for this Parallax effect, so I have just put the effect on a containing div, so then for things functions such as sticky headers I can simply check for the scroll amount on this div and set anything sticky to position: sticky.

Sticky doesn't work on Edge or IE so a fall back would be just to completely disable the parallax effect on these browsers and give the scrolling back to the HTML element so you can use position: fixed.

Fallback:

```<code>@supports ((perspective: 1px) and (not (-webkit-overflow-scrolling: touch)) and ((position: sticky))) {
</code>```

Body:
I have been following Keith Clark's guide to CSS Parallax. His concept it like so:

HTML:

CSS:

.container {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow-y: scroll;
  perspective: 1px;
  perspective-origin: 0 0;
}

.parallax-child {
  transform-origin: 0 0;
  transform: translateZ(-2px) scale(3);
}

This works perfect for the most part, for example on my development website. However I need to add this effect to another website where I can't control the HTML structure much at all, below is the basic structure tree, added comments to where I can edit.

Content in here scrolls slower than everything else

This is all of the top level content

I can add any styles I want, just can't edit the HTML structure apart from where stated in the comments.

My issue is I can't seem to get the parallax effect to work, if I put the example container styles for the parallax effect (at the top of this post) on the body the parallax effect works...

From what I have read I would need to add the transform-style: preserve-3d; style onto elements between the container and the children, however this doesn't appear to work.

Anyone know what's going wrong?

Edit:

Codepen of the working CSS on the body.

Codepen of the non-working CSS on the HTML.

Edit:
Due to more complications with fixed positions and detecting body scroll (not possible it seems), I really need to get this working by using the HTML element.

What is strange, is that is sort of works. Follow this link and click and drag the slider left/right, the parallax effect is there, just not when you scroll down...

Not too sure why this effect doesn't work when you scroll down...

Body:
Guessing no one knows the answer to this, so thought I may as well post what I did.

It appears that you simply can't use the HTML tag for this Parallax effect, so I have just put the effect on a containing div, so then for things functions such as sticky headers I can simply check for the scroll amount on this div and set anything sticky to position: sticky.

Sticky doesn't work on Edge or IE so a fall back would be just to completely disable the parallax effect on these browsers and give the scrolling back to the HTML element so you can use position: fixed.

Fallback:

@supports ((perspective: 1px) and (not (-webkit-overflow-scrolling: touch)) and ((position: sticky))) {


问:
Xcode 8.0 Command /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
When I compile my code on Xcode Version 8.0 beta 4 (8S188o) I get this single error bringing the compilation to failure:

Command
  /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc
  failed with exit code 1

I tried to clean the project and wipe the derived folder but that did not change things.
What is it and how may I know more about it?

When I try to compile on the terminal the error being reported is:

Invalid bitcast\n  %.asUnsubstituted = bitcast %swift.error* %13 to
  i2, !dbg !438\nLLVM ERROR: Broken function found, compilation
  aborted!\n

答:
I got this error and resolved by changing Xcode command line tools,

Goto Xcode -> Preferences -> Choose Locations tab

Choose required Command Line Tools from drop down, run the project error has been fixed.


问:
AngularJS arrays and incremental memory usage
I am using a $timeout to periodically pull tabular data from the back end and display them in HTML. I suspect every time I get an update, a new memory segment is being allocated in the browser for the JSON array. I was wondering if that's the case. Below are simplified fragments of code.

HTML`

```<code><tr ng-repeat="measurement in measurementResults">
  <td>{{measurement.type}}</td>
  <td>{{measurement.value}}</td>
</tr>
</code>```

JS

```<code>function startTimeout() {
  MeasurementService.getNewMeasurements(function (measuredData) {
    $scope.measurementResults = measuredData;

  });

  $timeout(startTimeout, 15000);

}

startTimeout();
</code>```

This is the JSON data array format that I am passing to the $scope.

```<code>[{"type":type1,"value":10}, {"type":type2,"value":20}, {"type":type3,"value":80}]
</code>```

Is $scope.measurementResults pointing to a new memory location (or creating a new array) every time I receive the measuredData from the service callback?

EDIT:
I am attaching two screenshots of memory graphs, the first one shows how the nodes go up and down (green line), and the second one shows how the line becomes flat after applying "track by $index"

答:
```<code>//You may use track by for performance boost
<tr ng-repeat="measurement in measurementResults track by $index">
  <td>{{measurement.type}}</td>
  <td>{{measurement.value}}</td>
</tr>
</code>```

Body:
I am using a $timeout to periodically pull tabular data from the back end and display them in HTML. I suspect every time I get an update, a new memory segment is being allocated in the browser for the JSON array. I was wondering if that's the case. Below are simplified fragments of code.

HTML`

  {{measurement.type}}
  {{measurement.value}}

JS

function startTimeout() {
  MeasurementService.getNewMeasurements(function (measuredData) {
    $scope.measurementResults = measuredData;

  });

  $timeout(startTimeout, 15000);

}

startTimeout();

This is the JSON data array format that I am passing to the $scope.

[{"type":type1,"value":10}, {"type":type2,"value":20}, {"type":type3,"value":80}]

Is $scope.measurementResults pointing to a new memory location (or creating a new array) every time I receive the measuredData from the service callback?

EDIT:
I am attaching two screenshots of memory graphs, the first one shows how the nodes go up and down (green line), and the second one shows how the line becomes flat after applying "track by $index"


问:
Sort keys in a dictionary Python
I have a Json file like this:

```<code>{
  "wasGeneratedBy": {
    "_:wGB3": {
      "prov:entity": "ivo://stsci/DSS-digitized-J.444",
      "prov:activity": "stcsiNum-1b"
    },
    "_:wGB1": {
      "prov:entity": "ivo://stsci/DSS-digitized-J.444-cutouts",
      "prov:activity": "cds_cutout444"
    },
    "_:wGB2": {
      "prov:entity": "ivo://stsci/DSS-digitized-I.444",
      "prov:activity": "stcsiNum-1a"
    }
  },
  "activity": {
    "stcsiNum-1a": {},

  },
  "used": {
    "_:u6": {
      "prov:entity": "ivo://stsci/DSS-Plate-R.444",
      "prov:activity": "stcsiNum-1c"
    },
    "_:u2": {
      "prov:entity": "ivo://stsci/DSS-Plate-I.444",
      "prov:activity": "stcsiNum-1a"
    },
    "_:u3": {
      "prov:entity": "ivo://stsci/DSS-digitized-J.444",
      "prov:activity": "cds_cutout444"

  },
  "entity": {
    "ivo://stsci/DSS-digitized-R.444": {},
    "ivo://stsci/DSS-digitized-J.444-cutouts": {},
    "ivo://stsci/DSS-Plate-R.444": {},
  }
}
</code>```

But I want to sort all the keys ("wasGenereratedBy","activiy"...) in a specific order like this ("activity","entity","used","wasGeneratedBy")

I have declared this:

```<code>my_own_order = ['entity', 'used', 'activity','wasGeneratedBy']
</code>```

And I have try this, but doesn't work:

```<code>print sorted(fileName,order=my_own_order)
</code>```

Any suggestions ? Thanks you

答:
Use OrderedDict:

```<code>from collections import OrderedDict

print OrderedDict((k,mydict[k] for k in  my_own_order))
</code>```

Title: Sort keys in a dictionary Python

Body:
I have a Json file like this:

{
  "wasGeneratedBy": {
    "_:wGB3": {
      "prov:entity": "ivo://stsci/DSS-digitized-J.444",
      "prov:activity": "stcsiNum-1b"
    },
    "_:wGB1": {
      "prov:entity": "ivo://stsci/DSS-digitized-J.444-cutouts",
      "prov:activity": "cds_cutout444"
    },
    "_:wGB2": {
      "prov:entity": "ivo://stsci/DSS-digitized-I.444",
      "prov:activity": "stcsiNum-1a"
    }
  },
  "activity": {
    "stcsiNum-1a": {},

  },
  "used": {
    "_:u6": {
      "prov:entity": "ivo://stsci/DSS-Plate-R.444",
      "prov:activity": "stcsiNum-1c"
    },
    "_:u2": {
      "prov:entity": "ivo://stsci/DSS-Plate-I.444",
      "prov:activity": "stcsiNum-1a"
    },
    "_:u3": {
      "prov:entity": "ivo://stsci/DSS-digitized-J.444",
      "prov:activity": "cds_cutout444"

  },
  "entity": {
    "ivo://stsci/DSS-digitized-R.444": {},
    "ivo://stsci/DSS-digitized-J.444-cutouts": {},
    "ivo://stsci/DSS-Plate-R.444": {},
  }
}

But I want to sort all the keys ("wasGenereratedBy","activiy"...) in a specific order like this ("activity","entity","used","wasGeneratedBy")

I have declared this:

my_own_order = ['entity', 'used', 'activity','wasGeneratedBy']

And I have try this, but doesn't work:

print sorted(fileName,order=my_own_order)

Any suggestions ? Thanks you

Body:
Use OrderedDict:

from collections import OrderedDict

print OrderedDict((k,mydict[k] for k in  my_own_order))


问:
How to avoid negative time between time difference?
I'm developing an app in which I'm using Java8 Time. I'm facing an issue.

Let's say Time A is 08:00 and Time B is 17:00, so the difference of between these two times will be 9h which in my case is correct, but if Time A is 18:00 and Time B is 02:00 it should be 8h, but in my case my program is returning -16. Kindly someone guide me how to solve this.

My code:

```<code>@Test
public void testTime()
{
    DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm");

    String s = "18:00";
    String e = "02:00";

    // Parse datetime string to java.time.LocalDateTime instance
    LocalTime startTime = LocalTime.parse(s, format);
    LocalTime endTime = LocalTime.parse(e, format);

    String calculatedTime = ChronoUnit.HOURS.between(startTime, endTime)%24 + ":"
            + ChronoUnit.MINUTES.between(startTime, endTime)%60;

    System.out.println(calculatedTime);

}
</code>```

答:
You have to  calculate time differences modulo 24.
So take the difference as you already do and then compute it modulo 24. Note that in Java -16%24 would return -16 so what you really need to do is the following:

```<code>public static int modulus(int n, int m){
    return  (n < 0) ? (m - (Math.abs(n) % m) ) %m : (n % m);
}
</code>```

which always return a  positive result.

Body:
I'm developing an app in which I'm using Java8 Time. I'm facing an issue.

Let's say Time A is 08:00 and Time B is 17:00, so the difference of between these two times will be 9h which in my case is correct, but if Time A is 18:00 and Time B is 02:00 it should be 8h, but in my case my program is returning -16. Kindly someone guide me how to solve this.

My code:

@Test
public void testTime()
{
    DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm");

    String s = "18:00";
    String e = "02:00";

    // Parse datetime string to java.time.LocalDateTime instance
    LocalTime startTime = LocalTime.parse(s, format);
    LocalTime endTime = LocalTime.parse(e, format);

    String calculatedTime = ChronoUnit.HOURS.between(startTime, endTime)%24 + ":"
            + ChronoUnit.MINUTES.between(startTime, endTime)%60;

    System.out.println(calculatedTime);

}

Body:
You have to  calculate time differences modulo 24.
So take the difference as you already do and then compute it modulo 24. Note that in Java -16%24 would return -16 so what you really need to do is the following:

public static int modulus(int n, int m){
    return  (n < 0) ? (m - (Math.abs(n) % m) ) %m : (n % m);
}

which always return a  positive result.


问:
Portable PHP IDE / Editor
There are a lot of IDE posts here but not for portable.

Can anybody help me find a good portable PHP IDE? I am looking for this features:

FTP && SFTP Sitemanager

Syntax Highlighting

Auto-complete (Optional)

I am fine even with a paid version. I tried aptana on my usb but the experience was not good.

答: Have you tried a portable gVim. It has a lots of plugins for ftp and sftp. I usualy use it with a portable WinScp together. About the autocomplete: I have it running under the desktop version, but i havent find a way to do that at a portable version. But I get used to snippets like in TextMate. Completion is fine, but I find this solution better.</p>

Title: Portable PHP IDE / Editor


答:
You can use this code to read data from the excel files.</p>

```<code>import os
import datetime
import sys
import re
import openpyxl
import uuid
from openpyxl import load_workbook

class ExcelDictSmall(dict):
    '''
    Dictionary with all Sheet Names as key, value is a List of Rows each item in a Row List is a List of Cells
    '''
    def __init__(self,dir,fname):
        fullFname = os.path.join(dir,fname)
        wb = load_workbook(filename=fullFname, read_only=True)
        allSheets= wb.get_sheet_names()
        for sheet in allSheets:
            sheetList = []
            rowlist=[]
            for row in wb[sheet].rows:
                for cell in row:
                    rowlist.append(cell.value)
                sheetList.append(rowlist)
                rowlist=[]
            self[sheet]=sheetList
</code>```

Title: Reading data from columns in Excel

Body:
I am working on a python script to read data from columns in an Excel file and using that data to execute commands on a Cisco switch.

For example, I have below 2 columns

Switch        MAC
aaa.com      mac.aaa.000
bbb.com      mac.bbb.000
ccc.com      mac.ccc.000
.....        .....

The python will now go to switch aaa and will set port security with mac mac.aaa.000 as sticky.

This is the command:

switchport port-security **<mac-address>** sticky

Now I have login part done and I can execute commands. I need help with the part which reads 2 columns from file and know to login to switch a and sticky macaaa on corresponding column.

Here is how I am logging in and executing commands on switch:

term_len = "term len 0"
# Need a loop here that gets switchname from coulmn A and assign it to variable host and also corresponding MAC address and assigns it to variable MAC
host = ""
MAC = ""
session = telnetlib.Telnet(host)
session.write(cred.username + '\n')
session.read_until('Password: ')
session.write(cred.password + '\n')
session.read_until('>')
session.write(cred.en + '\n')
session.read_until('Password: ')
session.write(cred.en_pass + '\n')
session.read_until('#')
session.write(term_len + '\n')
session.write(switchport port-security **MAC** sticky + '\n')

Please help. The loop will read all switches and MAC from files and executes the sticky command.

Body:
You can use this code to read data from the excel files.

import os
import datetime
import sys
import re
import openpyxl
import uuid
from openpyxl import load_workbook

class ExcelDictSmall(dict):
    '''
    Dictionary with all Sheet Names as key, value is a List of Rows each item in a Row List is a List of Cells
    '''
    def __init__(self,dir,fname):
        fullFname = os.path.join(dir,fname)
        wb = load_workbook(filename=fullFname, read_only=True)
        allSheets= wb.get_sheet_names()
        for sheet in allSheets:
            sheetList = []
            rowlist=[]
            for row in wb[sheet].rows:
                for cell in row:
                    rowlist.append(cell.value)
                sheetList.append(rowlist)
                rowlist=[]
            self[sheet]=sheetList


问:
How to plot data (Var1 vs Var2 as a line plot) containing large number of factors
I have some data of the following form:

```<code>Factor  Var1  Var2
1       100   1.5
2       150   1.2
3       90    1.9
......
1       80    2.0
2       96    2.1
3       50    2.9
</code>```

I have to compare the variation in Var2 with Var1 for the different factors. The idea is to figure out the range of values in Var1 corresponding to which there are low values in Var2, and for which factor.
I have up to 32 factors.

What is the best way to go about this?

So far, I have implemented this as a line plot in ggplot (see figure below).

```<code>ggplot(data = df, aes(x = df$var1, y = df$var2, colour = df$Factor)) +
  geom_line(size=0.05) +
  geom_point(size=0.8) +
  coord_cartesian(ylim = c(0,5)) +
  labs(x='var1', y='var2')
</code>```

However, the figure is very cluttered, and it is difficult to make out the patterns for the different factors, especially because of the colour coding as a gradient.

I also tried to use different shapes for the points.

```<code>ggplot(data = df, aes(x = df$var1, y = df$var2, colour = df$factor)) +
  geom_line(size=0.05) +
  geom_point(size=0.8, aes(shape=factor(df$Factor))) +
  coord_cartesian(ylim = c(0,5)) +
  labs(x='var1', y='var2')
</code>```

But this gives a warning message (see below), and does not show symbols for all the factors.

```<code> # Warning messages:
 #    1: The shape palette can deal with a maximum of 6 discrete values because more than 6 becomes difficult to discriminate; you have 29. Consider specifying shapes manually if you must have them.
</code>```

What is the best way to visualize this variation in the data? The number of factors can vary (maximum 32).

** As suggested, I tried out facet_wrap (see fig below).

```<code>ggplot(data = df, aes(x = df$var1, y = df$var2)) + geom_line(size=0.05) + geom_point(size=0.8) + coord_cartesian(ylim = c(0,5)) + facet_wrap(~ df$Factor) + labs(x='var1', y='var2') #+ geom_hline(yintercept = 2)
</code>```

facet_wrap fig

For the sake of comparison among the factors, I would like to add a horizontal line to all the plots. But geom_hline(yintercept = 2) does not do the trick, gives the following error msg:

```<code>Error in `$<-.data.frame`(`*tmp*`, "PANEL", value = c(6L, 8L, 24L, 26L, : replacement has 1170 rows, data has 1
</code>```

How to add a horizontal line to all these plots?
Alternately, is there a way to separate the data frame into smaller data frames, consisting of 5-6 factors instead of all, and plot for each of these smaller sets?

答:
If your factor levels has an intrinsic order maybe it is better to plot them as a gradient, as if they were numeric:

```<code>df$Factor_numeric <- as.numeric(gsub("2MCT ", "", Factor))
ggplot(data = df,
       aes(x = var1,
           y = var2,
           colour = Factor_numeric) +
  geom_line(size=0.05) +
  scale_colour_gradient(name = "Your Factor",
                        labels = function(breaks)  paste0("2MCT ", breaks)) +
  coord_cartesian(ylim = c(0,5)) +
  labs(x='var1', y='var2')
</code>```

Another option is to use a new column in the data frame that groups your Factor so you end up with less plots:

```<code>df$grouped_Factor <- NA
df$grouped_Factor[df$Factor %in% paste0("2MCT ", 101:108)] <- "G1"
df$grouped_Factor[df$Factor %in% paste0("2MCT ", 109:118)] <- "G2"
df$grouped_Factor[df$Factor %in% paste0("2MCT ", 119:124)] <- "G3"
df$grouped_Factor[df$Factor %in% paste0("2MCT ", 125:132)] <- "G4"

ggplot(data = df,
       aes(x = var1, y = var2, colour = Factor)) +
  geom_line(size=0.05) +
  geom_point(size=0.8) +
  coord_cartesian(ylim = c(0,5)) +
  facet_wrap(~ grouped_Factor) +
  labs(x='var1', y='var2')
</code>```

Body:
I have some data of the following form:

Factor  Var1  Var2
1       100   1.5
2       150   1.2
3       90    1.9
......
1       80    2.0
2       96    2.1
3       50    2.9

I have to compare the variation in Var2 with Var1 for the different factors. The idea is to figure out the range of values in Var1 corresponding to which there are low values in Var2, and for which factor.
I have up to 32 factors.

What is the best way to go about this?

So far, I have implemented this as a line plot in ggplot (see figure below).

ggplot(data = df, aes(x = df$var1, y = df$var2, colour = df$Factor)) +
  geom_line(size=0.05) +
  geom_point(size=0.8) +
  coord_cartesian(ylim = c(0,5)) +
  labs(x='var1', y='var2')

However, the figure is very cluttered, and it is difficult to make out the patterns for the different factors, especially because of the colour coding as a gradient.

I also tried to use different shapes for the points.

ggplot(data = df, aes(x = df$var1, y = df$var2, colour = df$factor)) +
  geom_line(size=0.05) +
  geom_point(size=0.8, aes(shape=factor(df$Factor))) +
  coord_cartesian(ylim = c(0,5)) +
  labs(x='var1', y='var2')

But this gives a warning message (see below), and does not show symbols for all the factors.

 # Warning messages:
 #    1: The shape palette can deal with a maximum of 6 discrete values because more than 6 becomes difficult to discriminate; you have 29. Consider specifying shapes manually if you must have them.

What is the best way to visualize this variation in the data? The number of factors can vary (maximum 32).

** As suggested, I tried out facet_wrap (see fig below).

ggplot(data = df, aes(x = df$var1, y = df$var2)) + geom_line(size=0.05) + geom_point(size=0.8) + coord_cartesian(ylim = c(0,5)) + facet_wrap(~ df$Factor) + labs(x='var1', y='var2') #+ geom_hline(yintercept = 2)

facet_wrap fig

For the sake of comparison among the factors, I would like to add a horizontal line to all the plots. But geom_hline(yintercept = 2) does not do the trick, gives the following error msg:

Error in `$<-.data.frame`(`*tmp*`, "PANEL", value = c(6L, 8L, 24L, 26L, : replacement has 1170 rows, data has 1

How to add a horizontal line to all these plots?
Alternately, is there a way to separate the data frame into smaller data frames, consisting of 5-6 factors instead of all, and plot for each of these smaller sets?

Body:
If your factor levels has an intrinsic order maybe it is better to plot them as a gradient, as if they were numeric:

df$Factor_numeric <- as.numeric(gsub("2MCT ", "", Factor))
ggplot(data = df,
       aes(x = var1,
           y = var2,
           colour = Factor_numeric) +
  geom_line(size=0.05) +
  scale_colour_gradient(name = "Your Factor",
                        labels = function(breaks)  paste0("2MCT ", breaks)) +
  coord_cartesian(ylim = c(0,5)) +
  labs(x='var1', y='var2')

Another option is to use a new column in the data frame that groups your Factor so you end up with less plots:

df$grouped_Factor <- NA
df$grouped_Factor[df$Factor %in% paste0("2MCT ", 101:108)] <- "G1"
df$grouped_Factor[df$Factor %in% paste0("2MCT ", 109:118)] <- "G2"
df$grouped_Factor[df$Factor %in% paste0("2MCT ", 119:124)] <- "G3"
df$grouped_Factor[df$Factor %in% paste0("2MCT ", 125:132)] <- "G4"

ggplot(data = df,
       aes(x = var1, y = var2, colour = Factor)) +
  geom_line(size=0.05) +
  geom_point(size=0.8) +
  coord_cartesian(ylim = c(0,5)) +
  facet_wrap(~ grouped_Factor) +
  labs(x='var1', y='var2')


问:
Benefits of non-tracking pixel to https to prewarm SSL handshake from http page
A client has an e-commerce website with the homepage, listing and detail pages (i.e. the catalog) over standard non-secure HTTP. The sign-in, cart, and checkout pages are behind secure https on the same domain. This is due to be changed later in the year, I'm well aware of how far behind the times http is but it is in the works.

However as an immediate optimization, quick to apply, is there any benefit to including a 1px x 1px img pixel pointing to a https img on the http page catalog pages?

Would this in any way prewarm the SSL handshake for when the end user adds an item to cart resulting in faster acknowledgement (cart is non-ajax again to be changed). I'm thinking about caching of certificate validation, revocation list checking etc..

Is there any downsides to this?

答:
No downside compared to no pixel.

Downsides compare to a full-https website:

Slower (except if all resources of the http pages use https, which will made de pixel useless)

Less secure (vulnerable to sslstrip attacks, can't use HSTS)


问:
How to fill a ComboBox using records from an Access database
I want to retrieve the data and display in a ComboBox but it's showing blank.

This is my code:

```<code>Imports System.Data.OleDb

Public Class frmAirwaybill

    Private Sub frmAirwaybill_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim cm As OleDbCommand = New OleDbCommand("select acc_no from tblshipper order by acc_no")
        cm.Connection = DBconnection()
        Dim dr As OleDbDataReader = cm.ExecuteReader
        Do While (dr.Read())
            txtAccountNo.Items.Add(dr.Item("acc_no"))
        Loop
        dr.Close()
        DBconnection.Close()
    End Sub
End Class*
</code>```

txtAccountNo is the ComboBox

What I want, when the form loads, is to load the accno from my database. How do I do that?

This is a screenshot showing the ComboBox with blank values:

My database connection is OK.

This is my connection on module file

```<code>Public Function DBconnection() As OleDbConnection

        Dim con As New OleDb.OleDbConnection
        Dim constring As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\SmartshipG2.mdb"
        con = New OleDb.OleDbConnection(constring)
        con.Open()
        Return con

End Function
</code>```

答:
The first thing to note is that you haven't opened the connection. This is probably the root cause.

That said, you are better binding to the .DataSource of the ComboBox using a DataTable and setting the .DisplayMember and .ValueMember properties.

I would also consider implementing Using:

Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.

Lastly, consider giving your ComboBox a better prefix. txt is often used for TextBox controls. I use cmb whilst others may use cbx. So in this case cmbAccountNo seems a better fit.

With the changes you code would look something like this:

```<code>Dim dt As New DataTable
Using con As OleDbConnection New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\SmartshipG2.mdb"),
      cmd As New OleDbCommand("SELECT [acc_no] FROM [tblshipper] ORDER BY [acc_no]", con)
    con.Open()

    dt.Load(cmd.ExecuteReader())
End Using

cmbAccountNo.DataSource = dt
cmbAccountNo.DisplayMember = "acc_no"
cmbAccountNo.ValueMember = "acc_no"
</code>```

Body:
I want to retrieve the data and display in a ComboBox but it's showing blank.

This is my code:

Imports System.Data.OleDb

Public Class frmAirwaybill

    Private Sub frmAirwaybill_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim cm As OleDbCommand = New OleDbCommand("select acc_no from tblshipper order by acc_no")
        cm.Connection = DBconnection()
        Dim dr As OleDbDataReader = cm.ExecuteReader
        Do While (dr.Read())
            txtAccountNo.Items.Add(dr.Item("acc_no"))
        Loop
        dr.Close()
        DBconnection.Close()
    End Sub
End Class*

txtAccountNo is the ComboBox

What I want, when the form loads, is to load the accno from my database. How do I do that?

This is a screenshot showing the ComboBox with blank values:

My database connection is OK.

This is my connection on module file

Public Function DBconnection() As OleDbConnection

        Dim con As New OleDb.OleDbConnection
        Dim constring As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\SmartshipG2.mdb"
        con = New OleDb.OleDbConnection(constring)
        con.Open()
        Return con

End Function

Body:
The first thing to note is that you haven't opened the connection. This is probably the root cause.

That said, you are better binding to the .DataSource of the ComboBox using a DataTable and setting the .DisplayMember and .ValueMember properties.

I would also consider implementing Using:

Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.

Lastly, consider giving your ComboBox a better prefix. txt is often used for TextBox controls. I use cmb whilst others may use cbx. So in this case cmbAccountNo seems a better fit.

With the changes you code would look something like this:

Dim dt As New DataTable
Using con As OleDbConnection New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\SmartshipG2.mdb"),
      cmd As New OleDbCommand("SELECT [acc_no] FROM [tblshipper] ORDER BY [acc_no]", con)
    con.Open()

    dt.Load(cmd.ExecuteReader())
End Using

cmbAccountNo.DataSource = dt
cmbAccountNo.DisplayMember = "acc_no"
cmbAccountNo.ValueMember = "acc_no"


问:
Getting below issue while fetching private repositories from GitHub with Jenkins
I have added credentials to the jenkins for GItHub account.
I was able to checkout code from github desktop.
But with Jenkins, I am getting below error with the private repositories.

答:
For detailed description you can visit below link:
https://devopsdiaryblog.wordpress.com/2017/06/06/jenkins-issue-with-fetching-github-data/</p>


问:
Using collection size in for loop comparison
Is there a compiler optimization for the size() methods of Collections in Java?

Consider the following code:

```<code>for(int i=0;i<list.size();i++)
      ...some operation.....
</code>```

There is a call to the size() methods for every i. Won't it be better to find out the size and reuse it? (Method calls have overheads).

```<code>final int len = list.size()
for(int i=0;i<len;i++)
      ...some operation.....
</code>```

However, when I timed both these code pieces there was no significant time difference, even for i as high as 10000000.
Am I missing something here?

Update1: I understand that the size is not computed again unless the collection changes. But there has to be some overhead associated with a method call. Is it the case that the compiler always inlines these (See Esko's answer)?

Update 2: My curiosity has been fueled further. From the answers given, I see that good JIT compilers will often inline this function call. But they will still have to determine whether the collection was modified or not. I am not accepting an answer in the hope that someone will give me pointers regarding how this is handled by compilers.

答:
The java language specification explains, that the expression is evaluated on each iteration step. With you example, list.size() is called 10.000.000 times.

This doesn't matter in your case, because list implementations (usually) have a private attribute that stores the actual list size. But it may cause trouble, if the evaluation really takes time. In those cases it's advisable to store the result of the expression to a local variable.

ContentLicense: CC BY-SA 4.0

Body:
Is there a compiler optimization for the size() methods of Collections in Java?

Consider the following code:

for(int i=0;i<list.size();i++)
      ...some operation.....

There is a call to the size() methods for every i. Won't it be better to find out the size and reuse it? (Method calls have overheads).

final int len = list.size()
for(int i=0;i<len;i++)
      ...some operation.....

However, when I timed both these code pieces there was no significant time difference, even for i as high as 10000000.
Am I missing something here?

Update1: I understand that the size is not computed again unless the collection changes. But there has to be some overhead associated with a method call. Is it the case that the compiler always inlines these (See Esko's answer)?

Update 2: My curiosity has been fueled further. From the answers given, I see that good JIT compilers will often inline this function call. But they will still have to determine whether the collection was modified or not. I am not accepting an answer in the hope that someone will give me pointers regarding how this is handled by compilers.


问:
How to handle input parameters while generating dynamic html from jquery function
I am using below function to generate dynamic HTML.

```<code>function (content) {
    $('#divMessage').append('<span>'+ content+ '</span>');
}
</code>```

Here I am appending content in div with id divMessage.

Here input parameter content can be any text passed to this function.

I am facing problem when I pass data containing html elements as it distorts html. I am not aable to paste it here as its get dostorted here in stack overflow editor as well.

How can I resolve this issue, TIA.

It should append what is being passed, don't want to convert html tags to html, if html tag with data is passed then html tag with data should be the ouput.

答:
To resolve this you need to only paser the content text to HTML

Just do this

```<code>    content= $.parseHTML(content);
$('#divMessage').append('<span>'+ content+ '</span>');
</code>```

Hope it will help!

Body:
I am using below function to generate dynamic HTML.

function (content) {
    $('#divMessage').append(''+ content+ '');
}

Here I am appending content in div with id divMessage.

Here input parameter content can be any text passed to this function.

I am facing problem when I pass data containing html elements as it distorts html. I am not aable to paste it here as its get dostorted here in stack overflow editor as well.

How can I resolve this issue, TIA.

It should append what is being passed, don't want to convert html tags to html, if html tag with data is passed then html tag with data should be the ouput.

Body:
To resolve this you need to only paser the content text to HTML

Just do this

    content= $.parseHTML(content);
$('#divMessage').append('<span>'+ content+ '</span>');

Hope it will help!


问:
pssh and known_hosts file
when I use pssh, trying to access a remote machine which is not inside the UNIX
known hosts file, pssh freeze after giving the password.
After having added the host using a direct ssh command, pssh works.

So is there an option to give to the pssh command in order to avoid this problem ?

Thanks for your help,
Regards

答:
You need to add the remote host key to the known_hosts file first. You can do that with a shell command:</p>

```<code>ssh-keyscan HOSTNAME >> $HOME/.ssh/known_hosts
</code>```

Title: pssh and known_hosts file

Body:
You need to add the remote host key to the known_hosts file first. You can do that with a shell command:

ssh-keyscan HOSTNAME >> $HOME/.ssh/known_hosts


问:
How do I exit/shut down a React Native app?
If my React Native app fails to connect to its backend, I show an Alert with an OK button. If this happens, there's no point in the app continuing to run, so I'd like to shut it down when the button is clicked. How do I do this?

I suspect the key is in AppRegistry but the docs are a bit scant.

答:
Write a native module that performs the following actions when called:

IOS:

```<code>exit(9);
</code>```

ANDROID:

```<code>((YourApplication) self.getApplicationContext()).kill();
</code>```

...EDIT...

Or just use the one I created: https://www.npmjs.com/package/react-native-exit-app

Body:
Write a native module that performs the following actions when called:

IOS:

exit(9);

ANDROID:

((YourApplication) self.getApplicationContext()).kill();

...EDIT...

Or just use the one I created: https://www.npmjs.com/package/react-native-exit-app


问:
C# Asp.NET Get URL Parameters
How I can get the number 68 of the following link? http://localhost:54547/Home/Details/68

I had a DB whit table "Modules", in each module i had content(that is other table in DB) . So when i click in see Contents, it pass a Module ID (that i click) for associate to Content ( localhost:54547/Home/Details/68). When I click for "Create a New Content", i want that the Module ID pass for the next link.

Thanks for help

I am programing in Asp.NET using C#

答:
Your method in the controller should be like this:</p>

```<code>[HttpPost]
public ActionResult Details(int id){
   // You will get value 68 in id

}
</code>```

Title: C# Asp.NET Get URL Parameters

Body:
Your method in the controller should be like this:

[HttpPost]
public ActionResult Details(int id){
   // You will get value 68 in id

}


问:
Correlation between a column and a group of others in Pandas
I am a beginner in Data Science and Python, and learning Statistics at the same time as leasure. I am not a Computer Scientist , so sorry if this question may sounds basic.

I have a Dataframe, which I process using Pandas using Python 3. From a preliminary exploration, I suspect that one of the columns is correlated to the behavior of two others instead of just one.

I can calculate the correlation coefficient between two single columns. However, is there a way to calculate some sort of "weighted" correlation between one column and two others?

答: You can compute and plot Correlation Matrix. Please refer http://www.marketcalls.in/python/quick-start-guide-compute-correlation-matrix-using-nsepy-pandas-python.html and python documentation. </p>