问:
Mongo DB unknown Error?
I am new to Mongo DB I have to implement it in java. I went through may slides but I am confused what is happening. I executed a small java program using mongo DB but it is not working?

My java code:

```<code>    public class MongoDbTesting {

    public void connectingMongo() throws UnknownHostException, MongoException{
    Mongo m = new Mongo("localhost" , 27017); //mongo object
    DB db = m.getDB("todo");
    System.out.println("Connected");
    //making a collection object which is table when compared to sql
    DBCollection items = db.getCollection("items");
    System.out.println("items got");

    //to work with document we need basicDbObject
    BasicDBObject query = new BasicDBObject();
    System.out.println("Created mongoObject");
    //insert in mongo
    query.put("priority", "highest");
    items.insert(query);
    System.out.println("Inserted");
      //Cursor, which is like rs in sql
    DBCursor cursor = items.find();
    System.out.println("items got");
    //print highest priority items

    while(cursor.hasNext()){
        System.out.println(cursor.hasNext());
    }
    }
    }
</code>```

The output is:
 it is getting printed continuously as

true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true

I cant figure out what is happening. i want to insert some data into the collection "items"
also if i want to know how to use Mongo in java. I know mysql well but shifting to mongo I cant relate both in queries. What is "query.put" is doing? Any suggestions please?

答:
You have to use:

```<code>System.out.println(cursor.next());
</code>```

rather than

```<code>System.out.println(cursor.hasNext());
</code>```

...

Title: Mongo DB unknown Error?

Body:
I am new to Mongo DB I have to implement it in java. I went through may slides but I am confused what is happening. I executed a small java program using mongo DB but it is not working?

My java code:

    public class MongoDbTesting {

    public void connectingMongo() throws UnknownHostException, MongoException{
    Mongo m = new Mongo("localhost" , 27017); //mongo object
    DB db = m.getDB("todo");
    System.out.println("Connected");
    //making a collection object which is table when compared to sql
    DBCollection items = db.getCollection("items");
    System.out.println("items got");

    //to work with document we need basicDbObject
    BasicDBObject query = new BasicDBObject();
    System.out.println("Created mongoObject");
    //insert in mongo
    query.put("priority", "highest");
    items.insert(query);
    System.out.println("Inserted");
      //Cursor, which is like rs in sql
    DBCursor cursor = items.find();
    System.out.println("items got");
    //print highest priority items

    while(cursor.hasNext()){
        System.out.println(cursor.hasNext());
    }
    }
    }

The output is:
 it is getting printed continuously as

true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true

I cant figure out what is happening. i want to insert some data into the collection "items"
also if i want to know how to use Mongo in java. I know mysql well but shifting to mongo I cant relate both in queries. What is "query.put" is doing? Any suggestions please?

Body:
You have to use:

System.out.println(cursor.next());

rather than

System.out.println(cursor.hasNext());

...


来源: stackexchange

答:
use sum and where

```<code>SELECT SUM(amount)
FROM table_name WHERE Customer_No=2709;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Summing values for each in SQL

Body:
I have a table containing customer ledger entries, where every transaction amount is recorded (including charges and payments). I want to get the balance for each customer in a query probably using the sum function (The sum of the balances gives the balance).

How do i achieve it?

Here is some sample data (I have filtered for only one customer though I have thousands of them).

amount  Customer No.
-14,453.00  2709
-12,000.00  2709
-9,200.00   2709
-8,000.00   2709
-8,000.00   2709
-8,000.00   2709
-8,000.00   2709
-7,998.20   2709
-7,997.20   2709
-5,568.00   2709
-4,300.00   2709
-4,001.80   2709
-4,000.20   2709
-4,000.00   2709
-4,000.00   2709
-4,000.00   2709
-4,000.00   2709
-4,000.00   2709
-4,000.00   2709
-4,000.00   2709
-4,000.00   2709
-3,999.80   2709
-3,998.20   2709
-2,953.00   2709
-2,841.80   2709
-2,596.80   2709
-2,558.20   2709
-2,381.20   2709
-2,101.80   2709
-2,000.00   2709
-1,800.00   2709
-1,771.80   2709
-1,737.00   2709
-1,737.00   2709
-1,737.00   2709
-1,736.80   2709
-1,500.00   2709
-1,368.80   2709
-1,181.20   2709
-870    2709
-870    2709
-870    2709
-870    2709
-870    2709
-870    2709
-870    2709
-870    2709
-870    2709
-851.2  2709
-820    2709
-816.8  2709
-800    2709
-800    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-580    2709
-571.8  2709
-533.2  2709
-370    2709
-368.2  2709
-356.2  2709
-200    2709
-200    2709
-176.8  2709
-131.8  2709
-41.8   2709
-28.2   2709
-23.2   2709
-2.8    2709
-2.8    2709
-1.8    2709
-0.2    2709
1.8 2709
1.8 2709
2.8 2709
23.2    2709
131.8   2709
200 2709
200 2709
200 2709
368.2   2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
580 2709
800 2709
820 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
870 2709
1,160.00    2709
1,500.00    2709
1,737.00    2709
1,737.00    2709
1,737.00    2709
1,737.00    2709
1,737.00    2709
1,737.00    2709
1,800.00    2709
2,000.00    2709
2,101.80    2709
2,953.00    2709
2,953.00    2709
2,953.00    2709
2,953.00    2709
2,953.00    2709
2,953.00    2709
3,375.00    2709
3,375.00    2709
3,998.20    2709
4,000.00    2709
4,000.00    2709
4,000.00    2709
4,000.00    2709
4,000.00    2709
4,000.00    2709
4,000.00    2709
4,300.00    2709
5,568.00    2709
7,868.20    2709
7,976.80    2709
8,000.00    2709
8,000.00    2709
8,000.00    2709
8,000.00    2709
8,000.00    2709
8,000.00    2709
8,000.00    2709
9,200.00    2709
14,450.20   2709

Body:
use sum and where

SELECT SUM(amount)
FROM table_name WHERE Customer_No=2709;


问:
Add values inside the Java while loop and stop it using a sentinel
I want to make a loop where the user inputs multiple values and when they want to stop input their values they input -1. I know it has to use a sentinel but I don't know how.</p>

```<code>Scanner myInput = new Scanner(System.in);
int total = 0;
int count = 0;

while(values >= 0)
{
    int values;
    total += values;
    count ++;

    System.out.println("Please input your value, type - 1 to stop entering values.");
    values = myInput.nextInt();
}

System.out.println ("The sum of all your values is " + total);
</code>```

答:
```<code>public static void main(String[] args) {
    Scanner myInput = new Scanner(System.in);
    System.out.println("Please input your value, type - 1 to stop entering values.");
    int values = 0;
    int total = 0;

    while (values >= 0) {
        total += values;
        values = myInput.nextInt();
    }
    System.out.println("The sum of all your values is " + total);
    myInput.close();
}
</code>```

Out put will be like this:

Body:
I want to make a loop where the user inputs multiple values and when they want to stop input their values they input -1. I know it has to use a sentinel but I don't know how.

Scanner myInput = new Scanner(System.in);
int total = 0;
int count = 0;

while(values >= 0)
{
    int values;
    total += values;
    count ++;

    System.out.println("Please input your value, type - 1 to stop entering values.");
    values = myInput.nextInt();
}

System.out.println ("The sum of all your values is " + total);

Body:
public static void main(String[] args) {
    Scanner myInput = new Scanner(System.in);
    System.out.println("Please input your value, type - 1 to stop entering values.");
    int values = 0;
    int total = 0;

    while (values >= 0) {
        total += values;
        values = myInput.nextInt();
    }
    System.out.println("The sum of all your values is " + total);
    myInput.close();
}

Out put will be like this:


问:
Download multiple CSV files from a list in a single CSV (Python)
I have a 2 column CSV with download links in the first column and company symbols in the second column. For example:

http://data.com/data001.csv, BHP

http://data.com/data001.csv, TSA

I am trying to loop through the list so that Python opens each CSV via the download link and saves it separately as the company name. Therefore each file should be downloaded and saved as follows:

BHP.csv

TSA.csv

Below is the code I am using. It currently exports the entire CSV into a single row tabbed format, then loops back and does it again and again in an infinite loop.

```<code>import pandas as pd

data = pd.read_csv('download_links.csv', names=['download', 'symbol'])
file = pd.DataFrame()
cache = []

for d in data.download:
    df = pd.read_csv(d,index_col=None, header=0)
    cache.append(df)
    file = pd.DataFrame(cache)
    for s in data.symbol:
        file.to_csv(s+'.csv')

print("done")
</code>```

Up until I convert the list 'cache' into the DataFrame 'file' to export it, the data is formatted perfectly. It's only when it gets converted to a DataFrame when the trouble starts.

I'd love some help on this one as I've been stuck on it for a few hours.

答:
Iterate over both fields in parallel:</p>

```<code>for download, symbol in data.itertuples(index=False):
    df = pd.read_csv(d,index_col=None, header=0)
    df.to_csv('{}.csv'.format(symbol))
</code>```

Body:
I have a 2 column CSV with download links in the first column and company symbols in the second column. For example:

http://data.com/data001.csv, BHP

http://data.com/data001.csv, TSA

I am trying to loop through the list so that Python opens each CSV via the download link and saves it separately as the company name. Therefore each file should be downloaded and saved as follows:

BHP.csv

TSA.csv

Below is the code I am using. It currently exports the entire CSV into a single row tabbed format, then loops back and does it again and again in an infinite loop.

import pandas as pd

data = pd.read_csv('download_links.csv', names=['download', 'symbol'])
file = pd.DataFrame()
cache = []

for d in data.download:
    df = pd.read_csv(d,index_col=None, header=0)
    cache.append(df)
    file = pd.DataFrame(cache)
    for s in data.symbol:
        file.to_csv(s+'.csv')

print("done")

Up until I convert the list 'cache' into the DataFrame 'file' to export it, the data is formatted perfectly. It's only when it gets converted to a DataFrame when the trouble starts.

I'd love some help on this one as I've been stuck on it for a few hours.

Body:
Iterate over both fields in parallel:

for download, symbol in data.itertuples(index=False):
    df = pd.read_csv(d,index_col=None, header=0)
    df.to_csv('{}.csv'.format(symbol))


问:
what is the difference between these two piece of json
Before we rewrote the system to use a wcf service the json returned to the client is :

```<code>{"CreationDate":"2016-12-01T13:15:02.923+00:00","Email":"sagysad@dd.com","IsApproved":true,"IsLockedOut":false,"IsOnline":true,"LastActivityDate":"2017-03-31T00:13:21.333+01:00","LastLockoutDate":"1754-01-01T00:00:00+00:00","LastLoginDate":"2017-03-31T00:13:21.113+01:00","LastPasswordChangedDate":"2099-12-31T00:00:00+00:00","ProviderName":"LoginProvider","ProviderUserKey":"dcc5f38f-f71e-4d9d-bdb2-58fb60b7a65e","UserName":"schoi","IsValidLogin":true}
</code>```

but after exposing it as a wcf service the json has changed to this:

```<code>{
    "SignInResult":
    {
        "CreationDate": "/Date(1480598102923+0000)/",
        "Email": "steven.choi@dasdada.com",
        "IsApproved": true,
        "IsLockedOut": false,
        "IsOnline": true,
        "IsValidLogin": true,
        "LastActivityDate": "/Date(1490916050417+0100)/",
        "LastLockoutDate": "/Date(-6816268800000+0000)/",
        "LastLoginDate": "/Date(1490916050417+0100)/",
        "LastPasswordChangedDate": "/Date(-2208988800000+0000)/",
        "ProviderName": "LoginProvider",
        "ProviderUserKey": "dcc5f38f-f71e-4d9d-bdb2-58fb60b7a65e",
        "UserName": "schoi"
    }
}
</code>```

why can't I just do this

```<code>JsonConvert.DeserializeObject<SignInResult>((provider.SignIn(username,password))
</code>```

答:
According to this msdn link, DateTime objects are:

...represented in JSON as "/Date(number of ticks)/". The number of
  ticks is a positive or negative long value that indicates the number
  of ticks (milliseconds) that have elapsed since midnight 01 January,
  1970 UTC.

if you want deserilze it with newsoft you can use this:

```<code>        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
            Formatting = Formatting.Indented
        };
JsonConvert.DeserializeObject<SignInResult>((provider.SignIn(username,password), settings )
</code>```

Body:
Before we rewrote the system to use a wcf service the json returned to the client is :

{"CreationDate":"2016-12-01T13:15:02.923+00:00","Email":"sagysad@dd.com","IsApproved":true,"IsLockedOut":false,"IsOnline":true,"LastActivityDate":"2017-03-31T00:13:21.333+01:00","LastLockoutDate":"1754-01-01T00:00:00+00:00","LastLoginDate":"2017-03-31T00:13:21.113+01:00","LastPasswordChangedDate":"2099-12-31T00:00:00+00:00","ProviderName":"LoginProvider","ProviderUserKey":"dcc5f38f-f71e-4d9d-bdb2-58fb60b7a65e","UserName":"schoi","IsValidLogin":true}

but after exposing it as a wcf service the json has changed to this:

{
    "SignInResult":
    {
        "CreationDate": "/Date(1480598102923+0000)/",
        "Email": "steven.choi@dasdada.com",
        "IsApproved": true,
        "IsLockedOut": false,
        "IsOnline": true,
        "IsValidLogin": true,
        "LastActivityDate": "/Date(1490916050417+0100)/",
        "LastLockoutDate": "/Date(-6816268800000+0000)/",
        "LastLoginDate": "/Date(1490916050417+0100)/",
        "LastPasswordChangedDate": "/Date(-2208988800000+0000)/",
        "ProviderName": "LoginProvider",
        "ProviderUserKey": "dcc5f38f-f71e-4d9d-bdb2-58fb60b7a65e",
        "UserName": "schoi"
    }
}

why can't I just do this

JsonConvert.DeserializeObject<SignInResult>((provider.SignIn(username,password))

Body:
According to this msdn link, DateTime objects are:

...represented in JSON as "/Date(number of ticks)/". The number of
  ticks is a positive or negative long value that indicates the number
  of ticks (milliseconds) that have elapsed since midnight 01 January,
  1970 UTC.

if you want deserilze it with newsoft you can use this:

        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
            Formatting = Formatting.Indented
        };
JsonConvert.DeserializeObject<SignInResult>((provider.SignIn(username,password), settings )


问:
celery_tasktree does not support DAG workflow in general. Is there an alternative?
celery_tasktree (https://pypi.python.org/pypi/celery-tasktree) provides a cleaner workflow canvas compared to celery workflow scheduler (http://docs.celeryproject.org/en/latest/userguide/canvas.html). However, it only support tree-like workflow structure, not a general DAG-like workflow. Celery workflow does have "chords" method but seems cumbersome to use.

Is there any other celery-based library similar to celery_tasktree that works with general DAG workflow?

答:
Here are couple of libraries that support DAG based job schedulers.

https://github.com/thieman/dagobah

https://github.com/apache/incubator-airflow

They are not based on celery. However you can create your own primitives in celery to forward results which can used to build a DAG job schedulers.

```<code>@app.task(bind=True)
def forward(self, result, sig):
    # convert JSON serialized signature back to Signature
    sig = self.app.signature(sig)
    # get the return value of the provided task signature
    result2 = sig()
    # next task will receive tuple of (result_A, result_B)
    return (result, result2)

@app.task
def C(self, Ares_Bres)):
    Ares, Bres = Ares__Bres
    return Ares + Bres

workflow = (A.s() | forward.s(B.s()) | C.s())
</code>```

See here for a more detailed discussion.

Body:
Here are couple of libraries that support DAG based job schedulers.

https://github.com/thieman/dagobah

https://github.com/apache/incubator-airflow

They are not based on celery. However you can create your own primitives in celery to forward results which can used to build a DAG job schedulers.

@app.task(bind=True)
def forward(self, result, sig):
    # convert JSON serialized signature back to Signature
    sig = self.app.signature(sig)
    # get the return value of the provided task signature
    result2 = sig()
    # next task will receive tuple of (result_A, result_B)
    return (result, result2)

@app.task
def C(self, Ares_Bres)):
    Ares, Bres = Ares__Bres
    return Ares + Bres

workflow = (A.s() | forward.s(B.s()) | C.s())

See here for a more detailed discussion.


问:
How to check if user is in a certain table
I have my user table in django, and to differ all the users I created two tables, (Teacher and Student).

Both tables are getting an fk from user

So, in order to make authorization how do I check if one's user is in a certain table.

I need to check it this way

```<code>def test_func(self):
    return self.request.user.check..if..it..exists..in..table
</code>```

My models are like this.

```<code>class Teacher(models.Model):
   User = models.OneToOneField(settings.AUTH_USER_MODEL)
</code>```

答:
If you put in your relation the argument "related_name" you can do it using inverse relationship

```<code>class SomeTable(models.Model):
    user = models.ForeignKey(
        User, #Your user model or Django one
        verbose_name = "User",
        related_name = "inverse_relation_name"
    )
</code>```

Then you have to call using keyword arguments for the filters:

```<code>SomeTable.inverse_relation_name.filter(id=self.request.user.id) #You will get a queryset
</code>```

Or

```<code>SomeTable.inverse_relation_name.get(id=self.request.user.id) # You will get the object or a exception
</code>```

Body:
I have my user table in django, and to differ all the users I created two tables, (Teacher and Student).

Both tables are getting an fk from user

So, in order to make authorization how do I check if one's user is in a certain table.

I need to check it this way

def test_func(self):
    return self.request.user.check..if..it..exists..in..table

My models are like this.

class Teacher(models.Model):
   User = models.OneToOneField(settings.AUTH_USER_MODEL)

Body:
If you put in your relation the argument "related_name" you can do it using inverse relationship

class SomeTable(models.Model):
    user = models.ForeignKey(
        User, #Your user model or Django one
        verbose_name = "User",
        related_name = "inverse_relation_name"
    )

Then you have to call using keyword arguments for the filters:

SomeTable.inverse_relation_name.filter(id=self.request.user.id) #You will get a queryset

Or

SomeTable.inverse_relation_name.get(id=self.request.user.id) # You will get the object or a exception


问:
Scrolling recyclerview in fragment causes view to be pushed up

When I tried to scroll inside my recyclerview fragment, the entire view got pushed up.

Fragment Code

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />

</RelativeLayout>
</code>```

List Layout Code

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content" android:focusable="true"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:clickable="true"
    android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:text="Title"
        android:textColor="#000000"
        android:textSize="16dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Location"
        android:layout_below="@+id/title"
        android:layout_alignParentStart="true" />

    <TextView
        android:id="@+id/date"
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_height="wrap_content"
        android:text="Date"
        />
</RelativeLayout>
</code>```

Toolbar Code

```<code> <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay">

        </android.support.v7.widget.Toolbar>
</code>```

I've tried changing the fragment to wrap_content instead of match_parent and when I tried scrolling at the content area, the same problems occurs where the view will get pushed up

答:
Your toolbar scrollflags need to be changed like below,

```<code> app:layout_scrollFlags="scroll|exitUntilCollapsed"
</code>```

instead of exitUntilCollapsed you can try some other properties also

1)enterAlways
2)enterAlwaysCollapsed

and your recyclerview parent RelativeLayout should have following properties.

```<code>app:layout_behavior="@string/appbar_scrolling_view_behavior"
</code>```

Body:
When I tried to scroll inside my recyclerview fragment, the entire view got pushed up.

Fragment Code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />

</RelativeLayout>

List Layout Code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content" android:focusable="true"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:clickable="true"
    android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:text="Title"
        android:textColor="#000000"
        android:textSize="16dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Location"
        android:layout_below="@+id/title"
        android:layout_alignParentStart="true" />

    <TextView
        android:id="@+id/date"
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_height="wrap_content"
        android:text="Date"
        />
</RelativeLayout>

Toolbar Code

 <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay">

        </android.support.v7.widget.Toolbar>

I've tried changing the fragment to wrap_content instead of match_parent and when I tried scrolling at the content area, the same problems occurs where the view will get pushed up

Body:
Your toolbar scrollflags need to be changed like below,

 app:layout_scrollFlags="scroll|exitUntilCollapsed"

instead of exitUntilCollapsed you can try some other properties also

1)enterAlways
2)enterAlwaysCollapsed

and your recyclerview parent RelativeLayout should have following properties.

app:layout_behavior="@string/appbar_scrolling_view_behavior"


问:
How to get the JPA generated SQL query?
I use JPA specification and Hibernate as my vendor. I need somehow to take the generated SQL Query which is sent to the the DB (printed to the sysout) and save it as a simple string.

Is there a way to do this?

EDIT

Let me make it a beat clearer: I don't need hibernate log. I need to be able to execute the same query on a different DB. Therefore, I need to get the SQL query as is, and hold it in a normal String variable.

Edit 2

Is there a util which I can provide it a bean and it will automatically generate an Insert query? can I somehow use Hibernate beans here? I know it's a beat complex.

Thanks,

Idob

答:
Try to add properties in instance of LocalContainerEntityManagerFactoryBean ,Its working for me :-</p>

```<code>@EnableJpaRepositories(basePackages = "org.common.persistence.dao")
public class PersistenceJPAConfig {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[] { "org.common.persistence.model" });
        final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());
        return em;
    }

    final Properties additionalProperties() {
        final Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("showSql", "true");
        hibernateProperties.setProperty("hibernate.show_sql", "true");
        hibernateProperties.setProperty("hibernate.format_sql", "true");
        hibernateProperties.setProperty("hibernate.query.substitutions", "false");
        return hibernateProperties;
    }
}
</code>```

Title: How to get the JPA generated SQL query?

Body:
Try to add properties in instance of LocalContainerEntityManagerFactoryBean ,Its working for me :-

@EnableJpaRepositories(basePackages = "org.common.persistence.dao")
public class PersistenceJPAConfig {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[] { "org.common.persistence.model" });
        final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());
        return em;
    }

    final Properties additionalProperties() {
        final Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("showSql", "true");
        hibernateProperties.setProperty("hibernate.show_sql", "true");
        hibernateProperties.setProperty("hibernate.format_sql", "true");
        hibernateProperties.setProperty("hibernate.query.substitutions", "false");
        return hibernateProperties;
    }
}


问:
Dynamics CRM - C# Plug-in for specific view
I've written a plugin in C# that runs when a specific view "My activities" for example is called. How can I specify my plugin ONLY to run when this view is called and not when "Closed activities", "All activities", etc. are?

And will the plugin I'm writing still work when Dynamics will be updated or in 1 year or 2?

答:
Just piggybacking off Henk's answer, you don't want to limit your plugin to run only when a specific view is requested anyway. If this column is always "empty" in the database, you really just want to inspect the ColumnSet of the submitted QueryExpression & do your manipulation any time the "calculated" column is requested.
Once you get the ColumnSet from the query:

```<code>Query q = context.InputParameters.TryGetValue("Query") as QueryExpression; // could also be QueryByAttribute or FetchExpression,
if (q != null)
{
   ColumnSet cols = q.ColumnSet;
   if (cols.AllColumns == true || cols.Columns.Contains("regarding_object_type"))
   {
       executionContext.OutputParameters["BusinessEntityCollection"] = GetResultValuesInWhateverWayYouAreGoingTo();
   }
}
</code>```

https://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.query.queryexpression.columnset.aspx

Body:
Just piggybacking off Henk's answer, you don't want to limit your plugin to run only when a specific view is requested anyway. If this column is always "empty" in the database, you really just want to inspect the ColumnSet of the submitted QueryExpression & do your manipulation any time the "calculated" column is requested.
Once you get the ColumnSet from the query:

Query q = context.InputParameters.TryGetValue("Query") as QueryExpression; // could also be QueryByAttribute or FetchExpression,
if (q != null)
{
   ColumnSet cols = q.ColumnSet;
   if (cols.AllColumns == true || cols.Columns.Contains("regarding_object_type"))
   {
       executionContext.OutputParameters["BusinessEntityCollection"] = GetResultValuesInWhateverWayYouAreGoingTo();
   }
}

https://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.query.queryexpression.columnset.aspx


问:
How to use Scala's this typing, abstract types, etc. to implement a Self type?
I couldn't find the answer to this in any other question. Suppose that I have an abstract superclass Abstract0 with two subclasses, Concrete1 and Concrete1. I want to be able to define in Abstract0 something like

```<code>def setOption(...): Self = {...}
</code>```

where Self would be the concrete subtype. This would allow chaining calls to setOption like this:

```<code>val obj = new Concrete1.setOption(...).setOption(...)
</code>```

and still get Concrete1 as the inferred type of obj.

What I don't want is to define this:

```<code>abstract class Abstract0[T <: Abstract0[T]]
</code>```

because it makes it harder for clients to handle this type. I tried various possibilities including an abstract type:

```<code>abstract class Abstract0 {
  type Self <: Abstract0
}

class Concrete1 extends Abstract0 {
  type Self = Concrete1
}
</code>```

but then it is impossible to implement setOption, because this in Abstract0 does not have type Self. And using this: Self => also doesn't work in Abstract0.

What solutions are there to this issue?

答:
This is what this.type is for:

```<code>scala> abstract class Abstract0 {
     |   def setOption(j: Int): this.type
     | }
defined class Abstract0

scala> class Concrete0 extends Abstract0 {
     |   var i: Int = 0
     |   def setOption(j: Int) = {i = j; this}
     | }
defined class Concrete0

scala> (new Concrete0).setOption(1).setOption(1)
res72: Concrete0 = Concrete0@a50ea1
</code>```

As you can see setOption returns the actual type used, not Abstract0. If Concrete0 had setOtherOption then (new Concrete0).setOption(1).setOtherOption(...) would work

UPDATE: To answer JPP's followup question in the comment (how to return new instances:
The general approach described in the question is the right one (using abstract types). However, the creation of the new instances needs to be explicit for each subclass.

One approach is:

```<code>abstract class Abstract0 {
  type Self <: Abstract0

  var i = 0

  def copy(i: Int) : Self

  def setOption(j: Int): Self = copy(j)
}

class Concrete0(i: Int) extends Abstract0 {
  type Self = Concrete0
  def copy(i: Int) = new Concrete0(i)
}
</code>```

Another one is to follow the builder pattern used in Scala's collection library. That is, setOption receives an implicit builder parameter. This has the advantages that building the new instance can be done with more methods than just 'copy' and that complex builds can be done. E.g. a setSpecialOption can specify that the return instance must be SpecialConcrete.

Here's an illustration of the solution:

```<code>trait Abstract0Builder[To] {
    def setOption(j: Int)
    def result: To
}

trait CanBuildAbstract0[From, To] {
  def apply(from: From): Abstract0Builder[To]
}

abstract class Abstract0 {
  type Self <: Abstract0

  def self = this.asInstanceOf[Self]

  def setOption[To <: Abstract0](j: Int)(implicit cbf: CanBuildAbstract0[Self, To]): To = {
    val builder = cbf(self)
    builder.setOption(j)
    builder.result
  }

}

class Concrete0(i: Int) extends Abstract0 {
  type Self = Concrete0
}

object Concrete0 {
    implicit def cbf = new CanBuildAbstract0[Concrete0, Concrete0] {
        def apply(from: Concrete0) = new Abstract0Builder[Concrete0] {
           var i = 0
           def setOption(j: Int) = i = j
           def result = new Concrete0(i)
        }
    }
}

object Main {
    def main(args: Array[String]) {
    val c = new Concrete0(0).setOption(1)
    println("c is " + c.getClass)
    }
}
</code>```

UPDATE 2:
Replying to JPP's second comment. In case of several levels of nesting, use a type parameter instead of type member and make Abstract0 into a trait:

```<code>trait Abstract0[+Self <: Abstract0[_]] {
  // ...
}

class Concrete0 extends Abstract0[Concrete0] {
  // ....
}

class RefinedConcrete0 extends Concrete0 with Abstract0[RefinedConcrete0] {
 // ....
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I couldn't find the answer to this in any other question. Suppose that I have an abstract superclass Abstract0 with two subclasses, Concrete1 and Concrete1. I want to be able to define in Abstract0 something like

def setOption(...): Self = {...}

where Self would be the concrete subtype. This would allow chaining calls to setOption like this:

val obj = new Concrete1.setOption(...).setOption(...)

and still get Concrete1 as the inferred type of obj.

What I don't want is to define this:

abstract class Abstract0[T <: Abstract0[T]]

because it makes it harder for clients to handle this type. I tried various possibilities including an abstract type:

abstract class Abstract0 {
  type Self <: Abstract0
}

class Concrete1 extends Abstract0 {
  type Self = Concrete1
}

but then it is impossible to implement setOption, because this in Abstract0 does not have type Self. And using this: Self => also doesn't work in Abstract0.

What solutions are there to this issue?

Body:
This is what this.type is for:

scala> abstract class Abstract0 {
     |   def setOption(j: Int): this.type
     | }
defined class Abstract0

scala> class Concrete0 extends Abstract0 {
     |   var i: Int = 0
     |   def setOption(j: Int) = {i = j; this}
     | }
defined class Concrete0

scala> (new Concrete0).setOption(1).setOption(1)
res72: Concrete0 = Concrete0@a50ea1

As you can see setOption returns the actual type used, not Abstract0. If Concrete0 had setOtherOption then (new Concrete0).setOption(1).setOtherOption(...) would work

UPDATE: To answer JPP's followup question in the comment (how to return new instances:
The general approach described in the question is the right one (using abstract types). However, the creation of the new instances needs to be explicit for each subclass.

One approach is:

abstract class Abstract0 {
  type Self <: Abstract0

  var i = 0

  def copy(i: Int) : Self

  def setOption(j: Int): Self = copy(j)
}

class Concrete0(i: Int) extends Abstract0 {
  type Self = Concrete0
  def copy(i: Int) = new Concrete0(i)
}

Another one is to follow the builder pattern used in Scala's collection library. That is, setOption receives an implicit builder parameter. This has the advantages that building the new instance can be done with more methods than just 'copy' and that complex builds can be done. E.g. a setSpecialOption can specify that the return instance must be SpecialConcrete.

Here's an illustration of the solution:

trait Abstract0Builder[To] {
    def setOption(j: Int)
    def result: To
}

trait CanBuildAbstract0[From, To] {
  def apply(from: From): Abstract0Builder[To]
}

abstract class Abstract0 {
  type Self <: Abstract0

  def self = this.asInstanceOf[Self]

  def setOption[To <: Abstract0](j: Int)(implicit cbf: CanBuildAbstract0[Self, To]): To = {
    val builder = cbf(self)
    builder.setOption(j)
    builder.result
  }

}

class Concrete0(i: Int) extends Abstract0 {
  type Self = Concrete0
}

object Concrete0 {
    implicit def cbf = new CanBuildAbstract0[Concrete0, Concrete0] {
        def apply(from: Concrete0) = new Abstract0Builder[Concrete0] {
           var i = 0
           def setOption(j: Int) = i = j
           def result = new Concrete0(i)
        }
    }
}

object Main {
    def main(args: Array[String]) {
    val c = new Concrete0(0).setOption(1)
    println("c is " + c.getClass)
    }
}

UPDATE 2:
Replying to JPP's second comment. In case of several levels of nesting, use a type parameter instead of type member and make Abstract0 into a trait:

trait Abstract0[+Self <: Abstract0[_]] {
  // ...
}

class Concrete0 extends Abstract0[Concrete0] {
  // ....
}

class RefinedConcrete0 extends Concrete0 with Abstract0[RefinedConcrete0] {
 // ....
}


问:
Is it possible to force a scale on geom_raster()?
I am trying to compare three plots using geom_raster(). The problem is that I would like to maintain the same scale in all three plots that was set in the first plot [-3,3].

Here is my code:

```<code>#raster plots
box <- .05
df <- expand.grid(x1 = seq(-1, 1, box), x2 = seq(-1, 1, box))
df$risk <- df$x1 + 2*df$x2

p1 <- ggplot(df, aes(x1, x2, fill = risk)) + geom_raster() +
  scale_fill_gradientn(colours=c("#FFFFFF","#046380","#000000")) +
  theme_minimal() +
  ggtitle("True Risk")

df <- expand.grid(x1 = seq(-1, 1, box), x2 = seq(-1, 1, box))
df$risk <- .99*df$x1 + 1.98*df$x2

p2 <- ggplot(df, aes(x1, x2, fill = risk)) + geom_raster() +
  scale_fill_gradientn(colours=c("#FFFFFF","#046380","#000000")) +
  theme_minimal() +
  ggtitle("Estimated Risk")

df <- expand.grid(x1 = seq(-1, 1, box), x2 = seq(-1, 1, box))
df$risk <- .01*df$x1 + .02*df$x2
p3 <- ggplot(df, aes(x1, x2, fill = risk)) + geom_raster() +
  scale_fill_gradientn(colours=c("#FFFFFF","#046380","#000000")) +
  theme_minimal() +
  ggtitle("Difference")

library(gridExtra)
grid.arrange(p1, p2, p3, ncol=1)
</code>```

This is my output

It is hard to see that the difference is minimal because the scale changes to [0.03, -0.03]. How can I show the correct surface, but on the original scale?

答:
You can keep all the three variables in one data.frame and use facet_grid or facet_wrap to maintain the scale.

```<code>library(ggplot2)
library(reshape2)
box <- .05
df <- expand.grid(x1 = seq(-1, 1, box), x2 = seq(-1, 1, box))
# Calculate each field
df$TrueRisk <- df$x1 + 2*df$x2
df$EstimatedRisk <- .99*df$x1 + 1.98*df$x2
df$Difference <- .01*df$x1 + .02*df$x2

# Transform the data into long format for ggplot2
df <- melt(df, c("x1", "x2"))

# Use facet_grid/facet_wrap to create the plot
ggplot(df, aes(x1, x2, fill = value)) + geom_raster() +
  facet_grid(variable ~ .) +
  scale_fill_gradientn(colours=c("#FFFFFF","#046380","#000000")) +
  theme_minimal() +
  ggtitle("Risk")
</code>```

Body:
I am trying to compare three plots using geom_raster(). The problem is that I would like to maintain the same scale in all three plots that was set in the first plot [-3,3].

Here is my code:

#raster plots
box <- .05
df <- expand.grid(x1 = seq(-1, 1, box), x2 = seq(-1, 1, box))
df$risk <- df$x1 + 2*df$x2

p1 <- ggplot(df, aes(x1, x2, fill = risk)) + geom_raster() +
  scale_fill_gradientn(colours=c("#FFFFFF","#046380","#000000")) +
  theme_minimal() +
  ggtitle("True Risk")

df <- expand.grid(x1 = seq(-1, 1, box), x2 = seq(-1, 1, box))
df$risk <- .99*df$x1 + 1.98*df$x2

p2 <- ggplot(df, aes(x1, x2, fill = risk)) + geom_raster() +
  scale_fill_gradientn(colours=c("#FFFFFF","#046380","#000000")) +
  theme_minimal() +
  ggtitle("Estimated Risk")

df <- expand.grid(x1 = seq(-1, 1, box), x2 = seq(-1, 1, box))
df$risk <- .01*df$x1 + .02*df$x2
p3 <- ggplot(df, aes(x1, x2, fill = risk)) + geom_raster() +
  scale_fill_gradientn(colours=c("#FFFFFF","#046380","#000000")) +
  theme_minimal() +
  ggtitle("Difference")

library(gridExtra)
grid.arrange(p1, p2, p3, ncol=1)

This is my output

It is hard to see that the difference is minimal because the scale changes to [0.03, -0.03]. How can I show the correct surface, but on the original scale?

Body:
You can keep all the three variables in one data.frame and use facet_grid or facet_wrap to maintain the scale.

library(ggplot2)
library(reshape2)
box <- .05
df <- expand.grid(x1 = seq(-1, 1, box), x2 = seq(-1, 1, box))
# Calculate each field
df$TrueRisk <- df$x1 + 2*df$x2
df$EstimatedRisk <- .99*df$x1 + 1.98*df$x2
df$Difference <- .01*df$x1 + .02*df$x2

# Transform the data into long format for ggplot2
df <- melt(df, c("x1", "x2"))

# Use facet_grid/facet_wrap to create the plot
ggplot(df, aes(x1, x2, fill = value)) + geom_raster() +
  facet_grid(variable ~ .) +
  scale_fill_gradientn(colours=c("#FFFFFF","#046380","#000000")) +
  theme_minimal() +
  ggtitle("Risk")


问:
using pthread in C?
I am trying to write a program that will continuously take reading from a sensor that will monitor water level. Then after every (10-15 mins) it will need to take soil moisture readings from other sensors. I have never used POSIX pthreads before.  This is what I have so far as a concept of how it may work.

It seems to be working the way I want it to, but is it a correct way to implement this. Is there anything else I need to do?

```<code>void *soilMoisture(void *vargp)
{
 sleep(10);
 funct();
 return NULL;
}

int main()
{
 pthread_t pt;
 int k=1;
 pthread_create(&pt, NULL, soilMoisture, NULL);
 while(k>0)
 {
   printf("This is the main thread (Measuring the water level) : %d\n", k);
   sleep(1);
 }
 return 0;
}

void funct()
{
 printf("******(Measuring soil moisture after sleeping for   10SEC)***********\n");
 pthread_t ptk;
 pthread_create(&ptk, NULL, soilMoisture, NULL);
}
</code>```

答:
It is not clear why you create a new thread every 10 seconds rather than just letting the original continue.  Since the original thread exits, you aren't directly accumulating threads, but you aren't waiting for any of them, so there are some resources unreleased.  You also aren't error checking, so you won't know when anything does go wrong; monitoring will simply stop.

You will eventually run out of space, one way or another.  You have a couple of options.

Don't create a new thread every 10 seconds.  Leave the thread running by making a loop in the soilMoisture() function and do away with funct() — or at least the pthread_create() call in it.

If you must create new threads, make them detached.  You'll need to create a non-default pthread_attr_t using the functions outlined and linked to in When pthread_attr_t is not NULL.

There are a myriad issues you've not yet dealt with, notably synchronization between the two threads.  If you don't have any such synchronization, you'd be better off with two separate programs — the Unix mantra of "each program does one job but does it well" still applies.  You'd have one program to do the soil moisture reading, and the other to do the water level reading.  You'll need to decide whether data is stored in a database or otherwise logged, and for how log such data is kept.  You'll need to think about rotating logs.  What should happen if sensors go off-line?  How can you restart threads or processes?  How can you detect when threads or processes lock up unexpectedly or exit unexpectedly?  Etc.

I assume the discrepancy between 10-15 minutes mentioned in the question and 10 seconds in the code is strictly for practical testing rather than a misunderstanding of the POSIX sleep() function.

Title: using pthread in C?

Body:
I am trying to write a program that will continuously take reading from a sensor that will monitor water level. Then after every (10-15 mins) it will need to take soil moisture readings from other sensors. I have never used POSIX pthreads before.  This is what I have so far as a concept of how it may work.

It seems to be working the way I want it to, but is it a correct way to implement this. Is there anything else I need to do?

void *soilMoisture(void *vargp)
{
 sleep(10);
 funct();
 return NULL;
}

int main()
{
 pthread_t pt;
 int k=1;
 pthread_create(&pt, NULL, soilMoisture, NULL);
 while(k>0)
 {
   printf("This is the main thread (Measuring the water level) : %d\n", k);
   sleep(1);
 }
 return 0;
}

void funct()
{
 printf("******(Measuring soil moisture after sleeping for   10SEC)***********\n");
 pthread_t ptk;
 pthread_create(&ptk, NULL, soilMoisture, NULL);
}


问:
AWK - error in script with count variable OR error in AWK Implementation / version?

Awk version: GNU Awk 3.1.1

Platform: OpenVMS 8.4-L1

Awk knowledge: limited

Script (Awk one liner).
NOTE: OpenVMS parameter parsing requires quotes

```<code>gawk "-F" ";" "BEGIN {x = 0} ; x++ {print $0,$1"";""x}" in.file > out.file

**in.file**
file.log;2000
file.log;1999
file.log;1998
file.log;1997

**out.file**
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4
</code>```

I wanted the following instead

```<code>file.log;2000 file.log;1
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4
</code>```

If I change the awk command above to: ...{x = -1}... I get

```<code>**out.file**
file.log;2000 file.log;0
file.log;1998 file.log;2
file.log;1997 file.log;3
</code>```

What I am wondering is

Can someone else using a different platform test this to see if it produces the same output?

Could it be the awk version I am running that is at fault OR is there something wrong with my awk script that I am not understanding

It really seems to me that it should produce a file.log;1999 file.log;1 line but it doesn't. I'm at a loss and need some pointers / awk education

Thanks in advance :-)

答: "";"" is the problem. Try.  'BEGIN ... $1";"x ... instead. What you posted amounts to.   print $0,$1; x} I.e. throw x awayt. Hth</p>

Body:
Awk version: GNU Awk 3.1.1

Platform: OpenVMS 8.4-L1

Awk knowledge: limited

Script (Awk one liner).
NOTE: OpenVMS parameter parsing requires quotes

gawk "-F" ";" "BEGIN {x = 0} ; x++ {print $0,$1"";""x}" in.file > out.file

**in.file**
file.log;2000
file.log;1999
file.log;1998
file.log;1997

**out.file**
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4

I wanted the following instead

file.log;2000 file.log;1
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4

If I change the awk command above to: ...{x = -1}... I get

**out.file**
file.log;2000 file.log;0
file.log;1998 file.log;2
file.log;1997 file.log;3

What I am wondering is

Can someone else using a different platform test this to see if it produces the same output?

Could it be the awk version I am running that is at fault OR is there something wrong with my awk script that I am not understanding

It really seems to me that it should produce a file.log;1999 file.log;1 line but it doesn't. I'm at a loss and need some pointers / awk education

Thanks in advance :-)


问:
Facing issue with parallel test execution in TestNG when using @DataProvider with TestNG XML
I've written a TestNG class which contains two methods (one@DataProvider, one @Test)

```<code>public class BaseTestNG extends BaseTest{
    @DataProvider(name="Demo", parallel=true)
    public Object[][] getData() {
        Object[][] data = new Object[4][2];
        data[0][0] = "sampleuser1";
        data[0][1] = "abcdef";
        data[1][0] = "testuser2";
        data[1][1] = "zxcvb";
        data[2][0] = "guestuser3";
        data[2][1] = "pass123";
        data[3][0] = "guestuser4";
        data[3][1] = "pass123";
        return data;
    }
    @Test(dataProvider="Demo")
    public void BaseTestNG(String username, String password)  {
        System.out.println(username + " :: " & password)
        Thread.currentThread.Sleep(5000);
    }
}
</code>```

In testng.xml I've set parameter thread-count to "2". But when I run the testng.xml as a TestNGSuite, 4 instances of @Test are getting launched simultaneously instead of 2 threads.

How can I restrict only to number of thread-count mentioned in testing.xml and not on the amount of TestData passed from @DataProvider?

答:
TestNG has two attributes in the TestNG suite xml file that lets you control threadpool size.

thread-count - This lets you control the number of threads when you enable parallelism (tests|classes|methods). This if not specified has a default value of 5

data-provider-thread-count - This lets you control the number of threads when a data provider is involved. This if not specified has a default value of 10

To fix your problem you can consider setting data-provider-thread-count attribute in your testng-suite.xml file to 2. After that TestNG should spawn only two threads.

Please note: You would need to create a suite xml file which includes your test class. Only then this will work.

Please refer here for more details on the TestNG DTD.

Body:
I've written a TestNG class which contains two methods (one@DataProvider, one @Test)

public class BaseTestNG extends BaseTest{
    @DataProvider(name="Demo", parallel=true)
    public Object[][] getData() {
        Object[][] data = new Object[4][2];
        data[0][0] = "sampleuser1";
        data[0][1] = "abcdef";
        data[1][0] = "testuser2";
        data[1][1] = "zxcvb";
        data[2][0] = "guestuser3";
        data[2][1] = "pass123";
        data[3][0] = "guestuser4";
        data[3][1] = "pass123";
        return data;
    }
    @Test(dataProvider="Demo")
    public void BaseTestNG(String username, String password)  {
        System.out.println(username + " :: " & password)
        Thread.currentThread.Sleep(5000);
    }
}

In testng.xml I've set parameter thread-count to "2". But when I run the testng.xml as a TestNGSuite, 4 instances of @Test are getting launched simultaneously instead of 2 threads.

How can I restrict only to number of thread-count mentioned in testing.xml and not on the amount of TestData passed from @DataProvider?


问:
MySQL CONCAT add comma after
I am struggling to get comma after value but this query is adding before value

```<code>ipaddress = CONCAT(IFNULL(ipaddress,''), ',$ipaddress')
</code>```

The field's default value is NULL

Even I have tried this too but result is the same. Adding comma before not after.

```<code>ipaddress = CONCAT(IFNULL(ipaddress,''), ',', '$ipaddress')
</code>```

答:
If ipaddress is NOT NULL then the string is formatted correctly.

```<code>E.g. 127.0.0.1,127.0.0.2
</code>```

In case where ipaddress IS NULL, the string will look like

```<code>,127.0.0.2
</code>```

You can use MySQL's TRIM function to fix this.

```<code> TRIM(LEADING ',' FROM CONCAT(IFNULL(ipaddress,''), ',', '$ipaddress'))
 TRIM(LEADING ',' FROM CONCAT(IFNULL(NULL,''), ',', '127.0.0.2'))
</code>```

Hope this helps!

Title: MySQL CONCAT add comma after

Body:
I am struggling to get comma after value but this query is adding before value

ipaddress = CONCAT(IFNULL(ipaddress,''), ',$ipaddress')

The field's default value is NULL

Even I have tried this too but result is the same. Adding comma before not after.

ipaddress = CONCAT(IFNULL(ipaddress,''), ',', '$ipaddress')

Body:
If ipaddress is NOT NULL then the string is formatted correctly.

E.g. 127.0.0.1,127.0.0.2

In case where ipaddress IS NULL, the string will look like

,127.0.0.2

You can use MySQL's TRIM function to fix this.

 TRIM(LEADING ',' FROM CONCAT(IFNULL(ipaddress,''), ',', '$ipaddress'))
 TRIM(LEADING ',' FROM CONCAT(IFNULL(NULL,''), ',', '127.0.0.2'))

Hope this helps!


问:
PHP: object is NULL right after creation
We have very strange errors occasionally popping up in our php logs: Trying to get property of non-object.

This exact error seems to be caused by the access to the member $shortName in the following if statement:

```<code>class MyLocaleWrapper extends SomeOtherClass {
    …
    protected static $system = NULL;
    public static function getSystemLocale() {
        if (self::$system === NULL) {
            self::$system = new self();
            debug(self::$system);
            self::$system->rfcName = SYSTEM_LOCALE_RFCNAME;
            self::$system->shortName = strtolower(Locale::getRegion(self::$system->rfcName));
            if (self::$system->shortName == '') {
                self::$system->shortName = strtolower(self::$system->rfcName);
            }
            …

# in another file:
class SomeOtherClass {
    …
    public function __construct() {
        # Some documentation about features that have been
        # removed from the constructor, but no real code in here.
        return NULL;
    }
    …

# in yet another file:
MyLocaleWrapper::getSystemLocale();
</code>```

if I dump self::$system into a log file, I see that it is NULL - right after being constructed with the keyword new.

The most interesting part is that this file is included in each and every request to our page, so it gets executed ~ 10 times per second. But occasionally it just fails without anyone touching the code (or even the server).

Has anyone else ever experienced such behavior in PHP?

答:
This will print the object once</p>

```<code>class MyLocaleWrapper extends SomeOtherClass {

    protected static $system = NULL;
    public static function getSystemLocale() {
        if (self::$system === NULL) {
            self::$system = new MyLocaleWrapper();

            self::$system->rfcName = 'test';
            self::$system->shortName = strtolower('test');
            if (self::$system->shortName == '') {
                self::$system->shortName = strtolower('test');
            }
                print_r(self::$system);

        }
        return self::$system;
    }
}

# in another file:
class SomeOtherClass {

    public function __construct() {
        # Some documentation about features that have been
        # removed from the constructor, but no real code in here.
        return NULL;
    }
}

# in yet another file:
$l = MyLocaleWrapper::getSystemLocale();
$l = MyLocaleWrapper::getSystemLocale();
</code>```

Body:
We have very strange errors occasionally popping up in our php logs: Trying to get property of non-object.

This exact error seems to be caused by the access to the member $shortName in the following if statement:

class MyLocaleWrapper extends SomeOtherClass {
    …
    protected static $system = NULL;
    public static function getSystemLocale() {
        if (self::$system === NULL) {
            self::$system = new self();
            debug(self::$system);
            self::$system->rfcName = SYSTEM_LOCALE_RFCNAME;
            self::$system->shortName = strtolower(Locale::getRegion(self::$system->rfcName));
            if (self::$system->shortName == '') {
                self::$system->shortName = strtolower(self::$system->rfcName);
            }
            …

# in another file:
class SomeOtherClass {
    …
    public function __construct() {
        # Some documentation about features that have been
        # removed from the constructor, but no real code in here.
        return NULL;
    }
    …

# in yet another file:
MyLocaleWrapper::getSystemLocale();

if I dump self::$system into a log file, I see that it is NULL - right after being constructed with the keyword new.

The most interesting part is that this file is included in each and every request to our page, so it gets executed ~ 10 times per second. But occasionally it just fails without anyone touching the code (or even the server).

Has anyone else ever experienced such behavior in PHP?

Body:
This will print the object once

class MyLocaleWrapper extends SomeOtherClass {

    protected static $system = NULL;
    public static function getSystemLocale() {
        if (self::$system === NULL) {
            self::$system = new MyLocaleWrapper();

            self::$system->rfcName = 'test';
            self::$system->shortName = strtolower('test');
            if (self::$system->shortName == '') {
                self::$system->shortName = strtolower('test');
            }
                print_r(self::$system);

        }
        return self::$system;
    }
}

# in another file:
class SomeOtherClass {

    public function __construct() {
        # Some documentation about features that have been
        # removed from the constructor, but no real code in here.
        return NULL;
    }
}

# in yet another file:
$l = MyLocaleWrapper::getSystemLocale();
$l = MyLocaleWrapper::getSystemLocale();


问:
Ubuntu Failed to start RabbitMQ broker
Im having a hard time trying to install RabbitMQ . Ive tried debian through webmin, done a sudo apt-get, tried sudo wget url then sudo dpkg -i . All attempts have failed with an Failed to start RabbitMQ broker.</p>

答:
Without looking into the server itself, providing a solution for your type of issue is extremely difficult, but since your objective is installing rabbitmq on server and if you're open to docker I suggest using the pre built docker that is provided by rabbitmq, which takes the implementation process a lot easier, faster, hassle free and makes restarts extremely easy.

First install docker in your server then do as the following link instructs.

https://hub.docker.com/_/rabbitmq/

If this does not suit you I suggest using the following link to uninstall everything rabbitmq related and go with a fresh installation

https://www.howtoinstall.co/en/ubuntu/trusty/rabbitmq-server?action=remove

Title: Ubuntu Failed to start RabbitMQ broker


问:
Implementation approach for forgot password in Angular2
I have a main application that sits within authorised login. All routes are sitting within a Route Guard. I now need to implement a forgot password component that should sit outside of the login. I have 2 requirements.

The forgot password page should have the url http://

It should be excluded from the route guard checks.

What would be the best approach to implement this?

答:
The router checks whether the path you wish to navigate to matches the URL you are going to in the order in which they are listed in your array of routes, so you can simply put the forgotPassword page at the top of your routes, then put a path: '' that will match every other url below that.

```<code>export const routes: Routes = [
{
    path: 'forgotPassword',
    component: ForgotPasswordComponent
},
{
    path: '', canActivate: [AuthGuard], children: [
        // All other components
    ]
}
];
</code>```

Body:
The router checks whether the path you wish to navigate to matches the URL you are going to in the order in which they are listed in your array of routes, so you can simply put the forgotPassword page at the top of your routes, then put a path: '' that will match every other url below that.

export const routes: Routes = [
{
    path: 'forgotPassword',
    component: ForgotPasswordComponent
},
{
    path: '', canActivate: [AuthGuard], children: [
        // All other components
    ]
}
];


问:
Wrapping a series of sibling elements
Using ruby/nokogiri I would like to wrap some elements starting at one element and ending before the next one of those elements. So lets say I have:

```<code><div class="foo"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="foo"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="bar"></div>
<div class="bar"></div>
</code>```

And I want to wrap all foos and their contiguous bars (if there are any) in a baz class that closes before the next foo (last one obvs doesn't have another foo), like this:

```<code><div class="baz">
    <div class="foo"></div>
    <div class="bar"></div>
    <div class="bar"></div>
</div>
<div class="baz">
    <div class="foo"></div>
    <div class="bar"></div>
    <div class="bar"></div>
    <div class="bar"></div>
    <div class="bar"></div>
</div>
<div class="baz">
    <div class="foo"></div>
</div>
<div class="baz">
    <div class="foo"></div>
    <div class="bar"></div>
    <div class="bar"></div>
</div>
</code>```

Thanks.

Edit: I found this that asks a similar question but I'm struggling to adapt it XPath axis, get all following nodes until

Edit 2:This will return the bars after the foo but not the foo:

```<code>body.xpath("(//div[@class='foo'])[1]/following-sibling::div[@class='bar']
    [1 = count(preceding-sibling::div[@class='foo'][1] | (//div[@class='foo'])[1])]")
</code>```

Need to figure out how to include the foo!

Edit 3: Welp this will add the foo:

```<code>body.xpath("//div[@class='foo'][1]","//div[@class='foo']
    [1]/following-sibling::div[@class='bar']
    [1 = count(preceding-sibling::div[@class='foo'][1] | (//div[@class='foo'])[1])]")
</code>```

But the bigger problem is I'm not sure how to iterate this? It just returns the first set of foo + bars.

Edit 4: Iterating through the foo-bar chunks:

```<code>var = 1
loop do
  chunk = body.xpath("//div[@class='foo'][#{var}]","//div[@class='foo']
    [#{var}]/following-sibling::div[@class='bar']
    [1 = count(preceding-sibling::div[@class='foo'][#{var}] |
    (//div[@class='foo'])[1])]")
  puts chunk
  var += 1
  break if chunk.length == 0
end
</code>```

Not sure how to wrap them in divs now.

答:
Welp I have a likely inelegant solution for the followers of this insanely popular question:</p>

```<code>var = 1
loop do
  chunk = body.xpath("//div[@class='foo'][#{var}]","//div[@class='foo']
    [#{var}]/following-sibling::div[@class='bar']
    [1 = count(preceding-sibling::div[@class='foo'][#{var}] |
    (//div[@class='foo'])[1])]")
  break if chunk.length == 0
  var += 1
  puts <div class="baz">
  puts chunk
  puts </div>
end
</code>```

Title: Wrapping a series of sibling elements

Body:
Using ruby/nokogiri I would like to wrap some elements starting at one element and ending before the next one of those elements. So lets say I have:

And I want to wrap all foos and their contiguous bars (if there are any) in a baz class that closes before the next foo (last one obvs doesn't have another foo), like this:

Thanks.

Edit: I found this that asks a similar question but I'm struggling to adapt it XPath axis, get all following nodes until

Edit 2:This will return the bars after the foo but not the foo:

body.xpath("(//div[@class='foo'])[1]/following-sibling::div[@class='bar']
    [1 = count(preceding-sibling::div[@class='foo'][1] | (//div[@class='foo'])[1])]")

Need to figure out how to include the foo!

Edit 3: Welp this will add the foo:

body.xpath("//div[@class='foo'][1]","//div[@class='foo']
    [1]/following-sibling::div[@class='bar']
    [1 = count(preceding-sibling::div[@class='foo'][1] | (//div[@class='foo'])[1])]")

But the bigger problem is I'm not sure how to iterate this? It just returns the first set of foo + bars.

Edit 4: Iterating through the foo-bar chunks:

var = 1
loop do
  chunk = body.xpath("//div[@class='foo'][#{var}]","//div[@class='foo']
    [#{var}]/following-sibling::div[@class='bar']
    [1 = count(preceding-sibling::div[@class='foo'][#{var}] |
    (//div[@class='foo'])[1])]")
  puts chunk
  var += 1
  break if chunk.length == 0
end

Not sure how to wrap them in divs now.

Body:
Welp I have a likely inelegant solution for the followers of this insanely popular question:

var = 1
loop do
  chunk = body.xpath("//div[@class='foo'][#{var}]","//div[@class='foo']
    [#{var}]/following-sibling::div[@class='bar']
    [1 = count(preceding-sibling::div[@class='foo'][#{var}] |
    (//div[@class='foo'])[1])]")
  break if chunk.length == 0
  var += 1
  puts <div class="baz">
  puts chunk
  puts </div>
end


问:
git blame to get the commit history for all files in entire repo
i am looking to get the commit history of every file in every folder under any repo. I am thinking to do brute force of git blame recursively and burn through all the folders, but how would i keep track of what file is under what folder, so yes the directory structure matters in this case as if i need to use the output of blame i would want to show what commit was made for what file under what folder.
I would appreciate if i am shown the direction and how can i pipe all of this data into some csv file.
Secondly, is it possible to get the blame of all the branches not just the current one but in a separate csv file per branch ?

Any help would be much appreciated.

Update: This is what i am doing right now;

```<code>for file in $(git ls-files);
    do git blame $file;
done
</code>```

答:
You could use git log: it can be applied to each file

```<code>git log -- afile
</code>```

You can add -M in order to follow renames.

Body:
i am looking to get the commit history of every file in every folder under any repo. I am thinking to do brute force of git blame recursively and burn through all the folders, but how would i keep track of what file is under what folder, so yes the directory structure matters in this case as if i need to use the output of blame i would want to show what commit was made for what file under what folder.
I would appreciate if i am shown the direction and how can i pipe all of this data into some csv file.
Secondly, is it possible to get the blame of all the branches not just the current one but in a separate csv file per branch ?

Any help would be much appreciated.

Update: This is what i am doing right now;

for file in $(git ls-files);
    do git blame $file;
done

Body:
You could use git log: it can be applied to each file

git log -- afile

You can add -M in order to follow renames.


问:
WSREP detected deadlock/conflict while copying data from one table to another one
I'm stamped with the error I keep getting on the query like this:

```<code>INSERT INTO database1.table1
SELECT * FROM database2.table2;
</code>```

table2 - InnoDB table, table 1 - MyISAM table.

The error looks like this:

"SQL error (1213): WSREP detected deadlock/conflict and aborted the
  transaction. Try restarting the transaction */"

I could workaround it by adding a limit of 500,000 records on select and performing this query part by part; but after 2,000,000 records are copied, the deadlock appear again, even if I reduce the limit per query to 5,000 records.

Which database settings may be responsible for this?

答:
Percona, MySQL 1.7.
Our administrator updated it to 1.7 a few weeks ago; before then this error didn't use to appear.</p>

Body:
I'm stamped with the error I keep getting on the query like this:

INSERT INTO database1.table1
SELECT * FROM database2.table2;

table2 - InnoDB table, table 1 - MyISAM table.

The error looks like this:

"SQL error (1213): WSREP detected deadlock/conflict and aborted the
  transaction. Try restarting the transaction */"

I could workaround it by adding a limit of 500,000 records on select and performing this query part by part; but after 2,000,000 records are copied, the deadlock appear again, even if I reduce the limit per query to 5,000 records.

Which database settings may be responsible for this?


问:
php pagination with break or continue
I need to make a paging with this format:

 1 2 3 4 5 ... 205

i use now this for loop:

```<code>$nav = '';
for($pageNum = 1; $pageNum <= $maxPage; $pageNum++)
{
   if ($pageNum == $p)
   {
   $nav .= '<li class=\"current\">$pageNum</li>';
   }
   else
   {
   $nav .= '<li><a href=\"?page=".$pageNum."\">$pageNum</a></li>';
   }
}
</code>```

i need to use a php break or continue??

答: Here there ara an example http://www.programacion.com/articulo/paginar_los_resultados_de_una_consulta_en_php_149</p>

Title: php pagination with break or continue

Body:
I need to make a paging with this format:

 1 2 3 4 5 ... 205

i use now this for loop:

$nav = '';
for($pageNum = 1; $pageNum <= $maxPage; $pageNum++)
{
   if ($pageNum == $p)
   {
   $nav .= '
$pageNum
';
   }
   else
   {
   $nav .= '
$pageNum
';
   }
}

i need to use a php break or continue??


问:
Design pattern to build one or more side-by-side views
I am attempting to build a dynamic control in Android that uses the builder pattern to construct a view that looks like:

[** Text][** Text]

Essentially, I am looking to create a view with an image and some text and group multiple such views together.

```<code>public static class DualBuilder {
        private final Context mContext;
        protected Drawable mFirstButtonIcon;
        protected Drawable mSecondButtonIcon;
        protected String mFirstButtonText;
        protected String mSecondButtonText;

        private DualBuilder(@NonNull final Context context) {
            mContext = context;
        }

        public DualBuilder firstButtonIcon(@Nullable final Drawable firstButtonIcon) {
            super.buttonIcon(firstButtonIcon);
            return this;
        }

        public DualBuilder firstButtonText(@NonNull final String firstButtonText) {
            super.buttonPrimaryText(firstButtonText);
            return this;
        }

        public DualBuilder secondButtonIcon(@Nullable final Drawable secondButtonIcon) {
            mSecondButtonIcon = secondButtonIcon;
            return this;
        }

        public DualBuilder secondButtonText(@NonNull final String secondButtonText) {
            mSecondButtonText = secondButtonText;
            return this;
        }

        public MultiViewControl build() {
            return new MultiViewControl(this);
        }
}
</code>```

The above would be a builder if i were to have two of these views. The constructor would take the builder variables and use them to construct a layout for each first/second view. The details of how that happens are not the issue, I just want to learn how to build something like this in a flexible way so it can accept 1...n number of views. What kind of a pattern can i use to achieve this? Any code sample would be very much appreciated.

答:
Google has released a new library called Fluxbox layout which will serve your purpose.

check out this https://github.com/google/flexbox-layout

It will add your view dynamically side by side as you expect.

Body:
I am attempting to build a dynamic control in Android that uses the builder pattern to construct a view that looks like:

[** Text][** Text]

Essentially, I am looking to create a view with an image and some text and group multiple such views together.

public static class DualBuilder {
        private final Context mContext;
        protected Drawable mFirstButtonIcon;
        protected Drawable mSecondButtonIcon;
        protected String mFirstButtonText;
        protected String mSecondButtonText;

        private DualBuilder(@NonNull final Context context) {
            mContext = context;
        }

        public DualBuilder firstButtonIcon(@Nullable final Drawable firstButtonIcon) {
            super.buttonIcon(firstButtonIcon);
            return this;
        }

        public DualBuilder firstButtonText(@NonNull final String firstButtonText) {
            super.buttonPrimaryText(firstButtonText);
            return this;
        }

        public DualBuilder secondButtonIcon(@Nullable final Drawable secondButtonIcon) {
            mSecondButtonIcon = secondButtonIcon;
            return this;
        }

        public DualBuilder secondButtonText(@NonNull final String secondButtonText) {
            mSecondButtonText = secondButtonText;
            return this;
        }

        public MultiViewControl build() {
            return new MultiViewControl(this);
        }
}

The above would be a builder if i were to have two of these views. The constructor would take the builder variables and use them to construct a layout for each first/second view. The details of how that happens are not the issue, I just want to learn how to build something like this in a flexible way so it can accept 1...n number of views. What kind of a pattern can i use to achieve this? Any code sample would be very much appreciated.


问:
Find Min Max of 2D array in scala
I have a 2D array of the form:

```<code>scala> signature_matrix
res129: Array[Array[Int]]
</code>```

How do I find the maximum element?

答:
flatten to a 1d list, then call max:</p>

```<code>arr.flatten.max
</code>```

Title: Find Min Max of 2D array in scala

Body:
I have a 2D array of the form:

scala> signature_matrix
res129: Array[Array[Int]]

How do I find the maximum element?

Body:
flatten to a 1d list, then call max:

arr.flatten.max


问:
Inno Setup - Prevent installation and execute program when installer is executed without administrator privileges
I want my installer to check admin rights at the beginning, and if not to execute a program that popups a form and exit the installation

procedure MyAfterInstall();
var
  MyProgChecked: boolean;
  ErrorCode : Integer;
begin
  MyProgChecked := not IsAdminLoggedOn;
  if MyProgChecked =true then
    ShellExec('', ExpandConstant('\users\public\EzPasteFiles\RAADMIN.EXE'), '',
              '', SW_SHOW, ewNoWait,ErrorCode ) ;
  ExitProcess(0);
end;
```

<p>My question is, where to put and how to make <strong>RAADMIN.EXE</strong> available to the procedure? </p>

<p>I have tried without success</p>

```Source: "c:\Dropbox\word\EzPasteOffice64Win10\RunAsAnAdminTutorial\RAADMIN.exe"; \
  DestDir: "\users\public\EzPasteFiles"; AfterInstall: MyAfterInstall
```

答:
Place your code in function InitializeSetup() which is called as very first when  installer starts.

If you return False from this function the installer will quit immediately.

Details: https://jrsoftware.org/ishelp/topic_scriptevents.htm

ContentLicense: CC BY-SA 4.0

Body:
I want my installer to check admin rights at the beginning, and if not to execute a program that popups a form and exit the installation

procedure MyAfterInstall();
var
  MyProgChecked: boolean;
  ErrorCode : Integer;
begin
  MyProgChecked := not IsAdminLoggedOn;
  if MyProgChecked =true then
    ShellExec('', ExpandConstant('\users\public\EzPasteFiles\RAADMIN.EXE'), '',
              '', SW_SHOW, ewNoWait,ErrorCode ) ;
  ExitProcess(0);
end;

My question is, where to put and how to make RAADMIN.EXE available to the procedure?

I have tried without success

Source: "c:\Dropbox\word\EzPasteOffice64Win10\RunAsAnAdminTutorial\RAADMIN.exe"; \
  DestDir: "\users\public\EzPasteFiles"; AfterInstall: MyAfterInstall


问:
Webpack - webpack-dev-server: command not found
I am working on a React webapp using webpack, loosely alongside this tutorial.

Accidentally, I added the node_modules folder to my git. I then removed it again using git rm -f node_modules/*.

Now, when I try starting the webpack server, I get the following error:

```<code>> webpack-dev-server -d --config webpack.dev.config.js --content-base public/ --progress --colors

sh: webpack-dev-server: command not found

npm ERR! Darwin 14.4.0
npm ERR! argv "node" "/usr/local/bin/npm" "run" "devserve"
npm ERR! node v0.12.4
npm ERR! npm  v2.10.1
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! Blabber@0.0.1 devserve: `webpack-dev-server -d --config webpack.dev.config.js --content-base public/ --progress --colors`
npm ERR! spawn ENOENT
</code>```

At first I thought it was only my project, but then I checked out the code checkpoints of the tutorial: same error! So something seems to be messed up globally.

Here's what I tried so far:

rm node_modules and reinstall with npm install

npm cache clean as someone mentioned regarding this issue on github

install webpack globally with npm install -g webpack

completely delete node and npm from my system (using this guide) and reinstall using brew

The error message still persists. What else can I try?

PS: The content of webpack.dev.config.js is:

```<code>var config = require('./webpack.config.js');
var webpack = require('webpack');

config.plugins.push(
  new webpack.DefinePlugin({
    "process.env": {
      "NODE_ENV": JSON.stringify("development")
    }
  })
);

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

答:
The script webpack-dev-server is already installed inside ./node_modules directory.
You can either install it again globally by

```<code>sudo npm install -g webpack-dev-server
</code>```

or run it like this

```<code>./node_modules/webpack-dev-server/bin/webpack-dev-server.js -d --config webpack.dev.config.js --content-base public/ --progress --colors
</code>```

. means look it in current directory.

Body:
I am working on a React webapp using webpack, loosely alongside this tutorial.

Accidentally, I added the node_modules folder to my git. I then removed it again using git rm -f node_modules/*.

Now, when I try starting the webpack server, I get the following error:

> webpack-dev-server -d --config webpack.dev.config.js --content-base public/ --progress --colors

sh: webpack-dev-server: command not found

npm ERR! Darwin 14.4.0
npm ERR! argv "node" "/usr/local/bin/npm" "run" "devserve"
npm ERR! node v0.12.4
npm ERR! npm  v2.10.1
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! Blabber@0.0.1 devserve: `webpack-dev-server -d --config webpack.dev.config.js --content-base public/ --progress --colors`
npm ERR! spawn ENOENT

At first I thought it was only my project, but then I checked out the code checkpoints of the tutorial: same error! So something seems to be messed up globally.

Here's what I tried so far:

rm node_modules and reinstall with npm install

npm cache clean as someone mentioned regarding this issue on github

install webpack globally with npm install -g webpack

completely delete node and npm from my system (using this guide) and reinstall using brew

The error message still persists. What else can I try?

PS: The content of webpack.dev.config.js is:

var config = require('./webpack.config.js');
var webpack = require('webpack');

config.plugins.push(
  new webpack.DefinePlugin({
    "process.env": {
      "NODE_ENV": JSON.stringify("development")
    }
  })
);

module.exports = config;

Body:
The script webpack-dev-server is already installed inside ./node_modules directory.
You can either install it again globally by

sudo npm install -g webpack-dev-server

or run it like this

./node_modules/webpack-dev-server/bin/webpack-dev-server.js -d --config webpack.dev.config.js --content-base public/ --progress --colors

. means look it in current directory.


问:
Copying stuff from vim running in putty
I am running Vim 6.3 through putty and putty connection manager. I have the mouse option set (set mouse = a). I am able to paste things from the (windows) clipboard to vim by  but selecting text in vim  isn't copying anything to the clipboard. Does anyone know how do I do this?

Note: I can't update Vim to a newer version.

答: Ctrl-Insert to copy, Shift-Insert to paste</p>

Title: Copying stuff from vim running in putty


问:
ng-show and ng-hide not binding to given variable in angularjs
I am using ng-show and ng-hide to show the banner for my page. When I am logged in I wanna show different banner than for logged out. So I have two div with ng-show and ng-hide whose value I am changing in the controller to true and false.

Html code:

First banner:

```<code><div id="firstPageHeader" class="navbar navbar-inverse" role="navigation" ng-show={{display}}>
</code>```

Second banner:

```<code><div id="restPageHeader" class="navbar-header" ng-hide={{display}}>
</code>```

Controller:

var LoginController = function($scope){

```<code>$scope.display = true;
$scope.loginUser = function(credentials){
console.log(credentials.username);
$scope.display = false;
}

$scope.logout = function(){
console.log('logout');
$scope.display = true;
}
</code>```

So here according to login and logout the display value will change to true and false but its not happening the value remains only true.
 So I want to know why the value is not getting changed even I used $scope.$apply()

答:
You just need to replace braces in ng-hide and ng-show double quotes</p>

```<code><div id="restPageHeader" class="navbar-header" ng-hide="display">
        I am login
        <img src="https://marketplace.canva.com/MABY09l0-Tw/1/0/thumbnail_large/canva-outlined-lettering-border-tumblr-banner-MABY09l0-Tw.jpg" alt="">
    </div>
    <div id="restPageHeader" class="navbar-header" ng-show="display">
        I am logout
        <img src="https://img.clipartfest.com/08e6b6a7495aca9bbc478fcf662cd29b_welcome-hanging-banner-welcome-banner-clipart_935-311.jpeg" alt="">
    </div>

this is controller

$scope.display = true;
    $scope.loginUser = function () {
        console.log('loginUser');
        $scope.display = false;
    }
    $scope.logout = function () {
            console.log('logout');
            $scope.display = true;
        }
</code>```

Body:
I am using ng-show and ng-hide to show the banner for my page. When I am logged in I wanna show different banner than for logged out. So I have two div with ng-show and ng-hide whose value I am changing in the controller to true and false.

Html code:

First banner:

Second banner:

Controller:

var LoginController = function($scope){

$scope.display = true;
$scope.loginUser = function(credentials){
console.log(credentials.username);
$scope.display = false;
}

$scope.logout = function(){
console.log('logout');
$scope.display = true;
}

So here according to login and logout the display value will change to true and false but its not happening the value remains only true.
 So I want to know why the value is not getting changed even I used $scope.$apply()

Body:
You just need to replace braces in ng-hide and ng-show double quotes

<div id="restPageHeader" class="navbar-header" ng-hide="display">
        I am login
        <img src="https://marketplace.canva.com/MABY09l0-Tw/1/0/thumbnail_large/canva-outlined-lettering-border-tumblr-banner-MABY09l0-Tw.jpg" alt="">
    </div>
    <div id="restPageHeader" class="navbar-header" ng-show="display">
        I am logout
        <img src="https://img.clipartfest.com/08e6b6a7495aca9bbc478fcf662cd29b_welcome-hanging-banner-welcome-banner-clipart_935-311.jpeg" alt="">
    </div>

this is controller

$scope.display = true;
    $scope.loginUser = function () {
        console.log('loginUser');
        $scope.display = false;
    }
    $scope.logout = function () {
            console.log('logout');
            $scope.display = true;
        }


问:
How to ignore CheckStyle warning for missing @throws for test method?
I'm being plagued by CheckStyle warnings about missing @throws in the JavaDoc of test methods.

I'm using writing a test method like this:

```<code>/**
 * Check that something works. <== CheckStyle wants @throws here
 */
@Test
public void testSomething() throws Exception {
  ...
}
</code>```

Is there a configurable way to tell CheckStyle to ignore this ?

The "throws" clause is there especially because it is a test method; where typically exception handling is ignored.

答: @SuppressWarnings("checkstyle:javadocmethod") is the annotation used to suppress warnings for getters and setters or any method in java where you don't need the javadoc</p>

Body:
I'm being plagued by CheckStyle warnings about missing @throws in the JavaDoc of test methods.

I'm using writing a test method like this:

/**
 * Check that something works. <== CheckStyle wants @throws here
 */
@Test
public void testSomething() throws Exception {
  ...
}

Is there a configurable way to tell CheckStyle to ignore this ?

The "throws" clause is there especially because it is a test method; where typically exception handling is ignored.


问:
how to copy Folders - FAKE F#MAKE
I am using  Copy function of FAKE to copy files from project1 to release folder ,I am using below code :

```<code>Target "CopyProject1" (fun _ ->
    !!(buildDir @@ "/_PublishWebsites/Project1/**/*.*")
        |> Copy releaseDir
)
</code>```

to copy files from Project1 folder to release folder , then all files inside Project1 are being copied to release folder , but I want to maintain folder structure of Project1 inside my release folder , i.e. I want to copy folders of Project1 to release , Is this possible or I will have to create subfolders inside my release folders and copy one by one .and if there is no such way of doing this then is this possible using custom task?

If anyone can help in this regard , that would be really helpful.

答:
I used CopyDir function of FAKE , and this is copying directories recursively , we just have to give the folder name and target location where we want to copy folders .Here is the code :

```<code>Target "CopyFoldersTargetLocation" (fun _ ->
    CopyDir targetDir SourceDir allFiles
)
</code>```

Title: how to copy Folders - FAKE F#MAKE

Body:
I am using  Copy function of FAKE to copy files from project1 to release folder ,I am using below code :

Target "CopyProject1" (fun _ ->
    !!(buildDir @@ "/_PublishWebsites/Project1/**/*.*")
        |> Copy releaseDir
)

to copy files from Project1 folder to release folder , then all files inside Project1 are being copied to release folder , but I want to maintain folder structure of Project1 inside my release folder , i.e. I want to copy folders of Project1 to release , Is this possible or I will have to create subfolders inside my release folders and copy one by one .and if there is no such way of doing this then is this possible using custom task?

If anyone can help in this regard , that would be really helpful.

Body:
I used CopyDir function of FAKE , and this is copying directories recursively , we just have to give the folder name and target location where we want to copy folders .Here is the code :

Target "CopyFoldersTargetLocation" (fun _ ->
    CopyDir targetDir SourceDir allFiles
)


问:
Ionic 2 how to check all checkboxes on button click and get checked checkboxes' value
I m fairly new in Angular 2 and hence Ionic 2, I have a little problem, can any body tell me how to check all checkboxes on button click?? and how to get value oc checked checkboxes on another button click.

Here is my how html looks like

```<code><div class="card item-icon-right"  *ngFor="let item of items" >
    <ion-checkbox *ngIf="showCheckBoxes" [(ngModel)]="item.id" mode="ios"></ion-checkbox>
</div>
<button class="button button-calm">Check All</button>
<button class="button button-primary">Get selected Values</button>
</code>```

Thanks

答:
you can have two checkbox elements

For select All -to make all the elements based on one click(simply toggle)

Select particular

```<code><div class="card item-icon-right"  *ngFor="let item of items" >
     <ion-checkbox *ngIf="showCheckBoxes && selectedAll" [(ngModel)]="item.id" mode="ios" [checked]="selectedAll"></ion-checkbox>

     <ion-checkbox *ngIf="showCheckBoxes && !selectedAll" [(ngModel)]="item.id" mode="ios" ></ion-checkbox>
</div>
</code>```

Check All
Get selected Values

```<code>checkAll(){
    this.selectedAll=true;
    console.log(this.items);
}
</code>```

When you are selecting all items then you are using the entire array as such.

Body:
I m fairly new in Angular 2 and hence Ionic 2, I have a little problem, can any body tell me how to check all checkboxes on button click?? and how to get value oc checked checkboxes on another button click.

Here is my how html looks like

    <ion-checkbox *ngIf="showCheckBoxes" [(ngModel)]="item.id" mode="ios"></ion-checkbox>

<button class="button button-calm">Check All</button>
<button class="button button-primary">Get selected Values</button>

Thanks

Body:
you can have two checkbox elements

For select All -to make all the elements based on one click(simply toggle)

Select particular

<div class="card item-icon-right"  *ngFor="let item of items" >
     <ion-checkbox *ngIf="showCheckBoxes && selectedAll" [(ngModel)]="item.id" mode="ios" [checked]="selectedAll"></ion-checkbox>

     <ion-checkbox *ngIf="showCheckBoxes && !selectedAll" [(ngModel)]="item.id" mode="ios" ></ion-checkbox>
</div>

Check All
Get selected Values

checkAll(){
    this.selectedAll=true;
    console.log(this.items);
}

When you are selecting all items then you are using the entire array as such.


问:
How to write user input 2D array?
I am new to java. Trying to make this into a user input 2D array which is 4*4. But when I try scanner, the row and col always got messed up.

```<code>public static void main(String[] args) {
        String array = "1 2 2 1,1 3 3 1,1 3 3 2,2 2 2 2";
        int[][] input = parseInt(array, 4, 4);
}
</code>```

And I also want the user input can output as:

```<code>1 2 2 1
1 3 3 1
1 3 3 2
2 2 2 2
</code>```

Appreciate for everybody's help!

答:
Try this one :

```<code> public static void main(String args[]) {

    String array = "1 2 2 1,1 3 3 1,1 3 3 2,2 2 2 2";
    int[][] input = new int[4][4];//4*4
    String[] inputs = array.split(",");
    for (int i = 0; i < inputs.length; i++) {
        String[] cols = inputs[i].split(" ");
        for (int j = 0; j < cols.length; j++) {
            input[i][j] = Integer.parseInt(cols[j]);
            System.out.print(input[i][j]);
            System.out.print(" ");// for spacing
        }

        System.out.println();

    }
}
</code>```

Output :

Title: How to write user input 2D array?

Body:
I am new to java. Trying to make this into a user input 2D array which is 4*4. But when I try scanner, the row and col always got messed up.

public static void main(String[] args) {
        String array = "1 2 2 1,1 3 3 1,1 3 3 2,2 2 2 2";
        int[][] input = parseInt(array, 4, 4);
}

And I also want the user input can output as:

1 2 2 1
1 3 3 1
1 3 3 2
2 2 2 2

Appreciate for everybody's help!

Body:
Try this one :

 public static void main(String args[]) {

    String array = "1 2 2 1,1 3 3 1,1 3 3 2,2 2 2 2";
    int[][] input = new int[4][4];//4*4
    String[] inputs = array.split(",");
    for (int i = 0; i < inputs.length; i++) {
        String[] cols = inputs[i].split(" ");
        for (int j = 0; j < cols.length; j++) {
            input[i][j] = Integer.parseInt(cols[j]);
            System.out.print(input[i][j]);
            System.out.print(" ");// for spacing
        }

        System.out.println();

    }
}

Output :


问:
Bootstrap place all div in single line
I am trying to place userlist in left side and searchbox and button in right side in same line

```<code><div class="row">
  <div class="col-md-4">
    <div class="user-title">User List-5</div>
  </div>
  <div class="col-md-8">
    <div class="input-group user-search-box col-md-6">
      <input type="text" class="form-control" placeholder="Search" aria-describedby="basic-addon2">
      <span class="input-group-addon input-search-custom-adon" ><i class="fa fa-search" aria-hidden="true"></i></span>
    </div>
    <div class="add-new-user col-md-6">
      <a class="btn  add-new-user" href="#" role="button">ADD NEW USER</a>
    </div>
  </div>
</div>
</code>```

i have tried by using float:left then add button will show first instead of search box
can any one help me

答:
I editted your code in fiddle. Seems to be having what you needed but only after 992px of viewport width. The reason for this is that you are using col-md-4 so the layout will hold tru only after that viewport width.

If you wish that it should hold true for smaller screens as well pls try using

```<code>col-sm-4 or col-xs-4 for user list

col-sm-8 or col-xs-8 for search and button div
</code>```

Note : Once you specify md for lower viewports it takes full width of 12 columns/100% of container.

If you need it after 992 px only then here is the updated code bootstrap way :P.
you probably got it wrong by combining input-group with col class

```<code><div class="row">
  <div class="col-md-4">
    <div class="user-title">User List-5</div>
  </div>
  <div class="col-md-8">
    <div class="row">
      <div class="col-md-offset-4 col-md-6">
        <div class="input-group user-search-box">
          <input type="text" class="form-control" placeholder="Search" aria-describedby="basic-addon2">
          <span class="input-group-addon input-search-custom-adon"><i class="fa fa-search" aria-hidden="true"></i></span>
        </div>
      </div>
      <div class="col-md-2">
        <div class="add-new-user">
          <a class="btn  add-new-user" href="#" role="button">ADD NEW USER</a>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

Hope this helps.

Title: Bootstrap place all div in single line

Body:
I am trying to place userlist in left side and searchbox and button in right side in same line

User List-5

      <input type="text" class="form-control" placeholder="Search" aria-describedby="basic-addon2">

      ADD NEW USER

i have tried by using float:left then add button will show first instead of search box
can any one help me

Body:
I editted your code in fiddle. Seems to be having what you needed but only after 992px of viewport width. The reason for this is that you are using col-md-4 so the layout will hold tru only after that viewport width.

If you wish that it should hold true for smaller screens as well pls try using

col-sm-4 or col-xs-4 for user list

col-sm-8 or col-xs-8 for search and button div

Note : Once you specify md for lower viewports it takes full width of 12 columns/100% of container.

If you need it after 992 px only then here is the updated code bootstrap way :P.
you probably got it wrong by combining input-group with col class

<div class="row">
  <div class="col-md-4">
    <div class="user-title">User List-5</div>
  </div>
  <div class="col-md-8">
    <div class="row">
      <div class="col-md-offset-4 col-md-6">
        <div class="input-group user-search-box">
          <input type="text" class="form-control" placeholder="Search" aria-describedby="basic-addon2">
          <span class="input-group-addon input-search-custom-adon"><i class="fa fa-search" aria-hidden="true"></i></span>
        </div>
      </div>
      <div class="col-md-2">
        <div class="add-new-user">
          <a class="btn  add-new-user" href="#" role="button">ADD NEW USER</a>
        </div>
      </div>
    </div>
  </div>
</div>

Hope this helps.


问:
jQuery Smooth Horizontal Scroll
I've created a long horizontal page and using anchors to navigate to section's within the page. I added a jQuery smooth scrolling function but it's not taking affect?

Here's the navigation:

```<code><ul class="nav">
<li><a href="#starters">Starters</a></li>
<li><a href="#main">Main Dishes</a></li>
<li><a href="#special">Special Dishes</a></li>
<li><a href="#side">Side Dishes</a></li>
</ul>
</code>```

Within the content i've added corresponding anchors:

```<code><a name="starters"></a>
</code>```

And here's the jQuery function:

```<code>$(function() {
$('ul.nav a').bind('click',function(event){
    var $anchor = $(this);

    $('html, body').stop().animate({
        scrollLeft: $($anchor.attr('href')).offset().left
    }, 1500, "easeInOutExpo");
    event.preventDefault();
});
});
</code>```

The anchor's work fine, clicking the navigation takes you to the desired section but it jumps instead of scrolling.

Any ideas why??

答:
It's simple add class to your div which need to scroll for example below:

```<code><ul class="nav">
<li class="a"><a href="#starters">Starters</a></li>
<li class="b"><a href="#main">Main Dishes</a></li>
<li class="c"><a href="#special">Special Dishes</a></li>
<li class="d"><a href="#side">Side Dishes</a></li>
</ul>
</code>```

Now, your js will be like this:

```<code>$(function() {
$('#clickable element').bind('click',function(event){
    $('#targetelement or div').stop().animate({
        scrollLeft: $('.a').offset().left
    }, 500);
    event.preventDefault();
});
});
</code>```

likewise you can build js for b,c,d classes.

Title: jQuery Smooth Horizontal Scroll

Body:
I've created a long horizontal page and using anchors to navigate to section's within the page. I added a jQuery smooth scrolling function but it's not taking affect?

Here's the navigation:

Starters

Main Dishes

Special Dishes

Side Dishes

Within the content i've added corresponding anchors:

And here's the jQuery function:

$(function() {
$('ul.nav a').bind('click',function(event){
    var $anchor = $(this);

    $('html, body').stop().animate({
        scrollLeft: $($anchor.attr('href')).offset().left
    }, 1500, "easeInOutExpo");
    event.preventDefault();
});
});

The anchor's work fine, clicking the navigation takes you to the desired section but it jumps instead of scrolling.

Any ideas why??

Body:
It's simple add class to your div which need to scroll for example below:

<ul class="nav">
<li class="a"><a href="#starters">Starters</a></li>
<li class="b"><a href="#main">Main Dishes</a></li>
<li class="c"><a href="#special">Special Dishes</a></li>
<li class="d"><a href="#side">Side Dishes</a></li>
</ul>

Now, your js will be like this:

$(function() {
$('#clickable element').bind('click',function(event){
    $('#targetelement or div').stop().animate({
        scrollLeft: $('.a').offset().left
    }, 500);
    event.preventDefault();
});
});

likewise you can build js for b,c,d classes.