问:
SubSet sum with N array Solution, Dynamic Solution recquired
Though you can have any number of arrays but let's Suppose you have two arrays {1,2,3,4,5,6} and {1,2,3,4,5,6}
You have to find whether they sum upto 4 with participation of both array elements. i.e.

```<code>1 from array1, 3 from array2
2 from array1, 2 from array2
3 from array1, 1 from array2
</code>```

etc

In Nutshell:Want to implement SubSet Sum Algorithm where there is two arrays and array elements are chosen from both of the arrays to make up the target Sum

here is the subset sum algorithm that I use for one array

```<code>bool subset_sum(int a[],int n, int sum)
{
 bool dp[n+1][sum+1];

   int i,j;

   for(i=0;i<=n;i++)
      dp[i][0]=true;

   for(j=1;j<=sum;j++)
        dp[0][j]=false;

   for(i=1;i<=n;i++)

    {

        for(j=1;j<=sum;j++)

       {

           if(dp[i-1][j]==true)

              dp[i][j]=true;

           else
           {

               if(a[i-1]>j)

                   dp[i][j]=false;

                else

                    dp[i][j]=dp[i-1][j-a[i-1]];

            }

        }

    }
  return dp[n][sum];
}
</code>```

答:
We can implement this with a 3 dimensional dp. But for simplicity and readability I have written it using two methods.

NOTE : My solution works when we choose at least one element from each array. It doesn't work if there is a condition that we have to choose equal number of elements from each array.

```<code>// This is a helper method

//  prevPosAr[] is the denotes what values could be made with participation from ALL
// arrays BEFORE the current array

// This method returns an array which denotes what values could be made with the
// with participation from ALL arrays UP TO current array

boolean[] getPossibleAr( boolean prevPossibleAr[], int ar[] )
{
    boolean dp[][] = new boolean[ ar.length + 1 ][ prevPossibleAr.length  ];
    // dp[i][j] denotes   if we can make value j using AT LEAST
    // ONE element from current ar[0...i-1]

    for (int i = 1; i <= ar.length; i++)
    {
        for (int j = 0; j < dp[i].length; j++)
        {
            if ( dp[i-1][j] == true )
            {
                // we can make value j using AT LEAST one element from ar[0...i-2]
                // it implies that we can also make value j using AT LEAST
                // one element from ar[0...i-1]
                dp[i][j] = true;
                continue;
            }

            int prev = i-ar[i-1];
            // now we look behind

            if ( prev < 0 )
            {
                // it implies that ar[i-1] > i
                continue;
            }

            if ( prevPossibleAr[prev] || dp[i-1][prev] )
            {
                // It is the main catch
                // Be careful

                // if ( prevPossibleAr[prev] == true )
                // it means that we could make the value prev
                // using the previous arrays (without using any element
                // of the current array)
                // so now we can add ar[i-1] with prev and eventually make i

                // if ( dp[i-1][prev] == true )
                // it means that we could make prev using one or more
                // elements from the current array....
                // now we can add ar[i-1] with this and eventually make i

                dp[i][j] = true;
            }
        }
    }

    // What is dp[ar.length] ?
    // It is an array of booleans
    // It denotes whether we can make value j using ALL the arrays
    // (using means taking AT LEAST ONE ELEMENT)
    // before the current array and using at least ONE element
    // from the current array ar[0...ar.lengh-1] (That is the full current array)

    return dp[ar.length];
}

// This is the method which will give us the output
boolean subsetSum(int  ar[][], int sum )
{
    boolean prevPossible[] = new boolean[sum+1];
    prevPossible[0] = true;

    for ( int i = 0; i < ar.length; i++ )
    {
        boolean newPossible[] = getPossibleAr(prevPossible, ar[i]);
        // calling that helper function
        // newPossible denotes what values can be made with
        // participation from ALL arrays UP TO i th array
        // (0 based index here)

        prevPossible = newPossible;
    }

    return prevPossible[sum];
}
</code>```

Body:
Though you can have any number of arrays but let's Suppose you have two arrays {1,2,3,4,5,6} and {1,2,3,4,5,6}
You have to find whether they sum upto 4 with participation of both array elements. i.e.

1 from array1, 3 from array2
2 from array1, 2 from array2
3 from array1, 1 from array2

etc

In Nutshell:Want to implement SubSet Sum Algorithm where there is two arrays and array elements are chosen from both of the arrays to make up the target Sum

here is the subset sum algorithm that I use for one array

bool subset_sum(int a[],int n, int sum)
{
 bool dp[n+1][sum+1];

   int i,j;

   for(i=0;i<=n;i++)
      dp[i][0]=true;

   for(j=1;j<=sum;j++)
        dp[0][j]=false;

   for(i=1;i<=n;i++)

    {

        for(j=1;j<=sum;j++)

       {

           if(dp[i-1][j]==true)

              dp[i][j]=true;

           else
           {

               if(a[i-1]>j)

                   dp[i][j]=false;

                else

                    dp[i][j]=dp[i-1][j-a[i-1]];

            }

        }

    }
  return dp[n][sum];
}

Body:
We can implement this with a 3 dimensional dp. But for simplicity and readability I have written it using two methods.

NOTE : My solution works when we choose at least one element from each array. It doesn't work if there is a condition that we have to choose equal number of elements from each array.

// This is a helper method

//  prevPosAr[] is the denotes what values could be made with participation from ALL
// arrays BEFORE the current array

// This method returns an array which denotes what values could be made with the
// with participation from ALL arrays UP TO current array

boolean[] getPossibleAr( boolean prevPossibleAr[], int ar[] )
{
    boolean dp[][] = new boolean[ ar.length + 1 ][ prevPossibleAr.length  ];
    // dp[i][j] denotes   if we can make value j using AT LEAST
    // ONE element from current ar[0...i-1]

    for (int i = 1; i <= ar.length; i++)
    {
        for (int j = 0; j < dp[i].length; j++)
        {
            if ( dp[i-1][j] == true )
            {
                // we can make value j using AT LEAST one element from ar[0...i-2]
                // it implies that we can also make value j using AT LEAST
                // one element from ar[0...i-1]
                dp[i][j] = true;
                continue;
            }

            int prev = i-ar[i-1];
            // now we look behind

            if ( prev < 0 )
            {
                // it implies that ar[i-1] > i
                continue;
            }

            if ( prevPossibleAr[prev] || dp[i-1][prev] )
            {
                // It is the main catch
                // Be careful

                // if ( prevPossibleAr[prev] == true )
                // it means that we could make the value prev
                // using the previous arrays (without using any element
                // of the current array)
                // so now we can add ar[i-1] with prev and eventually make i

                // if ( dp[i-1][prev] == true )
                // it means that we could make prev using one or more
                // elements from the current array....
                // now we can add ar[i-1] with this and eventually make i

                dp[i][j] = true;
            }
        }
    }

    // What is dp[ar.length] ?
    // It is an array of booleans
    // It denotes whether we can make value j using ALL the arrays
    // (using means taking AT LEAST ONE ELEMENT)
    // before the current array and using at least ONE element
    // from the current array ar[0...ar.lengh-1] (That is the full current array)

    return dp[ar.length];
}

// This is the method which will give us the output
boolean subsetSum(int  ar[][], int sum )
{
    boolean prevPossible[] = new boolean[sum+1];
    prevPossible[0] = true;

    for ( int i = 0; i < ar.length; i++ )
    {
        boolean newPossible[] = getPossibleAr(prevPossible, ar[i]);
        // calling that helper function
        // newPossible denotes what values can be made with
        // participation from ALL arrays UP TO i th array
        // (0 based index here)

        prevPossible = newPossible;
    }

    return prevPossible[sum];
}


来源: stackexchange

问:
Input Layout toggle hintText color change
I am using TextInputLayout in which i want to change the color of hinttext  when i enter text then the color of hint text should be blue other wise color should be gray and when edittext contains some value then the color of hintText should blue for more information please check my image.

Ultimate i want this after edit text containing some value.

This is my current result after using this code

```<code>  <style name="labelcolor" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Hint color and label color in FALSE state -->
    <item name="android:textColorHint">#868686</item>
    <item name="android:textSize">16sp</item>
    <item name="android:paddingTop">5sp</item>
    <!-- Label color in TRUE state and bar color FALSE and TRUE State -->
    <item name="colorAccent">#0ea3ff</item>
    <item name="colorControlNormal">#0ea3ffr</item>
    <item name="colorControlActivated">#0ea3ff</item>
</style>
</code>```

please help me how can i solve this issues.

答:
Create your as bellow and try </p>

```<code><style name="EditTextHint" parent="TextAppearance.AppCompat">
    <item name="colorAccent">@android:color/white</item>
    <item name="android:textColorHint">@color/BackgroundtWhiteColor</item>
    <item name="colorControlNormal">@color/BackgroundtWhiteColor</item>
    <item name="colorControlActivated">@color/your color</item>
    <item name="colorControlHighlight">@color/BackgroundtWhiteColor</item>
</style>
</code>```

<p>Use it as bellow </p>

```<code><android.support.design.widget.TextInputLayout
            android:theme="@style/EditTextHint"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
      <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
</android.support.design.widget.TextInputLayout>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using TextInputLayout in which i want to change the color of hinttext  when i enter text then the color of hint text should be blue other wise color should be gray and when edittext contains some value then the color of hintText should blue for more information please check my image.

Ultimate i want this after edit text containing some value.

This is my current result after using this code

please help me how can i solve this issues.

Body:
Create your as bellow and try

<style name="EditTextHint" parent="TextAppearance.AppCompat">
    <item name="colorAccent">@android:color/white</item>
    <item name="android:textColorHint">@color/BackgroundtWhiteColor</item>
    <item name="colorControlNormal">@color/BackgroundtWhiteColor</item>
    <item name="colorControlActivated">@color/your color</item>
    <item name="colorControlHighlight">@color/BackgroundtWhiteColor</item>
</style>

Use it as bellow

<android.support.design.widget.TextInputLayout
            android:theme="@style/EditTextHint"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
      <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
</android.support.design.widget.TextInputLayout>


问:
Why does IMAP require a tag in front of each command?
Why does IMAP require a tag in front of each command?

```<code>A login mylogin mysupersecretpassword
</code>```

What is the use for this?

答:
There are/were two goals.

Let clients issue several commands at a time and be told unambiguously which command has been completed by the server. (This could be achieved in other ways, such as an explicit ordering rule.)

Debugging. The tag provides convenient client/server logfile correlation.

Many clients do issue more than one command at a time in practice, even if they're far from the maximum allowed parallelism.

Body:
Why does IMAP require a tag in front of each command?

A login mylogin mysupersecretpassword

What is the use for this?


问:
Pandas Dataframe (from CSV) with mutiple header rows throughout the data
Test data fileI am working with a dataframe that I created from a CSV file. The data has header rows throughout the data, which identify something about the rows below that data, until the next header row.

The data looks something like this.

```<code>2001|     |colour |Price | Quantity sold<br>
Shoes|<br>
Blank  | High heal Shoes| red |£22|44<br>
Blank  | Low heal Shoes|red |£22|44<br>
Slippers|<br>
Blank  | High heal Slippers| red |£22|44<br>
Blank  | High heal Slippers| blue |£22|44<br>
Blank  | Low heal Slippers| red |£22|44<br>
2002|   |colour |Price | Quantity sold<br>
Shoes|<br>
Blank  | High heal Shoes| red |£22|44<br>
Blank  | Low heal Shoes|red |£22|44<br>
Slippers|<br>
Blank  | High heal Slippers| red |£22|44<br>
Blank  | High heal Slippers| blue |£22|44<br>
Blank  | Low heal Slippers| red |£22|44<br>
</code>```

What type of structure is this?

I need to read through this dataframe get all data on a particular item (say Slippers) for each year from the header row (so 2001, 2002 and so on). Even adding a row with the corresponding year next to each data row would help.

I will appreciate some help on how to do that?

答:
Use:

```<code>df = pd.read_csv('test.csv')

#get value of first column (here 2001)
col = df.columns[0]

#forward fill last previous value
df[col] = df[col].ffill()
#convert first column to numeric
num = pd.to_numeric(df[col], errors='coerce')
#forward fill again, first group replace by value of first column name
df['Year'] = num.ffill().fillna(col)
#change columns names
df = df.rename(columns={col:'Shoes', 'Unnamed: 1':'Names'})
#remove unnecessary rows
df = df[num.isnull() & df['colour'].notnull()].reset_index(drop=True)
</code>```

```<code>print (df)
           Shoes       Names  colour price Quantity sold  Year
0   Type A shoes  Sub type A     red    22             5  2001
1   Type A shoes  Sub type A   green    11             5  2001
2   Type A shoes  Sub type A  yellow    44             5  2001
3   Type A shoes  Sub type B     red    33             5  2001
4   Type A shoes  Sub type B   green    66             5  2001
5   Type A shoes  Sub type B  yellow    22             5  2001
6   Type B shoes  Sub type A     red    11             5  2001
7   Type B shoes  Sub type A   green    44             5  2001
8   Type B shoes  Sub type A  yellow    33             5  2001
9   Type B shoes  Sub type B     red    66             5  2001
10  Type B shoes  Sub type B   green    21             5  2001
11  Type B shoes  Sub type B  yellow    22             5  2001
12  Type A shoes  Sub type A     red    22             5  2002
13  Type A shoes  Sub type A   green    11             5  2002
14  Type A shoes  Sub type A  yellow    44             5  2002
15  Type A shoes  Sub type B     red    33             5  2002
16  Type A shoes  Sub type B   green    66             5  2002
17  Type A shoes  Sub type B  yellow    22             5  2002
18  Type B shoes  Sub type A     red    11             5  2002
19  Type B shoes  Sub type A   green    44             5  2002
20  Type B shoes  Sub type A  yellow    33             5  2002
21  Type B shoes  Sub type B     red    66             5  2002
22  Type B shoes  Sub type B   green    21             5  2002
23  Type B shoes  Sub type B  yellow    22             5  2002
</code>```

EDIT:

```<code>df = pd.read_csv('testV2.csv', sep='\t')
#print (df)

#get value of first column (here 2001)
col = df.columns[0]

#forward fill last previous value
df[col] = df[col].ffill()
#convert first column to numeric
num = pd.to_numeric(df[col], errors='coerce')
#forward fill again, first group replace by value of first column name
df['Year'] = num.ffill().fillna(col)
#change columns names
df = df.rename(columns={col:'Top Category', 'Unnamed: 1':'Names'})
#remove unnecessary rows
df = df[num.isnull() & (df['Top Category'] != 'Top Category')].reset_index(drop=True)
</code>```

```<code>print (df)

   Top Category   Names Colour Price Sold  Year
0        Item 1  Type 1      -     2  NaN  2001
1        Item 2  Type 1      -     2  NaN  2001
2        Item 3  Type 1    red     2    5  2001
3        Item 3  Type 2   blue     2    5  2001
4        Item 3  Type 3  green     2    5  2001
5        item 4  Type 1    red     2    5  2001
6        item 4  Type 2   blue     3  NaN  2001
7        item 4  Type 3  green     3  NaN  2001
8        Item 1  Type 1      -     3  NaN  2002
9        Item 2  Type 1      -     3  NaN  2002
10       Item 3  Type 1    red     3    5  2002
11       Item 3  Type 2   blue     3    5  2002
12       Item 3  Type 3  green     3    5  2002
13        Item4  Type 1    red     3  NaN  2002
14        Item4  Type 2   blue     3  NaN  2002
15        Item4  Type 3  green     3  NaN  2002
16       Item 1  Type 1      -     3  NaN  2003
17       Item 2  Type 1      -     3  NaN  2003
18       Item 3  Type 1    red     3    5  2003
19       Item 3  Type 2   blue     3    5  2003
20       Item 3  Type 3  green     3    5  2003
21        Item4  Type 1    red     3  NaN  2003
22        Item4  Type 2   blue     3  NaN  2003
23        Item4  Type 3  green     3  NaN  2003
</code>```

Body:
Test data fileI am working with a dataframe that I created from a CSV file. The data has header rows throughout the data, which identify something about the rows below that data, until the next header row.

The data looks something like this.

2001|     |colour |Price | Quantity sold

Shoes|

Blank  | High heal Shoes| red |£22|44

Blank  | Low heal Shoes|red |£22|44

Slippers|

Blank  | High heal Slippers| red |£22|44

Blank  | High heal Slippers| blue |£22|44

Blank  | Low heal Slippers| red |£22|44

2002|   |colour |Price | Quantity sold

Shoes|

Blank  | High heal Shoes| red |£22|44

Blank  | Low heal Shoes|red |£22|44

Slippers|

Blank  | High heal Slippers| red |£22|44

Blank  | High heal Slippers| blue |£22|44

Blank  | Low heal Slippers| red |£22|44

What type of structure is this?

I need to read through this dataframe get all data on a particular item (say Slippers) for each year from the header row (so 2001, 2002 and so on). Even adding a row with the corresponding year next to each data row would help.

I will appreciate some help on how to do that?

Body:
Use:

df = pd.read_csv('test.csv')

#get value of first column (here 2001)
col = df.columns[0]

#forward fill last previous value
df[col] = df[col].ffill()
#convert first column to numeric
num = pd.to_numeric(df[col], errors='coerce')
#forward fill again, first group replace by value of first column name
df['Year'] = num.ffill().fillna(col)
#change columns names
df = df.rename(columns={col:'Shoes', 'Unnamed: 1':'Names'})
#remove unnecessary rows
df = df[num.isnull() & df['colour'].notnull()].reset_index(drop=True)

print (df)
           Shoes       Names  colour price Quantity sold  Year
0   Type A shoes  Sub type A     red    22             5  2001
1   Type A shoes  Sub type A   green    11             5  2001
2   Type A shoes  Sub type A  yellow    44             5  2001
3   Type A shoes  Sub type B     red    33             5  2001
4   Type A shoes  Sub type B   green    66             5  2001
5   Type A shoes  Sub type B  yellow    22             5  2001
6   Type B shoes  Sub type A     red    11             5  2001
7   Type B shoes  Sub type A   green    44             5  2001
8   Type B shoes  Sub type A  yellow    33             5  2001
9   Type B shoes  Sub type B     red    66             5  2001
10  Type B shoes  Sub type B   green    21             5  2001
11  Type B shoes  Sub type B  yellow    22             5  2001
12  Type A shoes  Sub type A     red    22             5  2002
13  Type A shoes  Sub type A   green    11             5  2002
14  Type A shoes  Sub type A  yellow    44             5  2002
15  Type A shoes  Sub type B     red    33             5  2002
16  Type A shoes  Sub type B   green    66             5  2002
17  Type A shoes  Sub type B  yellow    22             5  2002
18  Type B shoes  Sub type A     red    11             5  2002
19  Type B shoes  Sub type A   green    44             5  2002
20  Type B shoes  Sub type A  yellow    33             5  2002
21  Type B shoes  Sub type B     red    66             5  2002
22  Type B shoes  Sub type B   green    21             5  2002
23  Type B shoes  Sub type B  yellow    22             5  2002

EDIT:

df = pd.read_csv('testV2.csv', sep='\t')
#print (df)

#get value of first column (here 2001)
col = df.columns[0]

#forward fill last previous value
df[col] = df[col].ffill()
#convert first column to numeric
num = pd.to_numeric(df[col], errors='coerce')
#forward fill again, first group replace by value of first column name
df['Year'] = num.ffill().fillna(col)
#change columns names
df = df.rename(columns={col:'Top Category', 'Unnamed: 1':'Names'})
#remove unnecessary rows
df = df[num.isnull() & (df['Top Category'] != 'Top Category')].reset_index(drop=True)

print (df)

   Top Category   Names Colour Price Sold  Year
0        Item 1  Type 1      -     2  NaN  2001
1        Item 2  Type 1      -     2  NaN  2001
2        Item 3  Type 1    red     2    5  2001
3        Item 3  Type 2   blue     2    5  2001
4        Item 3  Type 3  green     2    5  2001
5        item 4  Type 1    red     2    5  2001
6        item 4  Type 2   blue     3  NaN  2001
7        item 4  Type 3  green     3  NaN  2001
8        Item 1  Type 1      -     3  NaN  2002
9        Item 2  Type 1      -     3  NaN  2002
10       Item 3  Type 1    red     3    5  2002
11       Item 3  Type 2   blue     3    5  2002
12       Item 3  Type 3  green     3    5  2002
13        Item4  Type 1    red     3  NaN  2002
14        Item4  Type 2   blue     3  NaN  2002
15        Item4  Type 3  green     3  NaN  2002
16       Item 1  Type 1      -     3  NaN  2003
17       Item 2  Type 1      -     3  NaN  2003
18       Item 3  Type 1    red     3    5  2003
19       Item 3  Type 2   blue     3    5  2003
20       Item 3  Type 3  green     3    5  2003
21        Item4  Type 1    red     3  NaN  2003
22        Item4  Type 2   blue     3  NaN  2003
23        Item4  Type 3  green     3  NaN  2003


问:
Android Shopify Mobile buy Version - 3.1.1 Retryhandler Error
Hi i am using below mentioned code for pulling order conformation. But i can't get Order ID and order details from this Query. Not able to get order id and order details even order confirmed.
Currently i am using shopify mobilebuysdk:buy3:3.1.1</p>

```<code>graphClient!!.queryGraph(query).enqueue(
    object : GraphCall.Callback<Storefront.QueryRoot> {
        override fun onResponse(@NonNull response: GraphResponse<Storefront.QueryRoot>) {

            if (response.data()!!.getNode() as Storefront.Checkout != null) {
                val checkout = response.data()!!.getNode() as Storefront.Checkout
                println("CheckOut : " + checkout)

                if (checkout != null) {

                    if (checkout.getOrder() != null) {
                        if (checkout.getOrder().getId().toString() != null) {
                            val orderId = checkout.getOrder().getId().toString()
                            println("Order ID : " + orderId)
                        }
                    }

                }

            }

        }

        override fun onFailure(@NonNull error: GraphError) {}
    }, null,
    RetryHandler.exponentialBackoff(1, TimeUnit.MILLISECONDS, 1.2f)
            .whenResponse<Storefront.QueryRoot> { response ->
                (response.data()?.getNode() as Storefront.Checkout).getOrder() == null
            }
            .maxCount(10)
            .build())
</code>```

答:
```<code>val checkoutId = ID(tinyDB!!.getString("New_checkoutID"))
    val query = Storefront.query({ rootQuery ->
        rootQuery
                .node(checkoutId, { nodeQuery ->
                    nodeQuery
                            .onCheckout({ checkoutQuery ->
                                checkoutQuery
                                        .order({ orderQuery ->
                                            orderQuery
                                                    .orderNumber()
                                                    .totalPrice()
                                                    .processedAt()
                                        }

                                        )
                            }
                            )
                }
                )
    }
    )

graphClient!!.queryGraph(query).enqueue(
            object : GraphCall.Callback<Storefront.QueryRoot> {
                override fun onResponse(@NonNull response: GraphResponse<Storefront.QueryRoot>) {
                    val checkout = response.data()!!.getNode() as Storefront.Checkout
                    val orderId = checkout.getOrder().getId().toString()
                }

                override fun onFailure(@NonNull error: GraphError) {}
            }, null,
            RetryHandler.exponentialBackoff(1, TimeUnit.MILLISECONDS, 1.2f)
                    .whenResponse<Storefront.QueryRoot>(
                            { response -> (response.data().getNode() as Storefront.Checkout).getOrder() == null }
                    )
                    .maxCount(10)
                    .build()
    )
</code>```

Body:
Hi i am using below mentioned code for pulling order conformation. But i can't get Order ID and order details from this Query. Not able to get order id and order details even order confirmed.
Currently i am using shopify mobilebuysdk:buy3:3.1.1

graphClient!!.queryGraph(query).enqueue(
    object : GraphCall.Callback<Storefront.QueryRoot> {
        override fun onResponse(@NonNull response: GraphResponse<Storefront.QueryRoot>) {

            if (response.data()!!.getNode() as Storefront.Checkout != null) {
                val checkout = response.data()!!.getNode() as Storefront.Checkout
                println("CheckOut : " + checkout)

                if (checkout != null) {

                    if (checkout.getOrder() != null) {
                        if (checkout.getOrder().getId().toString() != null) {
                            val orderId = checkout.getOrder().getId().toString()
                            println("Order ID : " + orderId)
                        }
                    }

                }

            }

        }

        override fun onFailure(@NonNull error: GraphError) {}
    }, null,
    RetryHandler.exponentialBackoff(1, TimeUnit.MILLISECONDS, 1.2f)
            .whenResponse<Storefront.QueryRoot> { response ->
                (response.data()?.getNode() as Storefront.Checkout).getOrder() == null
            }
            .maxCount(10)
            .build())


问:
Golang: forever channel
Just have a question, what is happening here?  </p>

```<code>forever := make(chan bool)

log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever
</code>```

答:
That code creates an unbuffered channel, and attempts to receive from it.

And since no one ever sends anything on it, it's essentially a blocking forever operation.

The purpose of this is to keep the goroutine from ending / returning, most likely because there are other goroutines which do some work concurrently or they wait for certain events or incoming messages (like your log message says).

And the need for this is that without this, the application might quit without waiting for other goroutines. Namely, if the main goroutine ends, the program ends as well. Quoting from Spec: Program execution:

Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete.

Check out this answer for similar and more techniques: Go project's main goroutine sleep forever?

For an introduction about channels, see What are channels used for?

Title: Golang: forever channel

Body:
Just have a question, what is happening here?

forever := make(chan bool)

log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever

ContentLicense: CC BY-SA 4.0


问:
  in String.Format(...) for currency
I use String.Format to do currency formatting. It works great, but I want a non-breaking space ( ) between the currency symbol (R) and the value so it doesn't wrap in small spaces, making it harder to read.

```<code><%=String.Format("{0:R #,###.00;(R #,###.00);R 0.00}", Model)%>
</code>```

where Model is a decimal.

How do I add   between R and #,###.00 without confusing the String.Format method?

ContentLicense: CC BY-SA 2.5

Title: in String.Format(...) for currency

Body:
I use String.Format to do currency formatting. It works great, but I want a non-breaking space ( ) between the currency symbol (R) and the value so it doesn't wrap in small spaces, making it harder to read.

<%=String.Format("{0:R #,###.00;(R #,###.00);R 0.00}", Model)%>

where Model is a decimal.

How do I add   between R and #,###.00 without confusing the String.Format method?

Body:
<%=String.Format("{0:R&nbsp;#,###.00;(R&nbsp;#,###.00);R&nbsp;0.00}", Model)%>

No?


问:
During servelt running in Tomcat Server( Local) in Intellij Json object can not be loaded
I have written one jsp and corrosponding servelt in Intellij and running it in Tomcat local server from Intellij. Now without json file if I pass some normal text as output the servlet is working fine,but with json object its showing

java.lang.NoClassDefFoundError: org/json/simple/JSONObject
    Servlet.UserInt.processRequest
---I have already imported json-simple -1,1.jar in external libraries so that its compiling but during servlet running it cant be loaded.
I also have created under web one folder named lib and have placed json and servet jar files there.

enter code here

UserInt.java---

```<code>public class UserInt extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
      processRequest(request,response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        processRequest(request,response);
    }

   /* @Override
    public String toString() {
        return "UserInt{} " + super.toString();
    }*/

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        response.setContentType("application/json");
        try{
            String query=request.getParameter("searchquery");
            JSONObject json = new JSONObject();

            json.put("query", query);
            json.put("country", "India");
            String output = json.toString();

            PrintWriter writer = response.getWriter();
           writer.write("output");
            writer.flush();
            writer.close();
       }
        catch (Exception e){
            e.printStackTrace();
        }

    }
}
</code>```

Index.jsp---

```<code> <form action="Servlet.UserInt" method="get" id="search-box">
    <input type="text" class="search" name="searchquery" size="20" maxlength="120" placeholder="search...">
    <input type="submit" class="button"value="Search">

    <div class="set-parameter"><h3>User-Requirements</h3>
      <i>Number of pages you want to see ?</i><input type="text" name="k" class="simple"/>
    </div>

[enter image description here][1]
  </form>
</code>```

Can anyone please help me to solve this error? Thanks in advance!!

答:
Check if correct org.json jar-file is imported.

I created simple project in IDEA with such dependencies in pom.xml:

```<code>  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>3.0.1</version>
    </dependency>

    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20160810</version>
    </dependency>

  </dependencies>

  <repositories>
    <repository>
      <id>maven-eu.nuxeo.org</id>
      <url>https://maven-eu.nuxeo.org/nexus/content/repositories/public-releases</url>
    </repository>
  </repositories>
</code>```

Servlet:

```<code>package servlets;
import org.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet ("/myservlet.do")
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        PrintWriter out = resp.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<h1>Hello Servlet Get</h1>");

        JSONObject json = new JSONObject();
        json.put("query", "query");
        json.put("country", "India");
        String output = json.toString();

        out.println(output);
        out.println("</body>");
        out.println("</html>");
    }
}
</code>```

Result:

```<code>Hello Servlet Get
{"country":"India","query":"query"}
</code>```

I run it on WildFly JBoss 10.2.0.Final

Body:
I have written one jsp and corrosponding servelt in Intellij and running it in Tomcat local server from Intellij. Now without json file if I pass some normal text as output the servlet is working fine,but with json object its showing

java.lang.NoClassDefFoundError: org/json/simple/JSONObject
    Servlet.UserInt.processRequest
---I have already imported json-simple -1,1.jar in external libraries so that its compiling but during servlet running it cant be loaded.
I also have created under web one folder named lib and have placed json and servet jar files there.

enter code here

UserInt.java---

public class UserInt extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
      processRequest(request,response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        processRequest(request,response);
    }

   /* @Override
    public String toString() {
        return "UserInt{} " + super.toString();
    }*/

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        response.setContentType("application/json");
        try{
            String query=request.getParameter("searchquery");
            JSONObject json = new JSONObject();

            json.put("query", query);
            json.put("country", "India");
            String output = json.toString();

            PrintWriter writer = response.getWriter();
           writer.write("output");
            writer.flush();
            writer.close();
       }
        catch (Exception e){
            e.printStackTrace();
        }

    }
}

Index.jsp---

 <form action="Servlet.UserInt" method="get" id="search-box">
    <input type="text" class="search" name="searchquery" size="20" maxlength="120" placeholder="search...">
    <input type="submit" class="button"value="Search">

User-Requirements

      Number of pages you want to see ?<input type="text" name="k" class="simple"/>

[enter image description here][1]
  </form>

Can anyone please help me to solve this error? Thanks in advance!!

Body:
Check if correct org.json jar-file is imported.

I created simple project in IDEA with such dependencies in pom.xml:

  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>3.0.1</version>
    </dependency>

    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20160810</version>
    </dependency>

  </dependencies>

  <repositories>
    <repository>
      <id>maven-eu.nuxeo.org</id>
      <url>https://maven-eu.nuxeo.org/nexus/content/repositories/public-releases</url>
    </repository>
  </repositories>

Servlet:

package servlets;
import org.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet ("/myservlet.do")
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        PrintWriter out = resp.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<h1>Hello Servlet Get</h1>");

        JSONObject json = new JSONObject();
        json.put("query", "query");
        json.put("country", "India");
        String output = json.toString();

        out.println(output);
        out.println("</body>");
        out.println("</html>");
    }
}

Result:

Hello Servlet Get
{"country":"India","query":"query"}

I run it on WildFly JBoss 10.2.0.Final


问:
Adjust layout images and size
I'm trying to adjust the images and size depending the page size to doesn't go outside the grid, but I couldn't make it.

I tried add theses lines below in CSS but it bugged the others images

img{
    width: 100%;
    max-width: 800px;
}
```

The content should adjust the size of the image, but it isn't working

The image going outside the grid:

You can see the live preview here

答:
I suggest if you are trying responsive design, use 50em; instead of 800px

They are both equal (except when window is resized.)

Title: Adjust layout images and size

Body:
I'm trying to adjust the images and size depending the page size to doesn't go outside the grid, but I couldn't make it.

I tried add theses lines below in CSS but it bugged the others images

img{
    width: 100%;
    max-width: 800px;
}

The content should adjust the size of the image, but it isn't working

The image going outside the grid:

You can see the live preview here


答:
Just give max-width for image to 100%</p>

```<code>img {
  max-width: 100%;
}
</code>```

Title: Adjust layout images and size

Body:
Just give max-width for image to 100%

img {
  max-width: 100%;
}


问:
Xcode 9 - iOS 11 UITableView rows are empty
Ever since the new iOS 11 update, I have an app that will show blank tableview rows on the simulator and device. Even the row separators will not show for any of the rows that are supposed to be there. If I change the simulator to an older iOS version, the rows will show fine. No changes to code or storyboard.

The rows still have the data, meaning I can tap on one of the blank rows and it will execute the code and contain the information I was expecting.

It appears that other scenes that I have where the tableview is placed on a view and I don't use the built in text label work fine. Just this tableview class using the built in text label.

Here is my code for the tableview class...

```<code>@interface BunkPickTableViewController ()

@end

@implementation BunkPickTableViewController

@synthesize appDelegate, delegate, bunkPassedValue;

- (void)viewDidLoad {

    [super viewDidLoad];

    UIView *backgroundView = [[UIView alloc] initWithFrame:self.view.bounds];

    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    CAGradientLayer *bgLayer = [BackgroundLayer tanGradient];
    bgLayer.frame = self.view.bounds;
    [self.view.layer insertSublayer:bgLayer atIndex:0];

    self.tableView.backgroundView = backgroundView;

    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];

    self.title = @"Bunk Codes";

}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    [[self navigationController] setNavigationBarHidden:NO animated:NO];

    [self.tableView reloadData];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [appDelegate.bunkArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

        cell.textLabel.textAlignment = NSTextAlignmentCenter;

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        cell.backgroundColor = [UIColor clearColor];

    }

    Bunk *bunkObj = [appDelegate.bunkArray objectAtIndex:indexPath.row];

    cell.textLabel.text = bunkObj.bunkId;

    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;

    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

    Bunk *bunkObj  = [appDelegate.bunkArray objectAtIndex:indexPath.row];

    [delegate dismissBunkPop:bunkObj.bunkId];

    [self.navigationController popViewControllerAnimated:YES];

}

@end
</code>```

TableView Settings Image

答:
```<code>CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.tableView.bounds;
gradient.colors = @[(id)[UIColor blackColor].CGColor, (id)[UIColor
                    grayColor].CGColor, (id)[UIColor
                    lightGrayColor].CGColor];

UIView *bgView = [[UIView alloc]
                          initWithFrame:self.tableView.bounds];
[self setBackgroundView:bgView];
[bgView.layer insertSublayer:gradient atIndex:0];

[self.tableView setBackgroundView:bgView];
</code>```

Setting gradient layer for tableview's background view solved the problem for me. Upto iOS 10 we can directly insert sublayer to tableView but in iOS 11 layer should be inserted to UITableVIew's background view only.

Body:
Ever since the new iOS 11 update, I have an app that will show blank tableview rows on the simulator and device. Even the row separators will not show for any of the rows that are supposed to be there. If I change the simulator to an older iOS version, the rows will show fine. No changes to code or storyboard.

The rows still have the data, meaning I can tap on one of the blank rows and it will execute the code and contain the information I was expecting.

It appears that other scenes that I have where the tableview is placed on a view and I don't use the built in text label work fine. Just this tableview class using the built in text label.

Here is my code for the tableview class...

@interface BunkPickTableViewController ()

@end

@implementation BunkPickTableViewController

@synthesize appDelegate, delegate, bunkPassedValue;

- (void)viewDidLoad {

    [super viewDidLoad];

    UIView *backgroundView = [[UIView alloc] initWithFrame:self.view.bounds];

    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    CAGradientLayer *bgLayer = [BackgroundLayer tanGradient];
    bgLayer.frame = self.view.bounds;
    [self.view.layer insertSublayer:bgLayer atIndex:0];

    self.tableView.backgroundView = backgroundView;

    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];

    self.title = @"Bunk Codes";

}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    [[self navigationController] setNavigationBarHidden:NO animated:NO];

    [self.tableView reloadData];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [appDelegate.bunkArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

        cell.textLabel.textAlignment = NSTextAlignmentCenter;

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        cell.backgroundColor = [UIColor clearColor];

    }

    Bunk *bunkObj = [appDelegate.bunkArray objectAtIndex:indexPath.row];

    cell.textLabel.text = bunkObj.bunkId;

    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;

    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

    Bunk *bunkObj  = [appDelegate.bunkArray objectAtIndex:indexPath.row];

    [delegate dismissBunkPop:bunkObj.bunkId];

    [self.navigationController popViewControllerAnimated:YES];

}

@end

TableView Settings Image

Body:
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.tableView.bounds;
gradient.colors = @[(id)[UIColor blackColor].CGColor, (id)[UIColor
                    grayColor].CGColor, (id)[UIColor
                    lightGrayColor].CGColor];

UIView *bgView = [[UIView alloc]
                          initWithFrame:self.tableView.bounds];
[self setBackgroundView:bgView];
[bgView.layer insertSublayer:gradient atIndex:0];

[self.tableView setBackgroundView:bgView];

Setting gradient layer for tableview's background view solved the problem for me. Upto iOS 10 we can directly insert sublayer to tableView but in iOS 11 layer should be inserted to UITableVIew's background view only.


问:
Do I need to delete an static std::map?
In some classes I have an static std::map with pointers inside. My question is if I need to delete at the end of the program or this memory is automatically freed. My concern is if the pointers stored inside are correctly deleted through our destructors when std::map is deleted.

Thanks.

答:
A memory "leak" is where memory is unintentionally not deleted over a period of time, and ends up reducing as the process continues. If it is a type of process that runs for a very long period of time, eg a server that is rarely restarted, this can be a major problem.

Memory leak detectors will pick up on any memory that is allocated and not deleted by a programming call, so valgrind, etc. will report this as a leak.

It is as well to check your code with programs like valgrind, and therefore the less that "gets in the way", the easier it will be to spot real leaks. Therefore my advice is not do just let the system clean up the memory, or singletons, etc, for you when you have allocated a pointer with new (or malloc or new[]).

You can have a "clean-up" routine to do this. Just have an object in the scope of your map that has a deleter (as it will be deleted when it exits) that will clean up the pointers in the map. As you need your object to be deleted first it should be declared later than the map.

Title: Do I need to delete an static std::map?


问:
ToggleButton image does not maintain aspect ratio
The two toggle buttons don't maintain aspect ratio. How can I make it a square? It shouldn't fill the width but just wrap it's content.

```<code>            <LinearLayout
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_marginTop="24dp"
                android:orientation="horizontal">

                <ToggleButton
                    android:id="@+id/btn1"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_weight="1"
                    android:textOff=""
                    android:scaleType="centerCrop"
                    android:textOn=""
                    android:layout_margin="8dp"
                    android:background="@drawable/feedback_btn_selector"
                    />

                <ToggleButton
                    android:id="@+id/btn2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_weight="1"
                    android:scaleType="centerCrop"
                    android:layout_margin="8dp"
                    android:background="@drawable/feedback_btn_selector" />
            </LinearLayout>
</code>```

feedback_btn_selector

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_pressed="true" android:drawable="@drawable/btn_average" />
    <item android:state_pressed="true" android:drawable="@drawable/btn_average"/>
    <item android:state_checked="true" android:drawable="@drawable/btn_average"/>
    <item android:drawable="@drawable/btn_average_selected"/>
</selector>
</code>```

drawable-xhdpi:

答: Either you can make small size of image as you want or make ToggleButton with fixed size.

Body:
The two toggle buttons don't maintain aspect ratio. How can I make it a square? It shouldn't fill the width but just wrap it's content.

            <LinearLayout
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_marginTop="24dp"
                android:orientation="horizontal">

                <ToggleButton
                    android:id="@+id/btn1"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_weight="1"
                    android:textOff=""
                    android:scaleType="centerCrop"
                    android:textOn=""
                    android:layout_margin="8dp"
                    android:background="@drawable/feedback_btn_selector"
                    />

                <ToggleButton
                    android:id="@+id/btn2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_weight="1"
                    android:scaleType="centerCrop"
                    android:layout_margin="8dp"
                    android:background="@drawable/feedback_btn_selector" />
            </LinearLayout>

feedback_btn_selector

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_pressed="true" android:drawable="@drawable/btn_average" />
    <item android:state_pressed="true" android:drawable="@drawable/btn_average"/>
    <item android:state_checked="true" android:drawable="@drawable/btn_average"/>
    <item android:drawable="@drawable/btn_average_selected"/>
</selector>

drawable-xhdpi:


问:
Eclipse Oxygen/Neon and groovy - is it possible?
4 years ago I wrote on Groovy using Eclipse and was happy. Later I used Groovy through IntelliJ or NetBeans. Now again I am supposed to work in Eclipse but I can and want to do many tests in Groovy.

The problem is that when I am trying to get any Groovy plugin from Eclipse Marketplace, Eclipse agrees to install the Groovy-Eclipse feature only with condition of uninstalling of virtually everything. These plugins are old, base on even older jars and are incompatible with contemporary plugins, basing on more modern jars. I am sorry if I am telling that wrong, I am trying up to my understanding of Eclipse plugins compatibility and creation.

I see three ways:

To forget Groovy and do tests on Java. But analyzing XML, HTML and JSON in java is much less convenient. I wouldn't like to go that way.

To load the Eclipse for plugin developers, the source code of Groovy plugin and recreate it with new jars. It is the most interesting way, but I am horrified by the amount of work - it will take weeks. Or more. And I need tests now.

To install some light Eclipse package that has Groovy. That would be fast. But I won't like to install some several years old version.

IMHO, I am not breaking the rules, for I am not asking for a tool. I am asking for a modern, correct and compatible combination of versions of the known tools - Eclipse and Groovy plugin.

Also, it is not a duplicate of the old questions, for I know how to work on Groovy on old versions of Eclipse. And I am asking about new versions - Oxygen or Neon.

I can see on the GitHub https://github.com/groovy/groovy-eclipse/wiki/Groovy-Eclipse-2.9.2-Release-Notes obviously the last version of groovy for Eclipse. But how can I add it to an Eclipse package? Not a way is given on the page. What is the sense of making an Eclipse plugin that does not support an import from Eclipse? Obviously, there should exist some way.

If I go to https://www.function1.com/2016/06/installing-eclipse-groovy-plugin, there is a version of Groovy for Mars. It agrees to be installed on Oxygen only on conditions of uninstalling maven and java. A bit too severe, isn't it?

答:
I'm using eclipse Oxygen Release (4.7.0) for groovy/gradle/grails projects with no huge problems. I started with "Eclipe IDE for Java Developers" and installed several packages afterwards.

Here's a list of "Installed software":

Buildship: Eclipse Plug-ins for Gradle   2.1.2.v20170807-1324    org.eclipse.buildship.feature.group Eclipse Buildship

Code Recommenders for Java Developers    2.4.9.v20170613-1301    org.eclipse.recommenders.rcp.feature.feature.group  Eclipse Code Recommenders

EclEmma Java Code Coverage   3.0.0.201706140232  org.eclipse.eclemma.feature.feature.group   Eclipse EclEmma

Eclipse IDE for Java Developers  4.7.0.20170620-1800 epp.package.java    Eclipse Packaging Project

Eclipse Java Development Tools   3.13.0.v20170612-0950   org.eclipse.jdt.feature.group   Eclipse.org

Eclipse Platform 4.7.0.v20170612-1255    org.eclipse.platform.feature.group  Eclipse.org

Eclipse Quicksearch  3.7.3.201602250752-RELEASE  org.springsource.ide.eclipse.commons.quicksearch.feature.feature.group  Pivotal Software, Inc.

Eclipse RCP  4.7.0.v20170612-1255    org.eclipse.rcp.feature.group   Eclipse.org

Eclipse Web Developer Tools  3.9.0.v201706011953 org.eclipse.wst.web_ui.feature.feature.group    Eclipse Web Tools Platform

Eclipse XML Editors and Tools    3.9.0.v201706011851 org.eclipse.wst.xml_ui.feature.feature.group    Eclipse Web Tools Platform

Git integration for Eclipse  4.8.0.201706111038-r    org.eclipse.egit.feature.group  Eclipse EGit

Groovy Compiler 2.4  2.9.2.xx-201711060326-e47   org.codehaus.groovy24.feature.feature.group Codehaus.org

Groovy-Eclipse Feature   2.9.2.xx-201711060326-e47   org.codehaus.groovy.eclipse.feature.feature.group   Codehaus.org

Java implementation of Git   4.8.0.201706111038-r    org.eclipse.jgit.feature.group  Eclipse JGit

JavaScript Development Tools 2.1.0.v201706011953 org.eclipse.wst.jsdt.feature.feature.group  Eclipse Web Tools Platform

JDT Core patch for Groovy-Eclipse plugin on Eclipse 4.7  2.9.2.xx-201711060326-e47   org.codehaus.groovy.jdt.patch.feature.group Codehaus.org

Jspresso Developer Studio Spock tests feature    3.0.7.201611272038  org.jspresso.contrib.sjsplugin.spock.feature.feature.group  Maxime HAMM

Oomph Setup  1.9.0.v20170706-0615    org.eclipse.oomph.setup.feature.group   Eclipse Oomph Project

YEdit Feature    1.0.20.201509041456-RELEASE org.dadacoalition.yedit.feature.feature.group   YEdit Project

A couple of them can definitely be deleted.


问:
I am trying to use PassportJs with multiple types of users (each one has a different model). What am I doing wrong?
I am trying to use PassportJs with express using multiple types of users (each one has a different model).
When I use it with only one type of user it is OK but when I add a second one it is not working. Any idea ?

```<code>// Configuring Passport
var passport = require ('passport');

var LocalStrategyAdmin = require ('passport-local').Strategy;
var LocalStrategyClient = require ('passport-local').Strategy;

var adminModel = require ('./models/adminModel');
var clientModel = require ('./models/clientModel');

var session = require ('cookie-session');

app.use (session ({keys: [secretKey1, secretKey2]}));

app.use (passport.initialize ());
app.use (passport.session ());

passport.use (new LocalStrategyAdmin (adminModel.authenticate ()));
passport.use (new LocalStrategyClient (clientModel.authenticate ()));

passport.serializeUser (adminModel.serializeUser ());
passport.deserializeUser (adminModel.deserializeUser ());

passport.serializeUser (clientModel.serializeUser ());
passport.deserializeUser (clientModel.deserializeUser ());
</code>```

I fixed it

I had to give distinct names for each local strategy

I had to serialize/deserialize depending on the type of the user (client or admin in my case).

答:
you also want to use separate instances of passport</p>

```<code>var Passport = require ('passport');
var passportAdmin = new Passport.Passport();
var passportClient = new Passport.Passport();
</code>```

Body:
I am trying to use PassportJs with express using multiple types of users (each one has a different model).
When I use it with only one type of user it is OK but when I add a second one it is not working. Any idea ?

// Configuring Passport
var passport = require ('passport');

var LocalStrategyAdmin = require ('passport-local').Strategy;
var LocalStrategyClient = require ('passport-local').Strategy;

var adminModel = require ('./models/adminModel');
var clientModel = require ('./models/clientModel');

var session = require ('cookie-session');

app.use (session ({keys: [secretKey1, secretKey2]}));

app.use (passport.initialize ());
app.use (passport.session ());

passport.use (new LocalStrategyAdmin (adminModel.authenticate ()));
passport.use (new LocalStrategyClient (clientModel.authenticate ()));

passport.serializeUser (adminModel.serializeUser ());
passport.deserializeUser (adminModel.deserializeUser ());

passport.serializeUser (clientModel.serializeUser ());
passport.deserializeUser (clientModel.deserializeUser ());

I fixed it

I had to give distinct names for each local strategy

I had to serialize/deserialize depending on the type of the user (client or admin in my case).

Body:
you also want to use separate instances of passport

var Passport = require ('passport');
var passportAdmin = new Passport.Passport();
var passportClient = new Passport.Passport();


问:
Closes SFSafariViewController on a certain url
I am trying to close SFSafariViewController when I reach a certain page.

But I am unable to do it until the "Done" button is pressed explicitly
  by the user.

What I want is to get the URL as soon as it reached a certain page and then dismiss the view controller.
Then I can pick the rest using this

```<code>func safariViewControllerDidFinish(_ controller: SFSafariViewController){
    // do work here
}
</code>```

Note: This question has been asked before but I was unable to find any
  satisfactory answers

答:
You cannot do that with a SFSafariViewController. Use a WKWebView instead and implement the WKNavigationDelegate method like optional func webView(_ webView: WKWebView,
            didFinish navigation: WKNavigation!) and then read the current URL. Define your action based on that.

You can use this to close the view controller that houses your web view. You will unfortunately have to build your own navigation buttons (the ones the SFSafariViewController has), if you want to allow the user access to those. You don't have to provide them.

Body:
I am trying to close SFSafariViewController when I reach a certain page.

But I am unable to do it until the "Done" button is pressed explicitly
  by the user.

What I want is to get the URL as soon as it reached a certain page and then dismiss the view controller.
Then I can pick the rest using this

func safariViewControllerDidFinish(_ controller: SFSafariViewController){
    // do work here
}

Note: This question has been asked before but I was unable to find any
  satisfactory answers


问:
How to make a Popup with proper shadow and arrow in WPF?
I want a popup in WPF something like in below image:

I have implemented it using CSS.
So is it possible to build slimier popup using XAML?

I have tried to implement it using XAML but shadow is being in all direction.

答:
So I have researched little bit to solve it as requirement. This is little complex but yes this is completely working.

First of all make a Style

```<code><Style x:Key="PopupContentStyle" TargetType="ContentControl">
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ContentControl}">
                        <!--main grid 8px wider than actual size of popup to create shadow effect-->
                        <Grid Background="Transparent"
                              Width="{Binding ActualWidth, ConverterParameter='+,8', Converter={StaticResource WidthHeightExtender}, ElementName=mainGrid, Mode=OneWay}"
                              Height="{Binding ActualHeight, ConverterParameter='+,8', Converter={StaticResource WidthHeightExtender}, ElementName=mainGrid}">
                            <!--below is the grid to create blur effect which will looks like shadow after putting another grid on top of this-->
                            <Grid VerticalAlignment="Center" HorizontalAlignment="Center"
                                  Width="{Binding ActualWidth, ElementName=mainGrid}"
                                  Height="{Binding ActualHeight, ElementName=mainGrid}">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="*"/>
                                    <!--12px for arrow-->
                                    <RowDefinition Height="12"/>
                                </Grid.RowDefinitions>
                                <!--a box with blur effect for shadow-->
                                <Grid Background="Black" Opacity=".2" VerticalAlignment="Top" Width="{Binding ActualWidth, ElementName=mainGrid}"
                                      Height="{Binding ActualHeight, ConverterParameter='-,12', Converter={StaticResource WidthHeightExtender}, ElementName=mainGrid, Mode=OneWay}">
                                    <Grid.Effect>
                                        <BlurEffect Radius="8"/>
                                    </Grid.Effect>
                                </Grid>
                                <!--path which is a arrow with blur effect for shadow-->
                                <Path Grid.Row="1" Opacity=".25" Data="M 0 0 12 12 L 24 0 Z" Fill="Black" Margin="25,0,0,0" HorizontalAlignment="Left">
                                    <Path.Effect>
                                        <BlurEffect Radius="8"/>
                                    </Path.Effect>
                                </Path>
                            </Grid>
                            <!--below is similer grid as above without any blur effect so that we can hide blur in side the contentpresenter-->
                            <Grid Name="Mask" VerticalAlignment="Center" HorizontalAlignment="Center" Background="Transparent"
                                  Width="{Binding ActualWidth, ElementName=mainGrid}"
                                  Height="{Binding ActualHeight, ElementName=mainGrid}">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="*"/>
                                    <RowDefinition Height="12"/>
                                </Grid.RowDefinitions>
                                <Grid Background="#FFFFFF" VerticalAlignment="Top" Width="{Binding ActualWidth, ElementName=mainGrid}"
                                      Height="{Binding ActualHeight, ConverterParameter='-,12', Converter={StaticResource WidthHeightExtender}, ElementName=mainGrid, Mode=OneWay}">
                                </Grid>
                                <!--margin's left value is 25 that means arrow is 25 px away fro left-->
                                <Path Grid.Row="1" Data="M 0 0 12 12 L 24 0 Z" Fill="#FFFFFF" Margin="25,0,0,0" HorizontalAlignment="Left"/>
                            </Grid>

                            <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,4,0,16">
                                <!--if you want visualBrush then uncomment below's code and remove margin from ContentPresenter-->
                                <!--<ContentPresenter.OpacityMask >
                                    <VisualBrush  Visual="{Binding ElementName=Mask}" AlignmentX="Left" AlignmentY="Top" Stretch="None"/>
                                </ContentPresenter.OpacityMask>-->
                            </ContentPresenter>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
</code>```

In above style there is three part of it. First: 8px extended grid by width and height and I am bluring it to make looks like shadow. Second: Grid of required height and width to hide extra blured part. Third: ContentPresenter

Since I have used a custom converter so here is code:

```<code>/// <summary>
    /// Author: Suman Kumar
    /// It will increase or decrease width and height of any conrol
    /// Parameter should be like: "+,12"
    /// + is indicating increase and 12 is indicating length will be increased by 12 px
    /// </summary>
    public class WidthHeightExtender: IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                string []str = (parameter as string).Split(',');
                if (str[0].Equals("+"))
                    return System.Convert.ToDouble(value) + System.Convert.ToDouble(str[1]);
                else if (str[0].Equals("-"))
                    return System.Convert.ToDouble(value) - System.Convert.ToDouble(str[1]);
                else
                    return System.Convert.ToDouble(value);
            }
            catch(Exception ex)
            {
                return System.Convert.ToDouble(value);
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion

    }
</code>```

And lastly how to apply style to popup:

```<code><Popup>
        <ContentControl Name="popupMain"  Style="{DynamicResource PopupContentStyle}">

                <Grid Name="mainGrid" Width="255" Height="333" Background="#FFFFFF">
    <!-- Your content will we here-->
    <!-- Name="mainGrid": This is very impotent to give name as "mainGrid" because I am using it in style to fetch height and width of grid.-->
            </Grid>
        </ContentControl>
</Popup>
</code>```

This is the way We can archive a symmetric shadow effect in any content.

Body:
So I have researched little bit to solve it as requirement. This is little complex but yes this is completely working.

First of all make a Style

<Style x:Key="PopupContentStyle" TargetType="ContentControl">
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ContentControl}">
                        <!--main grid 8px wider than actual size of popup to create shadow effect-->
                        <Grid Background="Transparent"
                              Width="{Binding ActualWidth, ConverterParameter='+,8', Converter={StaticResource WidthHeightExtender}, ElementName=mainGrid, Mode=OneWay}"
                              Height="{Binding ActualHeight, ConverterParameter='+,8', Converter={StaticResource WidthHeightExtender}, ElementName=mainGrid}">
                            <!--below is the grid to create blur effect which will looks like shadow after putting another grid on top of this-->
                            <Grid VerticalAlignment="Center" HorizontalAlignment="Center"
                                  Width="{Binding ActualWidth, ElementName=mainGrid}"
                                  Height="{Binding ActualHeight, ElementName=mainGrid}">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="*"/>
                                    <!--12px for arrow-->
                                    <RowDefinition Height="12"/>
                                </Grid.RowDefinitions>
                                <!--a box with blur effect for shadow-->
                                <Grid Background="Black" Opacity=".2" VerticalAlignment="Top" Width="{Binding ActualWidth, ElementName=mainGrid}"
                                      Height="{Binding ActualHeight, ConverterParameter='-,12', Converter={StaticResource WidthHeightExtender}, ElementName=mainGrid, Mode=OneWay}">
                                    <Grid.Effect>
                                        <BlurEffect Radius="8"/>
                                    </Grid.Effect>
                                </Grid>
                                <!--path which is a arrow with blur effect for shadow-->
                                <Path Grid.Row="1" Opacity=".25" Data="M 0 0 12 12 L 24 0 Z" Fill="Black" Margin="25,0,0,0" HorizontalAlignment="Left">
                                    <Path.Effect>
                                        <BlurEffect Radius="8"/>
                                    </Path.Effect>
                                </Path>
                            </Grid>
                            <!--below is similer grid as above without any blur effect so that we can hide blur in side the contentpresenter-->
                            <Grid Name="Mask" VerticalAlignment="Center" HorizontalAlignment="Center" Background="Transparent"
                                  Width="{Binding ActualWidth, ElementName=mainGrid}"
                                  Height="{Binding ActualHeight, ElementName=mainGrid}">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="*"/>
                                    <RowDefinition Height="12"/>
                                </Grid.RowDefinitions>
                                <Grid Background="#FFFFFF" VerticalAlignment="Top" Width="{Binding ActualWidth, ElementName=mainGrid}"
                                      Height="{Binding ActualHeight, ConverterParameter='-,12', Converter={StaticResource WidthHeightExtender}, ElementName=mainGrid, Mode=OneWay}">
                                </Grid>
                                <!--margin's left value is 25 that means arrow is 25 px away fro left-->
                                <Path Grid.Row="1" Data="M 0 0 12 12 L 24 0 Z" Fill="#FFFFFF" Margin="25,0,0,0" HorizontalAlignment="Left"/>
                            </Grid>

                            <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,4,0,16">
                                <!--if you want visualBrush then uncomment below's code and remove margin from ContentPresenter-->
                                <!--<ContentPresenter.OpacityMask >
                                    <VisualBrush  Visual="{Binding ElementName=Mask}" AlignmentX="Left" AlignmentY="Top" Stretch="None"/>
                                </ContentPresenter.OpacityMask>-->
                            </ContentPresenter>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

In above style there is three part of it. First: 8px extended grid by width and height and I am bluring it to make looks like shadow. Second: Grid of required height and width to hide extra blured part. Third: ContentPresenter

Since I have used a custom converter so here is code:

/// <summary>
    /// Author: Suman Kumar
    /// It will increase or decrease width and height of any conrol
    /// Parameter should be like: "+,12"
    /// + is indicating increase and 12 is indicating length will be increased by 12 px
    /// </summary>
    public class WidthHeightExtender: IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                string []str = (parameter as string).Split(',');
                if (str[0].Equals("+"))
                    return System.Convert.ToDouble(value) + System.Convert.ToDouble(str[1]);
                else if (str[0].Equals("-"))
                    return System.Convert.ToDouble(value) - System.Convert.ToDouble(str[1]);
                else
                    return System.Convert.ToDouble(value);
            }
            catch(Exception ex)
            {
                return System.Convert.ToDouble(value);
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion

    }

And lastly how to apply style to popup:

<Popup>
        <ContentControl Name="popupMain"  Style="{DynamicResource PopupContentStyle}">

                <Grid Name="mainGrid" Width="255" Height="333" Background="#FFFFFF">
    <!-- Your content will we here-->
    <!-- Name="mainGrid": This is very impotent to give name as "mainGrid" because I am using it in style to fetch height and width of grid.-->
            </Grid>
        </ContentControl>
</Popup>

This is the way We can archive a symmetric shadow effect in any content.


问:
How to validate CSV file for no. of rows and columns?
I am trying to ascertain that the data file that is fed to my app has certain no of columns so that it doesn't fail in the application. Also I want to count number of rows and check that same number of rows is loaded to DB.

I also need to check that each row is containing a same number of columns.

I tried to write it as below but still struggling with the result.

```<code>Dim objFSO, dataArray, clippedArray
Set objFSO = CreateObject("Scripting.FileSystemObject")

'Create an array out of the CSV

'open the data file
Set oTextStream = objFSO.OpenTextFile("C:\Users\ds\Desktop\Quota\new_file.csv")
Set newFile = objFSO.CreateTextFile("C:\Users\ds\Desktop\loginfo.txt")
'make an array from the data file
dataArray = Split(oTextStream.ReadAll, vbNewLine)
'close the data file
oTextStream.Close
WScript.Echo "No. of Rows is " & UBound(dataArray)

For Each strLine In dataArray
    'Now make an array from each line
    clippedArray =  Split(strLine,"|")
    lngHowManyColumns = UBound(clippedArray)
    WScript.Echo UBound(clippedArray)

Next
WScript.Echo "No. of Columns is " & lngHowManyColumns

WScript.Echo "Done"
</code>```

Edited to make more sense as few experts were not able to understand the question, however it has been already answered below.

Thanks

答:
Keep it simple: Loop over the rows, check for field seps in each row via Split:

```<code>Option Explicit

Const csFSpec = "..\data\47261155.csv"
Const csFSep = ","
Const cnCols = 3    ' one less to optimize for UBound()!
Const cnRows = 6    ' one more to optimize for .Line

Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
Dim oTS : Set oTS = goFS.OpenTextFile(csFSpec)
Dim sL, nC
Do Until oTS.AtEndOfStream
   sL = oTS.ReadLine()
   nC = UBound(Split(sL, csFSep))
   If cnCols <> nC Then
      WScript.Echo "Col Error in line", oTS.Line - 1 & ":", cnCols, "<>", nC, "(" & sL & ")"
   End If
Loop
If cnRows <> oTS.Line Then
   WScript.Echo "Row Error: ", cnRows, "<>", oTS.Line
End If
oTS.Close
WScript.Echo "no news is good news"
</code>```

output:

type ..\data\47261155.csv
1,2,3,4
4,3,2,1
1,2,3,4,5
1,2,3
1,2,3,4
1,2,3,4

cscript 47261155.vbs
Col Error in line 3: 3 <> 4 (1,2,3,4,5)
Col Error in line 4: 3 <> 2 (1,2,3)
Row Error:  6 <> 7
no news is good news
```

Body:
I am trying to ascertain that the data file that is fed to my app has certain no of columns so that it doesn't fail in the application. Also I want to count number of rows and check that same number of rows is loaded to DB.

I also need to check that each row is containing a same number of columns.

I tried to write it as below but still struggling with the result.

Dim objFSO, dataArray, clippedArray
Set objFSO = CreateObject("Scripting.FileSystemObject")

'Create an array out of the CSV

'open the data file
Set oTextStream = objFSO.OpenTextFile("C:\Users\ds\Desktop\Quota\new_file.csv")
Set newFile = objFSO.CreateTextFile("C:\Users\ds\Desktop\loginfo.txt")
'make an array from the data file
dataArray = Split(oTextStream.ReadAll, vbNewLine)
'close the data file
oTextStream.Close
WScript.Echo "No. of Rows is " & UBound(dataArray)

For Each strLine In dataArray
    'Now make an array from each line
    clippedArray =  Split(strLine,"|")
    lngHowManyColumns = UBound(clippedArray)
    WScript.Echo UBound(clippedArray)

Next
WScript.Echo "No. of Columns is " & lngHowManyColumns

WScript.Echo "Done"

Edited to make more sense as few experts were not able to understand the question, however it has been already answered below.

Thanks

Body:
Keep it simple: Loop over the rows, check for field seps in each row via Split:

Option Explicit

Const csFSpec = "..\data\47261155.csv"
Const csFSep = ","
Const cnCols = 3    ' one less to optimize for UBound()!
Const cnRows = 6    ' one more to optimize for .Line

Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
Dim oTS : Set oTS = goFS.OpenTextFile(csFSpec)
Dim sL, nC
Do Until oTS.AtEndOfStream
   sL = oTS.ReadLine()
   nC = UBound(Split(sL, csFSep))
   If cnCols <> nC Then
      WScript.Echo "Col Error in line", oTS.Line - 1 & ":", cnCols, "<>", nC, "(" & sL & ")"
   End If
Loop
If cnRows <> oTS.Line Then
   WScript.Echo "Row Error: ", cnRows, "<>", oTS.Line
End If
oTS.Close
WScript.Echo "no news is good news"

output:

type ..\data\47261155.csv
1,2,3,4
4,3,2,1
1,2,3,4,5
1,2,3
1,2,3,4
1,2,3,4

cscript 47261155.vbs
Col Error in line 3: 3 <> 4 (1,2,3,4,5)
Col Error in line 4: 3 <> 2 (1,2,3)
Row Error:  6 <> 7
no news is good news


问:
Set GNOME terminal window title in Python?
How can I set the window title of a GNOME terminal from Python?

I am running several python scripts from different terminals. I would like that the python script, once executed, automatically set the window title to some status text that I can modify from within the script.

答:
The accepted answer was wrong for Python3. This works on Python >= 3.6:

```<code>terminal_title = "title you want"
print(f'\33]0;{terminal_title}\a', end='', flush=True)
</code>```

The flush is essential; See comments.

I also do not recommend checking if os.environ['TERM'] == 'xterm' like another answer does because some terminals fail that check even though they support the OSC escape code:

```<code>[navin@Radiant ~]$ echo $TERM
xterm-256color
[navin@Radiant ~]$ echo $TERM_PROGRAM
iTerm.app
</code>```

Body:
The accepted answer was wrong for Python3. This works on Python >= 3.6:

terminal_title = "title you want"
print(f'\33]0;{terminal_title}\a', end='', flush=True)

The flush is essential; See comments.

I also do not recommend checking if os.environ['TERM'] == 'xterm' like another answer does because some terminals fail that check even though they support the OSC escape code:

[navin@Radiant ~]$ echo $TERM
xterm-256color
[navin@Radiant ~]$ echo $TERM_PROGRAM
iTerm.app


问:
Unable to create call adapter in retrofit 2.0.0
I am trying to integrate retrofit 2.0.0-beta in to my app.

```<code>{
     "success":true,
     "categoryDetails":[
    {
        "topicId":550,
        "categoryName":"Classshshs",
    “categoryImageUrl” : “http://s3-apdd-southeast-1.amazonaws.com/tv-dev/member/photo/883191-medium130.jpg”,
    },
    {
    "topicId":550661,
        "categoryName":"Cricket sss",
    “categoryImageUrl” : “http://s3-apdd-southeast-1.amazonaws.com/tv-dev/member/photo/883191-medium130.jpg”,
    }

   ],
   "totalCategoryCount":2
}
</code>```

My rest adapter

```<code>Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://s3-ap-southeast-1.amazonaws.com").
                    addConverterFactory(GsonConverterFactory.create())
            .build();

    service=retrofit.create(RetrofitService.class);
</code>```

My Call method

```<code>Call<Object> call=service.listRs();
    call.enqueue(new Callback<Object>() {
        @Override
        public void onResponse(Response<Object> response) {
            Log.e(TAG,"sucess"+response.toString());

        }

        @Override
        public void onFailure(Throwable t) {

        }
    });

Caused by: java.lang.IllegalArgumentException: Unable to create call adapter for interface retrofit.Call
for method RetrofitService.listRs
        at retrofit.Utils.methodError(Utils.java:201)
        at retrofit.MethodHandler.createCallAdapter(MethodHandler.java:51)
        at retrofit.MethodHandler.create(MethodHandler.java:29)
        at retrofit.Retrofit.loadMethodHandler(Retrofit.java:138)
        at retrofit.Retrofit$1.invoke(Retrofit.java:127)
        at java.lang.reflect.Proxy.invoke(Proxy.java:397)
        at $Proxy1.listRs(Unknown Source)
</code>```

答:
Try this in gradle</p>

```<code>compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.okhttp3:okhttp:3.8.1'
</code>```

Body:
I am trying to integrate retrofit 2.0.0-beta in to my app.

{
     "success":true,
     "categoryDetails":[
    {
        "topicId":550,
        "categoryName":"Classshshs",
    “categoryImageUrl” : “http://s3-apdd-southeast-1.amazonaws.com/tv-dev/member/photo/883191-medium130.jpg”,
    },
    {
    "topicId":550661,
        "categoryName":"Cricket sss",
    “categoryImageUrl” : “http://s3-apdd-southeast-1.amazonaws.com/tv-dev/member/photo/883191-medium130.jpg”,
    }

   ],
   "totalCategoryCount":2
}

My rest adapter

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://s3-ap-southeast-1.amazonaws.com").
                    addConverterFactory(GsonConverterFactory.create())
            .build();

    service=retrofit.create(RetrofitService.class);

My Call method

Call<Object> call=service.listRs();
    call.enqueue(new Callback<Object>() {
        @Override
        public void onResponse(Response<Object> response) {
            Log.e(TAG,"sucess"+response.toString());

        }

        @Override
        public void onFailure(Throwable t) {

        }
    });

Caused by: java.lang.IllegalArgumentException: Unable to create call adapter for interface retrofit.Call
for method RetrofitService.listRs
        at retrofit.Utils.methodError(Utils.java:201)
        at retrofit.MethodHandler.createCallAdapter(MethodHandler.java:51)
        at retrofit.MethodHandler.create(MethodHandler.java:29)
        at retrofit.Retrofit.loadMethodHandler(Retrofit.java:138)
        at retrofit.Retrofit$1.invoke(Retrofit.java:127)
        at java.lang.reflect.Proxy.invoke(Proxy.java:397)
        at $Proxy1.listRs(Unknown Source)

Body:
Try this in gradle

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.okhttp3:okhttp:3.8.1'


问:
How to cache data for external API calls on Firebase or any custom server backend?
Im developing a React app which has a dashboard and other fields which display data from a 3rd Party API. I also have mobile apps(React Native and iOS) which also need to display the SAME data.
Since the 3rd party API has limits on the calls, if I have 1000 users, and I query the 3rd party API from the 1000 clients(client side invocation), I will reach that limit very quickly. My intention is to make API calls on the firebase database and then update the database every 30 minutes. So even if I have 1000 or 100 users, they will be hitting the firebase server for fetching data which in turn would be holding the cached data(A JSON object).
Is there a way I can do this using Firebase? Or heroku? Which is the preferred way to solve this issue?</p>

答:
You could create your own API with Firebase Functions and make that API do the requests to the 3rd party API and cache the results for 'x' time or write them to your Firebase Database using the Admin SDK.

Then your users will be able to fetch that data directly from your database without ever touching the 3rd party API.

Here you have a videotutorial from Firebase on how to create a Node.js app (hosting and functions). Functions section of the video is what you are looking for.

Hope it helps! :)


问:
Compile errors with templates and new/delete operators (C++)
I'm trying to build a vector-style class and in order to use templates as well as the new, delete operators I have this piece of code:

```<code>template <class type2> class storage
{
         private:
                 type2 *organs;
         public:
                int num;
                storage(); //constructor
                ~storage(); //destructor
                void operator+(type2 newone);
                void operator-(int howmany);
                type2 operator[](int place);
};

storage<class type2>:: ~storage()
{
          delete[] organs; //~~~~~~~Error number 1~~~~~~~~~~
}

void storage<class type2>:: operator+(type2 newone)
{ //                        ~~~~~~~~~~~Error number 2~~~~~~~~~~~~~~
     organs = new type2[1];
     num++;
     oragns[num-1] = newone;
}
</code>```

The compiler (Dev C++) writes this error on Error number 1:

invalid use of undefined type `struct
  type2'

And this error on Error Number 2:

`newone' has incomplete type

However, I don't understand what's wrong. Any hints?

答:
You need to specify what template you are using for those methods or move the function implementation into the class.

```<code>template <class type2>
storage<class type2>:: ~storage()
{
      delete[] organs;
}
</code>```

Probably the easiest solution.  The same should work for your second error as well.

EDIT:

Found a nice template tutorial which covers this, among other things.

http://www.cplusplus.com/doc/tutorial/templates/

Body:
I'm trying to build a vector-style class and in order to use templates as well as the new, delete operators I have this piece of code:

template <class type2> class storage
{
         private:
                 type2 *organs;
         public:
                int num;
                storage(); //constructor
                ~storage(); //destructor
                void operator+(type2 newone);
                void operator-(int howmany);
                type2 operator[](int place);
};

storage<class type2>:: ~storage()
{
          delete[] organs; //~~~~~~~Error number 1~~~~~~~~~~
}

void storage<class type2>:: operator+(type2 newone)
{ //                        ~~~~~~~~~~~Error number 2~~~~~~~~~~~~~~
     organs = new type2[1];
     num++;
     oragns[num-1] = newone;
}

The compiler (Dev C++) writes this error on Error number 1:

invalid use of undefined type `struct
  type2'

And this error on Error Number 2:

`newone' has incomplete type

However, I don't understand what's wrong. Any hints?

Body:
You need to specify what template you are using for those methods or move the function implementation into the class.

template <class type2>
storage<class type2>:: ~storage()
{
      delete[] organs;
}

Probably the easiest solution.  The same should work for your second error as well.

EDIT:

Found a nice template tutorial which covers this, among other things.

http://www.cplusplus.com/doc/tutorial/templates/


问:
how to separating the matching points in optical flow?
I'm using calcOpticalFlowPyrLK() function to track feature points. I'd like to separate matching only points from the results using the status vector resulted from calcOpticalFlowPyrLK().

The documentation from opencv page says,

output status vector (of unsigned chars); each element of the vector
  is set to 1 if the flow for the corresponding features has been found,
  otherwise, it is set to 0.

But when printed the status vector before implementation, I found that the status vector size is larger and 1s and 0s are scattered even after the array passes the size of feature points tracked.

If my tracked points vector size is 65, the status vector size is 100 and 1s and 0s are there even after status[64].

Will be help full if someone can help me out to get the right points only.

Thank You.

答:
Status vector should be of the same size as the feature vector.
If you see a size mismatch - please share the code you are using.

Here us how you can use it to filter out the "bad" features:

```<code> calcOpticalFlowPyrLK(gray_1, gray_2, features_1, features_2, status, err,
    wins_size, max_level, term_crit);

  // filter points with bad status
  size_t i, k;
  for( i = k = 0; i < features_2.size(); i++ ){
    if (!status[i]) continue;
    features_1[k] = features_1[i];
    features_2[k] = features_2[i];
    err[k] = err[i];
    k++;
  }
  features_1.resize(k);
  features_2.resize(k);
  err.resize(k);
</code>```

Body:
Status vector should be of the same size as the feature vector.
If you see a size mismatch - please share the code you are using.

Here us how you can use it to filter out the "bad" features:

 calcOpticalFlowPyrLK(gray_1, gray_2, features_1, features_2, status, err,
    wins_size, max_level, term_crit);

  // filter points with bad status
  size_t i, k;
  for( i = k = 0; i < features_2.size(); i++ ){
    if (!status[i]) continue;
    features_1[k] = features_1[i];
    features_2[k] = features_2[i];
    err[k] = err[i];
    k++;
  }
  features_1.resize(k);
  features_2.resize(k);
  err.resize(k);


问:
How do I explain to the user of my class the expected type of one of its attributes?
I'm developing a class in Python, in which one of its attributes is supposed to represent a neural network. I would like this attribute to actually be an instance of another class, let's call it NN, with several methods (like train() for training, predict() for prediction, etc.). Furthermore, I thought a reasonable way to initialize this attribute was by using my class' constructor, which would expect an instance of the NN class as one of its arguments.

My first thought on how to solve this was to implement an interface, and then type check whatever it is that the user supplies to my class constructor, in order to make sure it is from the expected NN class. However, it seems like neither interfaces (1) nor typechecking (2, 3, 4, 5) are good practices in Python.

Instead, we're supposed to use Duck typing, and simply try using the objects methods until we can't (i.e. defer type checking to runtime). However, in my case the NN class might be quite complicated, with several methods and attributes. If I do discard the interface idea, and simply expect the user of my class to provide an object with all the necessary methods and attributes, how will he/she know what is expected of this object? Should I write all this information in my class docstring, in my constructor docstring, or somewhere else? Or is there a better way to solve this scenario?

答:
I would say the __init__ docstring is the place you want to put it in, since that's where the NN object will be provided.

Something like:

```<code>"""
(...)
:param NN: an object supporting run(), train() and validate() methods
(...)
"""
</code>```

The advantage here is that you can supply anything as an argument - hell, you could write a NN argument that's not even a class but a function, or a modified instance of a builtin, or other crazy things like that - and as long as the user provides something that runs correctly, it will work as your neural network.

Body:
I would say the __init__ docstring is the place you want to put it in, since that's where the NN object will be provided.

Something like:

"""
(...)
:param NN: an object supporting run(), train() and validate() methods
(...)
"""

The advantage here is that you can supply anything as an argument - hell, you could write a NN argument that's not even a class but a function, or a modified instance of a builtin, or other crazy things like that - and as long as the user provides something that runs correctly, it will work as your neural network.


问:
Get current header of the tabView PrimeNG
I'd like to get current header of the PrimeNG tabView. I tried to do it by binding activeIndex property but it didn't work.</p>

答:
You can get a reference to your tabView in your component using @ViewChild and bind to a variable the selectedIndex then you can get the header of selected tavview this.tabView.tabs[this.selectedIndex].header.

Below a sample code:
app.component.ts

```<code>import { Component, ViewChild } from '@angular/core';
//imports
import {TabView, TabPanel} from 'primeng/primeng';

@Component({
  selector: 'my-app',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  selectedIndex = 0;
  //class variable
  @ViewChild(TabView) tabView: TabView;

  onChange($event) {
    this.selectedIndex = $event.index;
  }

  getSelectedHeader(){
    console.log(this.tabView.tabs[this.selectedIndex].header);
  }
}
</code>```

app.component.html

```<code><h2>PrimeNG Issue Template</h2>
<button pButton (click)="getSelectedHeader()" label="selected header"></button>
<p-tabView (onChange)="onChange($event)" [activeIndex]="selectedIndex">
  <p-tabPanel header="first" [selected]="true">
    <first></first>

  </p-tabPanel>
  <p-tabPanel header="second" cache="false">
    <ng-template pTemplate="content">
      <second></second>
    </ng-template>
  </p-tabPanel>
</p-tabView>
</code>```

A working plunker

Body:
You can get a reference to your tabView in your component using @ViewChild and bind to a variable the selectedIndex then you can get the header of selected tavview this.tabView.tabs[this.selectedIndex].header.

Below a sample code:
app.component.ts

import { Component, ViewChild } from '@angular/core';
//imports
import {TabView, TabPanel} from 'primeng/primeng';

@Component({
  selector: 'my-app',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  selectedIndex = 0;
  //class variable
  @ViewChild(TabView) tabView: TabView;

  onChange($event) {
    this.selectedIndex = $event.index;
  }

  getSelectedHeader(){
    console.log(this.tabView.tabs[this.selectedIndex].header);
  }
}

app.component.html

<h2>PrimeNG Issue Template</h2>
<button pButton (click)="getSelectedHeader()" label="selected header"></button>
<p-tabView (onChange)="onChange($event)" [activeIndex]="selectedIndex">
  <p-tabPanel header="first" [selected]="true">
    <first></first>

  </p-tabPanel>
  <p-tabPanel header="second" cache="false">
    <ng-template pTemplate="content">
      <second></second>
    </ng-template>
  </p-tabPanel>
</p-tabView>

A working plunker


问:
Sendgrid Codeigniter setting a category
Alright so I am trying to set a category using Sendgrid & Codeigniter. I am unable to use their STMP api so I have to do it manually but how?

This is my current code

```<code>$body = $this->load->view('mail_templates/users/SG_register_confirmation',$data, true);
$this->email->from($this->config->item('contact_email'), "Welcome!");
$this->email->to($this->config->item('to'));
$this->email->cc($this->config->item('cc'));
$this->email->subject($this->config->item('test_subject'));
$this->email->set_mailtype("html");
$this->email->message($body);
$this->email->send();
</code>```

Now the email works perfectly, but I cant seem to find a way to set its category old fashioned way...

答:
From this page, set your category using:

```<code>$json_string = array(

    'to' => array(
        'example1@sendgrid.com', 'example2@sendgrid.com'
    ),
    'category' => 'test_category'
);
</code>```

Then set the custom category header using the set_header method

```<code>$this->email->set_header('x-smtpapi', json_encode($json_string));
</code>```

See this page for the full list of methods supported by the Codeigniter Email library.

You could also use SMTP by setting Email Preferences. For eg.:

```<code>$config['smtp_host'] = 'https://api.sendgrid.com/';
$config['smtp_user'] = 'smtp_user';
$config['smtp_pass'] = 'smtp_pass';

$this->email->initialize($config);
</code>```

Title: Sendgrid Codeigniter setting a category

Body:
Alright so I am trying to set a category using Sendgrid & Codeigniter. I am unable to use their STMP api so I have to do it manually but how?

This is my current code

$body = $this->load->view('mail_templates/users/SG_register_confirmation',$data, true);
$this->email->from($this->config->item('contact_email'), "Welcome!");
$this->email->to($this->config->item('to'));
$this->email->cc($this->config->item('cc'));
$this->email->subject($this->config->item('test_subject'));
$this->email->set_mailtype("html");
$this->email->message($body);
$this->email->send();

Now the email works perfectly, but I cant seem to find a way to set its category old fashioned way...

Body:
From this page, set your category using:

$json_string = array(

    'to' => array(
        'example1@sendgrid.com', 'example2@sendgrid.com'
    ),
    'category' => 'test_category'
);

Then set the custom category header using the set_header method

$this->email->set_header('x-smtpapi', json_encode($json_string));

See this page for the full list of methods supported by the Codeigniter Email library.

You could also use SMTP by setting Email Preferences. For eg.:

$config['smtp_host'] = 'https://api.sendgrid.com/';
$config['smtp_user'] = 'smtp_user';
$config['smtp_pass'] = 'smtp_pass';

$this->email->initialize($config);