问:
duplicate keys conflict in using activerecord-import with apartment gem
I'm using activerecord-import gem to import many records in one DB insert, in the same project I'm using apartment gem to create and use multi postgres schemas and switch between many schemas realtime ...

the issue is sometimes after import records, will be conflict in unique records ids!

ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR:  duplicate
  key value violates unique constraint "table_name_" DETAIL:  Key
  (id)=(43) already exists.

this conflict only happening by using active-record import gem ...

答:
After debugging many cases ... I realized that the issue is coming from active record sequence_name after switching schema by apartment gem ..

let's say we have two schemas schema_1 and schema_2, after switching schema by apartment gem, it doesn't change the sequence_name of DB table!!, like following ...

```<code>Apartment::Tenant.switch! :schema_1
TableName.sequence_name => "schema_1.table_names_id_seq"
Apartment::Tenant.switch! :schema_2
TableName.sequence_name => "schema_1.table_names_id_seq"
</code>```

so after switching to schema_2 and using active-record-import gem it takes the sequence id from old schema! (schema_1) ... and could be this id is already used in the schema_2 ... and will be PG::UniqueViolation error ...

I tried creating records by TableName.create or .save ... and it works correctly! and getting new sequence ids from current schema (schema_2) ..

it seems like .create and .save refresh sequence_name automatically but active-records-import doesn't !

I solved this by refreshing sequence_name manually before using .import , by:

```<code>TableName.reset_sequence_name
</code>```

Body:
After debugging many cases ... I realized that the issue is coming from active record sequence_name after switching schema by apartment gem ..

let's say we have two schemas schema_1 and schema_2, after switching schema by apartment gem, it doesn't change the sequence_name of DB table!!, like following ...

Apartment::Tenant.switch! :schema_1
TableName.sequence_name => "schema_1.table_names_id_seq"
Apartment::Tenant.switch! :schema_2
TableName.sequence_name => "schema_1.table_names_id_seq"

so after switching to schema_2 and using active-record-import gem it takes the sequence id from old schema! (schema_1) ... and could be this id is already used in the schema_2 ... and will be PG::UniqueViolation error ...

I tried creating records by TableName.create or .save ... and it works correctly! and getting new sequence ids from current schema (schema_2) ..

it seems like .create and .save refresh sequence_name automatically but active-records-import doesn't !

I solved this by refreshing sequence_name manually before using .import , by:

TableName.reset_sequence_name


来源: stackexchange

问:
How to get active user database table in WOffice theme wordpress theme
I am using WordPress for my website with woffice theme. I am developing an android app for the above website. It is required to get database of active user with last login detail. If someone know how to display the active user list, please help me.
Thank you in advance.</p>

答:
It is possible to get the posts or texts of the page by using json api like Ideapress api plugin in wordpress. And retrieving the json response in android app.
Thank you for every one who helped me to get the answer. I hope, this answer could help others.</p>

ContentLicense: CC BY-SA 3.0


问:
How does regex {m,n}? work in Python?
From the Python documentation of the re module:

{m,n}?

Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as few repetitions as possible. This is the non-greedy version of the previous qualifier. For example, on the 6-character string 'aaaaaa', a{3,5} will match 5 'a' characters, while a{3,5}? will only match 3 characters.

I'm confused about how this works.  How is this any different from {m}?  I do not see how there could ever be a case where the pattern could match more than m repetitions. If there are m+1 repetitions in a row, then there are also m.  What am I missing?

答:
let say we have a string to be searched is:
                     str ="aaaaa"

Now we have patter = a{3,5}
The string which it matches are :{aaa,aaaa,aaaaa}
But here we have string as "aaaaa" since we have only one option.

Now lets say we have pattern = a{3,5}?
in this case it matches only "aaa" not "aaaaa".

Thus it takes the minimum items as possible,being non greedy.

please try using online regular Expression at :https://pythex.org/

It will be great help and we check immediately what it matches and what it does not

Title: How does regex {m,n}? work in Python?


问:
problem with quick search android
Hi i'm trying to set up a quick search for my application but i only get a ClassNotFoundException after clicking the search button. I just want to show the user input in a Log. Here's what i got so far:

Manifets.xml

```<code><activity android:name=".SearchActivity">
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>

            <meta-data android:name="android.app.searchable"
                       android:resource="@xml/searchable" />
        </activity>

        <!-- declare the default searchable Activity for the whole app -->
        <meta-data android:name="android.app.default_searchable"
                    android:value=".SearchActivity"/>
</code>```

searchable.xml

```<code><searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/search_label"
    android:hint="@string/search_hint" >
</searchable>
</code>```

SearchActivity.java

```<code>@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.searchresults);

        final Intent queryIntent = getIntent();
        final String queryAction = queryIntent.getAction();
        if (Intent.ACTION_SEARCH.equals(queryAction)) {
            String searchKeywords = queryIntent.getStringExtra(SearchManager.QUERY);
            Log.i("YOU ENTERED", searchKeywords);
        }
    }
</code>```

What i'm i doing wrong? Any help will be really appreciated.

Thanks!!

EDIT: here is the log file:

```<code>01-18 13:34:03.479: ERROR/AndroidRuntime(28349): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{se.madcoderz.searchExample/se.madcoderz.searchExample.SearchActivity}: java.lang.ClassNotFoundException: se.madcoderz.searchExample.SearchActivity in loader dalvik.system.PathClassLoader[/data/app/se.madcoderz.searchExample-2.apk]
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.os.Looper.loop(Looper.java:123)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.app.ActivityThread.main(ActivityThread.java:4627)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at java.lang.reflect.Method.invokeNative(Native Method)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at java.lang.reflect.Method.invoke(Method.java:521)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at dalvik.system.NativeStart.main(Native Method)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349): Caused by: java.lang.ClassNotFoundException: se.madcoderz.searchExample.SearchActivity in loader dalvik.system.PathClassLoader[/data/app/se.madcoderz.searchExample-2.apk]
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     ... 11 more
</code>```

The SDK version i'm using is 1.6

答:
Well i solved my own problem. In the Mainefest.xml i changed the activity name to <activity android:name=".searchExample.SearchActivity"> i did the same in the meta-data outside the activity:

```<code><!-- declare the default searchable Activity for the whole app -->
        <meta-data android:name="android.app.default_searchable"
                    android:value=".searchExample.SearchActivity"/>
</code>```

the thing is that android defines the package name in the Manifest under Manifest General Attributes and i changed some packages names in my project, but the manifest didn't got updated with my changes. So that's why i had to add this ".searchExample" which is the last name in the package where this activity is.

But anyways this is also the reason why we have to add a dot at the start of an activity name in the manifest, which i hadn't until today.

ContentLicense: CC BY-SA 2.5

Title: problem with quick search android

Body:
Hi i'm trying to set up a quick search for my application but i only get a ClassNotFoundException after clicking the search button. I just want to show the user input in a Log. Here's what i got so far:

Manifets.xml

<activity android:name=".SearchActivity">
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>

            <meta-data android:name="android.app.searchable"
                       android:resource="@xml/searchable" />
        </activity>

        <meta-data android:name="android.app.default_searchable"
                    android:value=".SearchActivity"/>

searchable.xml

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/search_label"
    android:hint="@string/search_hint" >
</searchable>

SearchActivity.java

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.searchresults);

        final Intent queryIntent = getIntent();
        final String queryAction = queryIntent.getAction();
        if (Intent.ACTION_SEARCH.equals(queryAction)) {
            String searchKeywords = queryIntent.getStringExtra(SearchManager.QUERY);
            Log.i("YOU ENTERED", searchKeywords);
        }
    }

What i'm i doing wrong? Any help will be really appreciated.

Thanks!!

EDIT: here is the log file:

01-18 13:34:03.479: ERROR/AndroidRuntime(28349): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{se.madcoderz.searchExample/se.madcoderz.searchExample.SearchActivity}: java.lang.ClassNotFoundException: se.madcoderz.searchExample.SearchActivity in loader dalvik.system.PathClassLoader[/data/app/se.madcoderz.searchExample-2.apk]
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.os.Looper.loop(Looper.java:123)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.app.ActivityThread.main(ActivityThread.java:4627)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at java.lang.reflect.Method.invokeNative(Native Method)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at java.lang.reflect.Method.invoke(Method.java:521)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at dalvik.system.NativeStart.main(Native Method)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349): Caused by: java.lang.ClassNotFoundException: se.madcoderz.searchExample.SearchActivity in loader dalvik.system.PathClassLoader[/data/app/se.madcoderz.searchExample-2.apk]
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
01-18 13:34:03.479: ERROR/AndroidRuntime(28349):     ... 11 more

The SDK version i'm using is 1.6

Body:
Well i solved my own problem. In the Mainefest.xml i changed the activity name to <activity android:name=".searchExample.SearchActivity"> i did the same in the meta-data outside the activity:

<!-- declare the default searchable Activity for the whole app -->
        <meta-data android:name="android.app.default_searchable"
                    android:value=".searchExample.SearchActivity"/>

the thing is that android defines the package name in the Manifest under Manifest General Attributes and i changed some packages names in my project, but the manifest didn't got updated with my changes. So that's why i had to add this ".searchExample" which is the last name in the package where this activity is.

But anyways this is also the reason why we have to add a dot at the start of an activity name in the manifest, which i hadn't until today.


问:
Remove previous onOptionsItemSelected between fragments
I have a toolbar with some actions, but those actions should change when I change the fragment to another.

I put setHasOptionsMenu(true); in the onCreate of each fragment that I need to change the action of the toolbar item.

Example fragment 1 onOptionsItemSelected:

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.borrarlote:
            Toast.makeText(viewRoot.getContext(), "Parametros", Toast.LENGTH_SHORT).show();
            break;
    }
    return super.onOptionsItemSelected(item);
}
</code>```

Only have to show me a Toast with the name of the fragments, it does correctly.

Now I change to fragment 2, I repeat the setHasOptions(true) in the onCreate and the onOptionsItemSelected:

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.borrarlote:
            Toast.makeText(viewRoot.getContext(), "Fragment Inicio", Toast.LENGTH_SHORT).show();
            break;
    }
    return super.onOptionsItemSelected(item);
}
</code>```

In my theory the app will shows a Toast saying "Fragment Inicio" but in the reality it shows a Toast saying "Parametros" and then another saying "Fragment Inicio".

It's like the options doesn´t change, just add the new action to the list of actions you have to do each time you click on that item.

Is there any way to clean the actions when I enter a new fragment?

Greetings

答: I solve it creating a menu.xml for each fragment that I need and inflating the menu on it. Works perfectly</p>

Body:
I have a toolbar with some actions, but those actions should change when I change the fragment to another.

I put setHasOptionsMenu(true); in the onCreate of each fragment that I need to change the action of the toolbar item.

Example fragment 1 onOptionsItemSelected:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.borrarlote:
            Toast.makeText(viewRoot.getContext(), "Parametros", Toast.LENGTH_SHORT).show();
            break;
    }
    return super.onOptionsItemSelected(item);
}

Only have to show me a Toast with the name of the fragments, it does correctly.

Now I change to fragment 2, I repeat the setHasOptions(true) in the onCreate and the onOptionsItemSelected:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.borrarlote:
            Toast.makeText(viewRoot.getContext(), "Fragment Inicio", Toast.LENGTH_SHORT).show();
            break;
    }
    return super.onOptionsItemSelected(item);
}

In my theory the app will shows a Toast saying "Fragment Inicio" but in the reality it shows a Toast saying "Parametros" and then another saying "Fragment Inicio".

It's like the options doesn´t change, just add the new action to the list of actions you have to do each time you click on that item.

Is there any way to clean the actions when I enter a new fragment?

Greetings


问:
How to find the Nth number in a fractal sequence?
The assignment is to write a C++ program which takes the input number n and outputs the nth number in the sequence:

1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 ...

This is what I've come up with so far:

```<code>#include <iostream>
using namespace std;

int main()
{
    long long n,k=1,result;
    cin >> n;
    if(n==1){
        result=1;
    }else{
        for(int i=1,j=1;;i=j,j=j+k){
            if(n>i&&n<=j){
                result=n-i;
                break;
            }else{
                k++;
            }
        }
    }
    cout << result << endl;
}
</code>```

This is also what I've written before:

```<code>#include <iostream>
using namespace std;

int main()
{
    long long n,count=0,result;
    cin >> n;
    for(int i=1;;i++){
        for(int j=1;j<=i;j++){
            count=count+1;
            if(count==n){
                result=j;
                break;
            }
        }
        if(count>=n){
            break;
        }
    }
    cout << result << endl;
}
</code>```

Both of these work properly for smaller numbers, but the problem is I have to follow the constraint:

1 <= n <= 10^12

So when bigger numbers are inputted, the programs both take too long to output the solution and exceed the time limit, which is 2 seconds. I've been working on this for 5 hours now and I don't know how to improve these programs so they are faster. I also thought about a certain formula that could help determine the nth number in such a sequence, but I can't seem to find anything about it on the internet or in my math books. Could somebody point me to the solution? I would be very grateful.

答:
A solution using loop. It will out the number at nth.

```<code>x = 0 ;
i = 1 ;
do {
    x += i ;
    if( x == n ) {
        cout<< i ;
        break ;
    }
    else if( x > n ) {
        cout<< (n - (x-i)) ;
        break ;
    }
    i ++ ;
}while( 1) ;
</code>```

Body:
The assignment is to write a C++ program which takes the input number n and outputs the nth number in the sequence:

1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 ...

This is what I've come up with so far:

#include <iostream>
using namespace std;

int main()
{
    long long n,k=1,result;
    cin >> n;
    if(n==1){
        result=1;
    }else{
        for(int i=1,j=1;;i=j,j=j+k){
            if(n>i&&n<=j){
                result=n-i;
                break;
            }else{
                k++;
            }
        }
    }
    cout << result << endl;
}

This is also what I've written before:

#include <iostream>
using namespace std;

int main()
{
    long long n,count=0,result;
    cin >> n;
    for(int i=1;;i++){
        for(int j=1;j<=i;j++){
            count=count+1;
            if(count==n){
                result=j;
                break;
            }
        }
        if(count>=n){
            break;
        }
    }
    cout << result << endl;
}

Both of these work properly for smaller numbers, but the problem is I have to follow the constraint:

1 <= n <= 10^12

So when bigger numbers are inputted, the programs both take too long to output the solution and exceed the time limit, which is 2 seconds. I've been working on this for 5 hours now and I don't know how to improve these programs so they are faster. I also thought about a certain formula that could help determine the nth number in such a sequence, but I can't seem to find anything about it on the internet or in my math books. Could somebody point me to the solution? I would be very grateful.

Body:
A solution using loop. It will out the number at nth.

x = 0 ;
i = 1 ;
do {
    x += i ;
    if( x == n ) {
        cout<< i ;
        break ;
    }
    else if( x > n ) {
        cout<< (n - (x-i)) ;
        break ;
    }
    i ++ ;
}while( 1) ;


问:
What is the difference between Face Detection and Face Tracking in iOS perspective
May be this sounds like a stupid one, but i really curious to know that, what is the difference between "Face Detection and Face Tracking" in iOS perspective? And in what case or which kind of situation should i use the two of them.</p>

答:
First of all you known about Vision Framework!!

Following this link:- https://developer.apple.com/documentation/vision

Vision — a framework to apply high-performance image analysis and computer vision techniques to identify faces, detect features, and classify scenes in images and video.

Face detection. Detects all faces on selected photo.

Face landmarks. An image analysis that finds facial features (such as
the eyes and mouth) in an image.

Object tracking. Track any object using camera.

Among a lot of new APIs there is the Vision Framework which helps with detection of faces, face features, object tracking and others.

Hope will helpful to you!!


问:
How to make the number of swaps zero in Quicksort algorithm for an already sorted array?
Is there any way to achieve the number of swaps zero for an already sorted ascending array list.</p>

```<code>int partition (int arr[], int low, int high)
{
    int pivot = arr[high];    // pivot
    int i = (low - 1);  // Index of smaller element

    for (int j = low; j <= high- 1; j++)
    {
         // If current element is smaller than or
         // equal to pivot
         if (arr[j] <= pivot)
          {
           printf("inside if");
           i++;    // increment index of smaller element
           swap(&arr[i], &arr[j]);
           no_of_comparisons++;
          }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}
</code>```

答:
If you use the middle element rather than the last element in the list (and rearrange the algorithm slightly), you can avoid swapping.

For optimum qsort, you are better off using the median of the first, last, and middle element (known as "median of three").

If you are concerned about the performance sorting attacker generated data (qsort has average O(n log n) performance, but worst-case O(n²)), use a random pivot.

Note:  I can see the question is about partition and not qsort, but it's quite likely to be in the context of qsort.

Body:
Is there any way to achieve the number of swaps zero for an already sorted ascending array list.

int partition (int arr[], int low, int high)
{
    int pivot = arr[high];    // pivot
    int i = (low - 1);  // Index of smaller element

    for (int j = low; j <= high- 1; j++)
    {
         // If current element is smaller than or
         // equal to pivot
         if (arr[j] <= pivot)
          {
           printf("inside if");
           i++;    // increment index of smaller element
           swap(&arr[i], &arr[j]);
           no_of_comparisons++;
          }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}


问:
Using asymmetric algorithm in angular
I need to apply asymmetric encryption for large JSON files on client-side to transfer them to the cloud. These files can include images in the base64 format. I'm working with Angular-cli and tried to use the library crypto-browserify but can't encrypt large files. Then I tried the node-rsa library and my program works in the console, but does not work in Angular.

const NodeRSA = require('node-rsa');

let key = new NodeRSA('-----BEGIN PUBLIC KEY-----\n'+
                      '-----END PUBLIC KEY-----');

let f = '{"data":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA ..."}';

let encrypt_data = key.encrypt(f, 'base64');
console.log(encrypt_data);```

答:
A solution is found in using node-rsa through browserify:

browserify -r node-rsa --standalone CryptRSA > rsa-brow.js

Then added to index.html

```<code><script src="assets/js/rsa-brow.js"></script>
</code>```

Then using in Angular

declare var CryptRSA: any;

@Injectable()
export class MyService {

    encrypt(file_content: string){
       let key = new CryptRSA(publicKey);
       let buffer = Buffer.from(file_content, 'utf-8');
       return key.encrypt(buffer, 'base64');
    }
}```

Title: Using asymmetric algorithm in angular

Body:
A solution is found in using node-rsa through browserify:

browserify -r node-rsa --standalone CryptRSA > rsa-brow.js

Then added to index.html

<script src="assets/js/rsa-brow.js"></script>

Then using in Angular

declare var CryptRSA: any;

@Injectable()
export class MyService {

    encrypt(file_content: string){
       let key = new CryptRSA(publicKey);
       let buffer = Buffer.from(file_content, 'utf-8');
       return key.encrypt(buffer, 'base64');
    }
}


问:
Is "return i++, i, i++;" undefined behaviour in C?
If I write like this :

```<code>i = i++, i, i++;
</code>```

It is undefined behaviour in C language.

But, If I write like this:

```<code>return i++, i, i++; // Is it UB?
</code>```

Is it undefined behaviour?

Example:

```<code>#include <stdio.h>

int f(int i)
{
    return i++, i, i++; // Is it UB?
}
int main() {
    int i = 1;
    i = i++, i, i++;

    i = f(i);
    printf("%d\n",i);
    return 0;
}
</code>```

答:
i = i++, i, i++; is UB because = has higher precedence than , and so the expression gets parsed as (i = i++), i, i++ where the sub-expression i = i++ invokes UB1).

Even if the code had been written as i = (i++, i, i++); it would still have been UB, because now there is no sequence point between the right-most i++ and i, the left operand of = 1).

However, when you remove the i = part, you remove that ambiguous behavior. return i++, i, i++; must get sequenced as:

```<code>i++, the left one
sequence point from left comma
i
sequence point from right comma
i++, the right one
sequence point before returning
</code>```

So it is well-defined.

Sources:

1) C11 6.5/2

If a side effect on a scalar object is unsequenced relative to either a different side effect
  on the same scalar object or a value computation using the value of the same scalar
  object, the behavior is undefined. If there are multiple allowable orderings of the
  subexpressions of an expression, the behavior is undefined if such an unsequenced side
  effect occurs in any of the orderings.

And then also C11 6.5.16/3

The side effect of updating the stored value of the left operand is
  sequenced after the value computations of the left and right operands. The evaluations of the operands are unsequenced.

Notable, the above text regarding assignment is different between C11 and C++11.

Body:
If I write like this :

i = i++, i, i++;

It is undefined behaviour in C language.

But, If I write like this:

return i++, i, i++; // Is it UB?

Is it undefined behaviour?

Example:

#include <stdio.h>

int f(int i)
{
    return i++, i, i++; // Is it UB?
}
int main() {
    int i = 1;
    i = i++, i, i++;

    i = f(i);
    printf("%d\n",i);
    return 0;
}

Body:
i = i++, i, i++; is UB because = has higher precedence than , and so the expression gets parsed as (i = i++), i, i++ where the sub-expression i = i++ invokes UB1).

Even if the code had been written as i = (i++, i, i++); it would still have been UB, because now there is no sequence point between the right-most i++ and i, the left operand of = 1).

However, when you remove the i = part, you remove that ambiguous behavior. return i++, i, i++; must get sequenced as:

i++, the left one
sequence point from left comma
i
sequence point from right comma
i++, the right one
sequence point before returning

So it is well-defined.

Sources:

1) C11 6.5/2

If a side effect on a scalar object is unsequenced relative to either a different side effect
  on the same scalar object or a value computation using the value of the same scalar
  object, the behavior is undefined. If there are multiple allowable orderings of the
  subexpressions of an expression, the behavior is undefined if such an unsequenced side
  effect occurs in any of the orderings.

And then also C11 6.5.16/3

The side effect of updating the stored value of the left operand is
  sequenced after the value computations of the left and right operands. The evaluations of the operands are unsequenced.

Notable, the above text regarding assignment is different between C11 and C++11.


问:
InetSocketAddress vs InetAddress
Can anyone please explain me is there is any difference between InetAddress and InetSocketAddress classes in java, and if there is a difference, please explain the same. I google-ed it up but I couldn't find anything explanatory.

答:
They represent different OSI layers:

An InetAddress corresponds to the Network Layer (Layer 3) and is basically an IP address.

A InetSocketAddress corresponds to the Transport Layer (Layer 4) and consists of an IP address and a port number.

Title: InetSocketAddress vs InetAddress


问:
Immutable vs Mutable types
I'm confused on what an immutable type is. I know the float object is considered to be immutable, with this type of example from my book:

```<code>class RoundFloat(float):
    def __new__(cls, val):
        return float.__new__(cls, round(val, 2))
</code>```

Is this considered to be immutable because of the class structure / hierarchy?, meaning float is at the top of the class and is its own method call. Similar to this type of example (even though my book says dict is mutable):

```<code>class SortedKeyDict(dict):
    def __new__(cls, val):
        return dict.__new__(cls, val.clear())
</code>```

Whereas something mutable has methods inside the class, with this type of example:

```<code>class SortedKeyDict_a(dict):
    def example(self):
        return self.keys()
</code>```

Also, for the last class(SortedKeyDict_a), if I pass this type of set to it:

```<code>d = (('zheng-cai', 67), ('hui-jun', 68),('xin-yi', 2))
</code>```

without calling the example method, it returns a dictionary. The SortedKeyDict with __new__ flags it as an error. I tried passing integers to the RoundFloat class with __new__ and it flagged no errors.

答:
Difference between Mutable and Immutable objects

Definitions

Mutable object: Object that can be changed after creating it.

Immutable object: Object that cannot be changed after creating it.

In Python if you change the value of the immutable object it will create a new object.

Mutable Objects

Here are the objects in Python that are of mutable type:

list

Dictionary

Set

bytearray

user defined classes

Immutable Objects

Here are the objects in Python that are of immutable type:

int

float

decimal

complex

bool

string

tuple

range

frozenset

bytes

Some Unanswered Questions

Question: Is string an immutable type?

Answer: yes  it is, but can you explain this:
Proof 1:

a = "Hello"
a +=" World"
print a
```
<p><strong>Output</strong></p>
```"Hello World"```
<p>In the above example the string got once created as "Hello" then changed to "Hello World". This implies that the string is of the mutable type. But it is not when we check its identity to see whether it is of a mutable type or not.</p>
<pre class="lang-py prettyprint-override"><code>a = "Hello"
identity_a = id(a)
a += " World"
new_identity_a = id(a)
if identity_a != new_identity_a:
    print "String is Immutable"
</code>```

Output

```String is Immutable```

Proof 2:

a = "Hello World"
a[0] = "M"
```
<p><strong>Output</strong></p>
```TypeError 'str' object does not support item assignment```
<p><strong>Question</strong>: <strong>Is Tuple an immutable type?</strong><br>
<strong>Answer</strong>: <strong>yes</strong>,  it is.
<strong>Proof 1</strong>:<br></p>
<pre class="lang-py prettyprint-override"><code>tuple_a = (1,)
tuple_a[0] = (2,)
print a
</code>```

Output

```'tuple' object does not support item assignment```

Title: Immutable vs Mutable types

Body:
I'm confused on what an immutable type is. I know the float object is considered to be immutable, with this type of example from my book:

class RoundFloat(float):
    def __new__(cls, val):
        return float.__new__(cls, round(val, 2))

Is this considered to be immutable because of the class structure / hierarchy?, meaning float is at the top of the class and is its own method call. Similar to this type of example (even though my book says dict is mutable):

class SortedKeyDict(dict):
    def __new__(cls, val):
        return dict.__new__(cls, val.clear())

Whereas something mutable has methods inside the class, with this type of example:

class SortedKeyDict_a(dict):
    def example(self):
        return self.keys()

Also, for the last class(SortedKeyDict_a), if I pass this type of set to it:

d = (('zheng-cai', 67), ('hui-jun', 68),('xin-yi', 2))

without calling the example method, it returns a dictionary. The SortedKeyDict with __new__ flags it as an error. I tried passing integers to the RoundFloat class with __new__ and it flagged no errors.

Body:
Difference between Mutable and Immutable objects

Definitions

Mutable object: Object that can be changed after creating it.

Immutable object: Object that cannot be changed after creating it.

In Python if you change the value of the immutable object it will create a new object.

Mutable Objects

Here are the objects in Python that are of mutable type:

list

Dictionary

Set

bytearray

user defined classes

Immutable Objects

Here are the objects in Python that are of immutable type:

int

float

decimal

complex

bool

string

tuple

range

frozenset

bytes

Some Unanswered Questions

Question: Is string an immutable type?

Answer: yes  it is, but can you explain this:
Proof 1:

a = "Hello"
a +=" World"
print a

Output

"Hello World"

In the above example the string got once created as "Hello" then changed to "Hello World". This implies that the string is of the mutable type. But it is not when we check its identity to see whether it is of a mutable type or not.

a = "Hello"
identity_a = id(a)
a += " World"
new_identity_a = id(a)
if identity_a != new_identity_a:
    print "String is Immutable"

Output

String is Immutable

Proof 2:

a = "Hello World"
a[0] = "M"

Output

TypeError 'str' object does not support item assignment

Question: Is Tuple an immutable type?

Answer: yes,  it is.
Proof 1:

tuple_a = (1,)
tuple_a[0] = (2,)
print a

Output

'tuple' object does not support item assignment

ContentLicense: CC BY-SA 4.0


问:
Match two equal values in pattern matching in Haskell
I have a data type, which basically just consists of flags, e.g.:

```<code>data IOMode = Read | Write | ReadWrite
</code>```

Now this would be ideal for a Semigroup, so that I could use it similiar to enums in C (openFile("./file", READ || WRITE)).

```<code>instance Semigroup IOMode where
   ReadWrite <> _         = ReadWrite
   _         <> ReadWrite = ReadWrite
   Read      <> Write     = ReadWrite
   Read      <> Read      = Read
   Write     <> Read      = ReadWrite
   Write     <> Write     = Write
</code>```

However is there some way to have a pattern match like:

```<code>(cont.)
  a          <> a         = a
</code>```

答:
To answer your question: no, Haskell allows only linear pattern matching: this means that a variable can occur only once in the head of a clause.

Using Eq

A more elegant solution is probably to let IOMode derive from Eq:

```<code>data IOMode = Read | Write | ReadWrite <b>deriving Eq</b></code>```

and then we can use the (==) :: Eq a => a -> a -> a function, and write it as:

```<code>instance Semigroup IOMode where
   <b>a         <> b         | a == b = a</b>
   ReadWrite <> _         = ReadWrite
   _         <> ReadWrite = ReadWrite
   Read      <> Write     = ReadWrite
   Write      <> Read      = ReadWrite</code>```

But now a problem is that the Haskell compiler can not derive that we have covered all the cases: for the compiler (==) is a blackbox function, so that means that a compiler is conservative and does not know when a == b might fail. So perhaps we want another solution.

Reducing the amount of rules

The above still is quite redundant, since the operator is commutative, we can first check for equality, then test against some cases, and otherwise perform a swap:

```<code>instance Semigroup IOMode where
   ReadWrite <> _         = ReadWrite
   Read      <> Write     = ReadWrite
   <b>a         <> b         | a == b = a</b>
                          | otherwise = b <> a</code>```

In this case, we can fold it all together, since if a /= b, we know that the outcome is ReadWrite:

```<code>instance Semigroup IOMode where
   a         <> b         | a == b = a
                          | otherwise = <b>ReadWrite</b></code>```

Using wildcards

Another way to handle this is to cover all the cases that are different, and use wildcards for all the cases where a == b:

```<code>instance Semigroup IOMode where
   ReadWrite <> _         = ReadWrite
   _         <> ReadWrite = ReadWrite
   Read      <> Write     = ReadWrite
   Write     <> Read      = ReadWrite
   a         <> _         = a</code>```

We know this will work since only the three instances that all cases where the first two parameters are different are covered by the definitions above.

We can check this by writing an instance without the wildcards (if we enable warnings):

```<code>Prelude Data.Semigroup| instance Semigroup IOMode where
Prelude Data.Semigroup|    ReadWrite <> _         = ReadWrite
Prelude Data.Semigroup|    _         <> ReadWrite = ReadWrite
Prelude Data.Semigroup|    Read      <> Write     = ReadWrite
Prelude Data.Semigroup|    Write     <> Read      = ReadWrite
Prelude Data.Semigroup| :}

<interactive>:22:4: warning: [-Wincomplete-patterns]
    Pattern match(es) are non-exhaustive
    In an equation for ‘<>’:
        Patterns not matched:
            Read Read
            Write Write
</code>```

So Haskell has derived that there are only two patterns left: Read Read and Write Write.

Body:
I have a data type, which basically just consists of flags, e.g.:

data IOMode = Read | Write | ReadWrite

Now this would be ideal for a Semigroup, so that I could use it similiar to enums in C (openFile("./file", READ || WRITE)).

instance Semigroup IOMode where
   ReadWrite <> _         = ReadWrite
   _         <> ReadWrite = ReadWrite
   Read      <> Write     = ReadWrite
   Read      <> Read      = Read
   Write     <> Read      = ReadWrite
   Write     <> Write     = Write

However is there some way to have a pattern match like:

(cont.)
  a          <> a         = a

Body:
To answer your question: no, Haskell allows only linear pattern matching: this means that a variable can occur only once in the head of a clause.

Using Eq

A more elegant solution is probably to let IOMode derive from Eq:

data IOMode = Read | Write | ReadWrite deriving Eq

and then we can use the (==) :: Eq a => a -> a -> a function, and write it as:

instance Semigroup IOMode where
   a         <> b         | a == b = a
   ReadWrite <> _         = ReadWrite
   _         <> ReadWrite = ReadWrite
   Read      <> Write     = ReadWrite
   Write      <> Read      = ReadWrite

But now a problem is that the Haskell compiler can not derive that we have covered all the cases: for the compiler (==) is a blackbox function, so that means that a compiler is conservative and does not know when a == b might fail. So perhaps we want another solution.

Reducing the amount of rules

The above still is quite redundant, since the operator is commutative, we can first check for equality, then test against some cases, and otherwise perform a swap:

instance Semigroup IOMode where
   ReadWrite <> _         = ReadWrite
   Read      <> Write     = ReadWrite
   a         <> b         | a == b = a
                          | otherwise = b <> a

In this case, we can fold it all together, since if a /= b, we know that the outcome is ReadWrite:

instance Semigroup IOMode where
   a         <> b         | a == b = a
                          | otherwise = ReadWrite

Using wildcards

Another way to handle this is to cover all the cases that are different, and use wildcards for all the cases where a == b:

instance Semigroup IOMode where
   ReadWrite <> _         = ReadWrite
   _         <> ReadWrite = ReadWrite
   Read      <> Write     = ReadWrite
   Write     <> Read      = ReadWrite
   a         <> _         = a

We know this will work since only the three instances that all cases where the first two parameters are different are covered by the definitions above.

We can check this by writing an instance without the wildcards (if we enable warnings):

Prelude Data.Semigroup| instance Semigroup IOMode where
Prelude Data.Semigroup|    ReadWrite <> _         = ReadWrite
Prelude Data.Semigroup|    _         <> ReadWrite = ReadWrite
Prelude Data.Semigroup|    Read      <> Write     = ReadWrite
Prelude Data.Semigroup|    Write     <> Read      = ReadWrite
Prelude Data.Semigroup| :}

<interactive>:22:4: warning: [-Wincomplete-patterns]
    Pattern match(es) are non-exhaustive
    In an equation for ‘<>’:
        Patterns not matched:
            Read Read
            Write Write

So Haskell has derived that there are only two patterns left: Read Read and Write Write.


问:
Confusion using object oriented design .. need help
Let say we have an Order class and OrderManagerService class.

Order class: [some state and methods that act on the state]

Item[]

status

OrderManagerService class: [have no state. only following static methods]

createOrder

getOrder

Question: Let say we are using a relational DB in the back. Our goal is to update Order status. Well, the status need to get updated in the DB. My concern is where to put the updateStatus method.

Should I call OrderManagerService.getOrder then, call Order.updateStatus?

or create a new method as OrderManagerService.updateOrderStatus?

well, 1st option seems following encapsulation. But, personally I dont like it as we may end up calling DAO layer from entity objects [perhaps, that might be ok]. Wondering what would be a right design choice and why? any help is greatly appreciated.

答:
I think OrderManagerService should have an array of Order class items.  This way you could iterate through each item and update the status there.  Or if you are looking for accessing a single order item go directly to it via the Order class and update it there.

In either case with your current setup the updateStatus() should be in the Order class.


问:
WPF Dynamically Populate UI
How can I populate UI items such as a textblock for example, based on the contents of a datagrid?

For example, if i had a datagrid with a varying number of columns each with a specific header. Would it be possible to create a new textblock for each column with the content of text being the column header?

I'm trying to populate a list of column names and checkboxes based on the contents of mydatagrid which has data pulled in from an excel file.

Thank you.

答:
The simplest solution is to bind to DataGrid's Columns property

MainWindow.xaml:

```<code><Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <DataGrid Grid.Column="0" AutoGenerateColumns="False" x:Name="DataGrid1">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Column 1" Width="75" />
                <DataGridTextColumn Header="Column 2" Width="75" />
                <DataGridTextColumn Header="Column 3" Width="75" />
                <DataGridTextColumn Header="Column 4" Width="75" />
            </DataGrid.Columns>
        </DataGrid>
        <ListBox Grid.Column="1" ItemsSource="{Binding ElementName=DataGrid1, Path=Columns}">
            <ListBox.ItemTemplate>
                <DataTemplate DataType="{x:Type DataGridColumn}">
                    <TextBlock Text="{Binding Path=Header}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>
</code>```

MainWindow.xaml.cs:

```<code>using System.Linq;

namespace WpfApp1
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();

            DataGrid1.ItemsSource = Enumerable.Range(1, 10).ToList();
        }
    }
}
</code>```

Then you can modify <ListBox.ItemTemplate> to adjust an items appearance to your needs.

Title: WPF Dynamically Populate UI

Body:
The simplest solution is to bind to DataGrid's Columns property

MainWindow.xaml:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <DataGrid Grid.Column="0" AutoGenerateColumns="False" x:Name="DataGrid1">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Column 1" Width="75" />
                <DataGridTextColumn Header="Column 2" Width="75" />
                <DataGridTextColumn Header="Column 3" Width="75" />
                <DataGridTextColumn Header="Column 4" Width="75" />
            </DataGrid.Columns>
        </DataGrid>
        <ListBox Grid.Column="1" ItemsSource="{Binding ElementName=DataGrid1, Path=Columns}">
            <ListBox.ItemTemplate>
                <DataTemplate DataType="{x:Type DataGridColumn}">
                    <TextBlock Text="{Binding Path=Header}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>

MainWindow.xaml.cs:

using System.Linq;

namespace WpfApp1
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();

            DataGrid1.ItemsSource = Enumerable.Range(1, 10).ToList();
        }
    }
}

Then you can modify <ListBox.ItemTemplate> to adjust an items appearance to your needs.


问:
Macro to find and replace cell with values from a different sheet
I need some help writing a Macro to find cells in one sheet, then replace the cells with data from a different sheet.   I have searched far and wide but my VBA knowledge is quite limited so am not sure what the coding is doing in other answers.

I have a spreadsheet with the names and locations of people in the organization like the one below (call it Sheet1).
Sheet1

And another similar sheet that tracks where people are temporarily located (Sheet2).
Sheet2

What I want is a Macro that searches Sheet1 for the people in Sheet2, and replaces the location in Sheet1 with the temporary location from Sheet2. The search needs to match LastName, FirstName, and Last4 to ensure its replacing the location for the right person.  The actual spreadsheet includes hundreds of people so its not uncommon to have multiple people with the same name.

I've found a similar issue in another thread: Need a VBA Script to replace data in one sheet with data in another

I know enough to understand what this script is doing.  What I need help with is getting it to search Sheet2 for multiple criteria that matches Sheet1 before replacing the cell.  This script only matches one name, and I need it to match a LastName, FirstName, and Last4.

Hope that makes sense.
Thanks for the help!

答:
Dont use VBA, use a Function. It will be simpler and quicker. Create a hidden column and concatenate your three columns into one string (=A2&B2&c3)
Then do the same in sheet 2
Then use INDEX and MATCH to search sheet 2 for that concatenated value. If found show the location from sheet2 otherwise show that from sheet1</p>


问:
The condition `WHERE Id = 14317961` in my query is invalid
```<code>var report = AdWordsApp.report(
           'SELECT Id, Criteria, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
           'FROM   KEYWORDS_PERFORMANCE_REPORT ' +
           'WHERE' +
           'Id = 14317961 ' +
           'DURING LAST_7_DAYS ');
var rows = report.rows();

while(rows.hasNext()) {
    var row = rows.next();
    var keywordIdReport = row['Id'];
    var keywordNameReport = row['Criteria'];
    var cpcBid = row['CpcBid'];
    var firstPageCpc = row['FirstPageCpc'];
    var firstPositionCpc = row['FirstPositionCpc'];
    var topOfPageCpc = row['TopOfPageCpc'];

    Logger.log('KeywordIdReport :' + keywordIdReport)
    Logger.log('CPCbid :' + cpcBid)
    Logger.log('firstPositionCpc : ' + firstPositionCpc)
    Logger.log('topOfPageCpc : ' + topOfPageCpc)
    Logger.log('firstPageCpc : ' + firstPageCpc)
}
</code>```

I don't understand why, but the Adwords IDE tell me that the condition WHERE Id = 14317961 in my query is invalid, but I can't explain it is wrong. Assume here that the current Id exists. The purpose of that query is to access the three fields firstPositionCpc, topOfPageCpc and firstPageCpc for the specific keyword id. How could I fix my problem?

答: Try giving a space after your where clause 'WHERE ' +.

Body:
var report = AdWordsApp.report(
           'SELECT Id, Criteria, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
           'FROM   KEYWORDS_PERFORMANCE_REPORT ' +
           'WHERE' +
           'Id = 14317961 ' +
           'DURING LAST_7_DAYS ');
var rows = report.rows();

while(rows.hasNext()) {
    var row = rows.next();
    var keywordIdReport = row['Id'];
    var keywordNameReport = row['Criteria'];
    var cpcBid = row['CpcBid'];
    var firstPageCpc = row['FirstPageCpc'];
    var firstPositionCpc = row['FirstPositionCpc'];
    var topOfPageCpc = row['TopOfPageCpc'];

    Logger.log('KeywordIdReport :' + keywordIdReport)
    Logger.log('CPCbid :' + cpcBid)
    Logger.log('firstPositionCpc : ' + firstPositionCpc)
    Logger.log('topOfPageCpc : ' + topOfPageCpc)
    Logger.log('firstPageCpc : ' + firstPageCpc)
}

I don't understand why, but the Adwords IDE tell me that the condition WHERE Id = 14317961 in my query is invalid, but I can't explain it is wrong. Assume here that the current Id exists. The purpose of that query is to access the three fields firstPositionCpc, topOfPageCpc and firstPageCpc for the specific keyword id. How could I fix my problem?


答:
You are just missing the space after the WHERE keyword, it should be as shown below:

```<code>var report = AdWordsApp.report(
           'SELECT Id, Criteria, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
           'FROM   KEYWORDS_PERFORMANCE_REPORT ' +
           'WHERE ' +
           'Id = 14317961 ' +
           'DURING LAST_7_DAYS ');
</code>```

Title: The condition `WHERE Id = 14317961` in my query is invalid

Body:
You are just missing the space after the WHERE keyword, it should be as shown below:

var report = AdWordsApp.report(
           'SELECT Id, Criteria, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
           'FROM   KEYWORDS_PERFORMANCE_REPORT ' +
           'WHERE ' +
           'Id = 14317961 ' +
           'DURING LAST_7_DAYS ');


问:
iOS SDK Mutual Friends Facebook API v2.0
I'm currently using the Facebook iOS SDK v3.16, which uses the Graph API 2.0. My call looks like this:

```<code> NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                        @"context.fields(mutual_friends)", @"fields",
                        nil
                        ];
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:@"/%@", object[@"profile"][@"facebookId"]]
                             parameters:params
                             HTTPMethod:@"GET"
                      completionHandler:^(
                                          FBRequestConnection *connection,
                                          id result,
                                          NSError *error
                                          ) {
                          cell.text3.text = [NSString stringWithFormat:@"Mutual Users: %lu", [result[@"context"][@"mutual_friends"][@"data"] count]];
                      }];
</code>```

object[@"profile"][@"facebookId"] is a scoped ID for the app.

The expected behavior for this call would be to return the number of mutual friends in between the current user and the requested user. The thing is, though, that the mutual friend count is almost always 0 (for some reason it is 2 in a couple cases, but it should actually be higher).

The weird part is the error object never has anything in it, and the result object is just nil. I'm not quite sure how to proceed since there are no results being returned and yet there should be, but it is not giving me an error.

答:
Find a working code in swift 3.0

Note: Submit for review to facebook for using this service

```<code>FBSDKGraphRequest(graphPath: fbTokenID, parameters: ["fields": "context.fields(mutual_friends.limit(8))"]).start(completionHandler: { (connection, result, error) -> Void in
            if (error == nil){

                print("//////Mutual friends")
                print(result!)

            } else {
                print(error!.localizedDescription)
            }
        })
</code>```

// you can also limit result of mutual friends by adding "limit"

Body:
I'm currently using the Facebook iOS SDK v3.16, which uses the Graph API 2.0. My call looks like this:

 NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                        @"context.fields(mutual_friends)", @"fields",
                        nil
                        ];
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:@"/%@", object[@"profile"][@"facebookId"]]
                             parameters:params
                             HTTPMethod:@"GET"
                      completionHandler:^(
                                          FBRequestConnection *connection,
                                          id result,
                                          NSError *error
                                          ) {
                          cell.text3.text = [NSString stringWithFormat:@"Mutual Users: %lu", [result[@"context"][@"mutual_friends"][@"data"] count]];
                      }];

object[@"profile"][@"facebookId"] is a scoped ID for the app.

The expected behavior for this call would be to return the number of mutual friends in between the current user and the requested user. The thing is, though, that the mutual friend count is almost always 0 (for some reason it is 2 in a couple cases, but it should actually be higher).

The weird part is the error object never has anything in it, and the result object is just nil. I'm not quite sure how to proceed since there are no results being returned and yet there should be, but it is not giving me an error.

Body:
Find a working code in swift 3.0

Note: Submit for review to facebook for using this service

FBSDKGraphRequest(graphPath: fbTokenID, parameters: ["fields": "context.fields(mutual_friends.limit(8))"]).start(completionHandler: { (connection, result, error) -> Void in
            if (error == nil){

                print("//////Mutual friends")
                print(result!)

            } else {
                print(error!.localizedDescription)
            }
        })

// you can also limit result of mutual friends by adding "limit"


问:
GWT Special Features compared to other Frameworks
I am on searching special features of GWT which are present only in GWT and not in other web framework. I am a student and I am not well acquainted to the many web frameworks on the market, so if u can help me increasing my list of special GWT features, it would be a great help. Some which i know are:

```<code> 1. GWT allows using java to program
web. (only, it also allows merging
javascript through JSNI of course)

2. The developer does not have to be a guru in browser incompatibilities
to develop web sites which works on
a variety of browsers because
incompatibilities are handled by GWT
through differed bindind

3. GWT allows easy integration of popular Java Tools such as ,
hibernate through gilead

4. GWT enables server implementation not only in java but also other
languages such as php

5. GWT enables code splitting which improves application interactivity
by allowing javaScript file to
download only when required

6. In essence GWT is toolkit, it does not force a way to program,
other layers can be placed on top of
it to program such as placing MVP or
MVC framework on top of GWT and then
develop app

7. GWT MVP is great because first it allows collaborative working, faster
testing with JUnit and the event bus
allows many updates in client side
application by placing event on the
event bus

8. GWT compiled java files to obfuscated mode which is first small
and make the application safer
because bots fails on the javascript
generated during the obfuscated mode
</code>```

In case in the 8 points, i've mention something which not special to GWT, then let me know.

答: I think you pulled together a pretty decent list of differentiators there already. I think that one point worth adding is the RequestFactory feature in the most recent release, which, if you will, is simplistically speaking and RPC for data and makes it quite easy to develop Create, Read, Update and Delete - type (CRUD) of applications.</p>

Body:
I am on searching special features of GWT which are present only in GWT and not in other web framework. I am a student and I am not well acquainted to the many web frameworks on the market, so if u can help me increasing my list of special GWT features, it would be a great help. Some which i know are:

 1. GWT allows using java to program
web. (only, it also allows merging
javascript through JSNI of course)

2. The developer does not have to be a guru in browser incompatibilities
to develop web sites which works on
a variety of browsers because
incompatibilities are handled by GWT
through differed bindind

3. GWT allows easy integration of popular Java Tools such as ,
hibernate through gilead

4. GWT enables server implementation not only in java but also other
languages such as php

5. GWT enables code splitting which improves application interactivity
by allowing javaScript file to
download only when required

6. In essence GWT is toolkit, it does not force a way to program,
other layers can be placed on top of
it to program such as placing MVP or
MVC framework on top of GWT and then
develop app

7. GWT MVP is great because first it allows collaborative working, faster
testing with JUnit and the event bus
allows many updates in client side
application by placing event on the
event bus

8. GWT compiled java files to obfuscated mode which is first small
and make the application safer
because bots fails on the javascript
generated during the obfuscated mode

In case in the 8 points, i've mention something which not special to GWT, then let me know.


问:
Why does testing a non-exported static function via obj file pass when it should fail?
I'm writing a DLL which sets a static boolean value in a class depending on the calling process.

Since I know that the testing environment will check for a false value, I inverted the logic in the setting code to ensure that the test failed.

When using a public static bool and an exported getValue(), this works as expected.

Switching to private static bool, friend DllMain(...) and an exported getValue() still works fine.

If I make the getValue() have internal linkage and then link the test via the .obj file produced by Visual C++, the test now passes an EXPECT_EQ(getValue, false) test even though the inverted logic means it should fail (i.e., getValue should return true.)

What's going on here? My guess is either covering of the value or removal of some of the code during compilation. Can I avoid this?

Loader.cpp:

```<code>bool WINAPI DllMain(HINSTANCE hInstance, DWORD reason, LPVOID lpReserved) {
    ...
    if (falseCondition) {
        myClass::isAvailable = false;
    } else {
        myClass::isAvailable = true;
    }
    return true;
}
</code>```

myClass.h

```<code>#ifdef MYPROJECT_EXPORTS
#define MYPROJECT_API __declspec(dllexport)
#else
#define MYPROJECT_API __declspec(dllimport)
#endif

class myClass {
   friend bool WINAPI DllMain(HINSTANCE, DWORD, LPVOID);
   static bool isAvailable;

public:
   MYPROJECT_API static bool getAvailable() { return isAvailable; }
};
</code>```

myClass.cpp

```<code>#include myClass.h
bool myClass::isAvailable = false;
</code>```

In the above example code, removing the MYPROJECT_API macro from the getAvailable() line leads to the test returning false when it should return true, and fail.

答:
You can share an instance of a class / variable through all accessing applications / other DLLs.

#pragma data_seg

```<code>#pragma data_seg (".mydata")
    int i = 0;
    char a[32]n = "hello world";
#pragma data_seg()
#pragma comment(linker, "/SECTION:.mydata,RWS"
</code>```

Here the string ".mydata" is your named section. You may change this string to something else. Do not forget to change it in the #pragma comment for the linker too.

The sample is taken from MSDN. I have added #pragma comment line as I use it myself (should be explained in detail on MSDN too).

Changing one of the variables inside the data_seg block will also change it for any other application / DLL accessing these.

Body:
I'm writing a DLL which sets a static boolean value in a class depending on the calling process.

Since I know that the testing environment will check for a false value, I inverted the logic in the setting code to ensure that the test failed.

When using a public static bool and an exported getValue(), this works as expected.

Switching to private static bool, friend DllMain(...) and an exported getValue() still works fine.

If I make the getValue() have internal linkage and then link the test via the .obj file produced by Visual C++, the test now passes an EXPECT_EQ(getValue, false) test even though the inverted logic means it should fail (i.e., getValue should return true.)

What's going on here? My guess is either covering of the value or removal of some of the code during compilation. Can I avoid this?

Loader.cpp:

bool WINAPI DllMain(HINSTANCE hInstance, DWORD reason, LPVOID lpReserved) {
    ...
    if (falseCondition) {
        myClass::isAvailable = false;
    } else {
        myClass::isAvailable = true;
    }
    return true;
}

myClass.h

#ifdef MYPROJECT_EXPORTS
#define MYPROJECT_API __declspec(dllexport)
#else
#define MYPROJECT_API __declspec(dllimport)
#endif

class myClass {
   friend bool WINAPI DllMain(HINSTANCE, DWORD, LPVOID);
   static bool isAvailable;

public:
   MYPROJECT_API static bool getAvailable() { return isAvailable; }
};

myClass.cpp

#include myClass.h
bool myClass::isAvailable = false;

In the above example code, removing the MYPROJECT_API macro from the getAvailable() line leads to the test returning false when it should return true, and fail.

Body:
You can share an instance of a class / variable through all accessing applications / other DLLs.

#pragma data_seg

#pragma data_seg (".mydata")
    int i = 0;
    char a[32]n = "hello world";
#pragma data_seg()
#pragma comment(linker, "/SECTION:.mydata,RWS"

Here the string ".mydata" is your named section. You may change this string to something else. Do not forget to change it in the #pragma comment for the linker too.

The sample is taken from MSDN. I have added #pragma comment line as I use it myself (should be explained in detail on MSDN too).

Changing one of the variables inside the data_seg block will also change it for any other application / DLL accessing these.


问:
Webpack: Is it possible to load svg with the file-loader? If yes, how?
I want to load my svg via the file-loader with webpack. Is this even possible and if yes, how do I do that.

webpack.config.js

```<code>test: /\.(jpe?g|png|gif|svg)$/i,
use: [
  {
    loader: 'file-loader',
    options: {
      name:'[name].[ext]',
      outputPath: 'img/',
      publicPath: '../',
    }
  }
]
</code>```

答: I had similar problem. Just imported svg as html and then injected to your template as component. Worked perfectly for me.</p>

Body:
I want to load my svg via the file-loader with webpack. Is this even possible and if yes, how do I do that.

webpack.config.js

test: /\.(jpe?g|png|gif|svg)$/i,
use: [
  {
    loader: 'file-loader',
    options: {
      name:'[name].[ext]',
      outputPath: 'img/',
      publicPath: '../',
    }
  }
]


问:
How to have implementation of interface repository in other project module in AndroidStudio using Dagger2 and Kotlin
I want to be able to have 2 different reactive implementation of the interface that is getting user location in other project module in AndroidStudio.

So to be specific it can be by using gms, or by just native android LocationManager.

Here is my repository interface:

```<code>interface RxLocationRepository {

@SuppressLint("MissingPermission")
fun onLocationUpdate(): Observable<Location>

fun stopLocationUpdates()
}
</code>```

So for now, i implement this interface here, in class that is in the same project module in AndroidStudio:

```<code>class RxLocationRepositoryImpl(val reactiveLocationProvider: ReactiveLocationProvider,
                           val reactiveLocationRequest: LocationRequest,
                           val isUsingLocationNativeApi: Boolean,
                           val locationManager: LocationManager,
                           val geoEventsDistanceMeters: Int,
                           val geoEventsIntervalSeconds: Int
) : RxLocationRepository {

var locationToPopulate: Location = Location(LocationManager.GPS_PROVIDER)
lateinit var mLocationCallbackNativeApi: LocationListener
private val subject: BehaviorSubject<Location> = BehaviorSubject.createDefault(locationToPopulate)
var locationEmitter: Observable<Location> = subject.hide()

init {
    configureEmitter()
}

@SuppressLint("MissingPermission")
private fun configureEmitter(){
    if (!isUsingLocationNativeApi)
      locationEmitter = reactiveLocationProvider.getUpdatedLocation(reactiveLocationRequest)
    else{
      configureNativeLocationEmitter()
    }
}

@SuppressLint("MissingPermission")
private fun configureNativeLocationEmitter() {

    mLocationCallbackNativeApi = object : LocationListener {

        override fun onLocationChanged(location: Location) {
            subject.onNext(location)
        }

        override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}

        override fun onProviderEnabled(provider: String) {}

        override fun onProviderDisabled(provider: String) {}

    }

    try {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                (geoEventsIntervalSeconds * 1000).toLong(),
                geoEventsDistanceMeters.toFloat(),
                mLocationCallbackNativeApi,
                Looper.getMainLooper())
    } catch (ignored: IllegalArgumentException) {
        ignored.printStackTrace()
    }

    try {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                (geoEventsIntervalSeconds * 1000).toLong(),
                geoEventsDistanceMeters.toFloat(),
                mLocationCallbackNativeApi,
                Looper.getMainLooper())
    } catch (ignored: IllegalArgumentException) {
        ignored.printStackTrace()
    }
}

@SuppressLint("MissingPermission")
override fun onLocationUpdate(): Observable<Location> {
    return locationEmitter
}

override fun stopLocationUpdates() {
    if(isUsingLocationNativeApi)
    locationManager.removeUpdates(mLocationCallbackNativeApi)
  }
}
</code>```

So everything is fine, but now i want to have the gms implementation of this in different project module(so i don't need to have gms dependencies in the gradle) and also the native implementation to the other module in Android Studio.

The final structure of the project in AndroidStudio will be like location_core, location_gms, location_native.

The location_core must not be aware of location_gms and native, i guess in opposite to them - they will have the dependency to location_core.

So now, i i have just location_core project module and a LocationClient class, which will provide the context:

```<code>class LocationClient @Inject constructor(val nexoLocationManager: NexoLocationManager){
companion object {

    private var locationClient: LocationClient? = null

    fun obtainLocationClient(context: Context): LocationClient{
        val result = locationClient ?:
                DaggerLocationComponent
                        .builder()
                        .context(context)
                        .build()
                        .locationClient()

        locationClient = result
        return result
    }
  }
}
</code>```

It is using some Dagger Component, which provide him all the implementation of different objects.
So i want to move this LocationClient or make it abstract in location_core project module and move the implementation of it in each location_gms and location_native project module in AndroidStudio.

So the LocationClient class in each of them will provide the different implementation of this RxRepository.
For now in each location_gms and location_native project module i have just implementation class which implements the repository rxLocationRepository(which i move from the implementation written above) on its own way.

The problem is i don't know exactly how to manage all of this with Dagger.
Now i am using Dagger like this in my location_core, here is the LocationComponent:

```<code>@Singleton
@Component(modules = arrayOf(LocationModule::class))
interface LocationComponent{
fun locationClient(): LocationClient

@Component.Builder
interface Builder {
    @BindsInstance
    fun context(context: Context): Builder
    fun build(): LocationComponent
 }

}
</code>```

and its module:

```<code>@Module
class LocationModule {

//some stuff

    @Provides
@Singleton
fun providesRxLocationRepository(
                                 reactiveLocationProvider: ReactiveLocationProvider,
                                 reactiveLocationRequest: LocationRequest,
                                 @Named("CONFIG_LOCATION_USE_NATIVE_API")isUsingLocationNativeApi: Boolean,
                                 locationManager: LocationManager,
                                 @Named("CONFIG_LOCATION_GEO_EVENTS_DISTANCE_METERS")geoEventsDistanceMeters: Int,
                                 @Named("CONFIG_LOCATION_GEO_EVENTS_INTERVAL_SECONDS")geoEventsIntervalSeconds: Int
): RxLocationRepository = RxLocationRepositoryImpl(
        reactiveLocationProvider,
        reactiveLocationRequest,
        isUsingLocationNativeApi,
        locationManager,
        geoEventsDistanceMeters,
        geoEventsIntervalSeconds)

//some other stuff
}
</code>```

So how to write the actual LocationClient in each of the modules - location_gms and the location_native? How to provide the implementation of the rxLocationRepository which is in each of the location_gms and location_native project modules with Dagger, so that i can just use the interface RxLocationRepository in my location_core module and don't be bother of its implementation, because it will be in each project module?

Of course i must point, that those 3 modules never be together i guess, it will be 2 modules in each build_variant i guess.
So i have to get rid of the google services dependency in location_core project module build.gradle.

UPDATE

How i can actually don't have Dagger component in my location_core, in which i am using it in tests like:

 val component = DaggerLocationTestInstrumentalComponent.builder().context(InstrumentationRegistry.getContext()).build()
    val database = component.testDatabase()
    val locationManager = component.locationClient().nexoLocationManager

答:
Of course i must point, that those 3 modules never be together i guess, it will be 2 modules in each build_variant i guess.

That's the main point to pay attention. Your component definition shouldn't be inside location_core. Instead, it should be on "consumer" side. By consumer, I mean forth module that actually uses location. Let's call it consumer_module.

How I would approach this task.

Both location_gms and location_native should contain LocationModule with different implementation. Use the same package name for LocationModule in both modules.

consumer_module contains LocationComponent. Depending on build variant it will be resolved to LocationModule from location_gms or location_native.

Another approach would be the same for LocationModule, but creating in consumer_module two LocationComponent. Each in different build variant. In that approach you don't have to keep same package name for LocationModule.

Body:
I want to be able to have 2 different reactive implementation of the interface that is getting user location in other project module in AndroidStudio.

So to be specific it can be by using gms, or by just native android LocationManager.

Here is my repository interface:

interface RxLocationRepository {

@SuppressLint("MissingPermission")
fun onLocationUpdate(): Observable<Location>

fun stopLocationUpdates()
}

So for now, i implement this interface here, in class that is in the same project module in AndroidStudio:

class RxLocationRepositoryImpl(val reactiveLocationProvider: ReactiveLocationProvider,
                           val reactiveLocationRequest: LocationRequest,
                           val isUsingLocationNativeApi: Boolean,
                           val locationManager: LocationManager,
                           val geoEventsDistanceMeters: Int,
                           val geoEventsIntervalSeconds: Int
) : RxLocationRepository {

var locationToPopulate: Location = Location(LocationManager.GPS_PROVIDER)
lateinit var mLocationCallbackNativeApi: LocationListener
private val subject: BehaviorSubject<Location> = BehaviorSubject.createDefault(locationToPopulate)
var locationEmitter: Observable<Location> = subject.hide()

init {
    configureEmitter()
}

@SuppressLint("MissingPermission")
private fun configureEmitter(){
    if (!isUsingLocationNativeApi)
      locationEmitter = reactiveLocationProvider.getUpdatedLocation(reactiveLocationRequest)
    else{
      configureNativeLocationEmitter()
    }
}

@SuppressLint("MissingPermission")
private fun configureNativeLocationEmitter() {

    mLocationCallbackNativeApi = object : LocationListener {

        override fun onLocationChanged(location: Location) {
            subject.onNext(location)
        }

        override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}

        override fun onProviderEnabled(provider: String) {}

        override fun onProviderDisabled(provider: String) {}

    }

    try {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                (geoEventsIntervalSeconds * 1000).toLong(),
                geoEventsDistanceMeters.toFloat(),
                mLocationCallbackNativeApi,
                Looper.getMainLooper())
    } catch (ignored: IllegalArgumentException) {
        ignored.printStackTrace()
    }

    try {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                (geoEventsIntervalSeconds * 1000).toLong(),
                geoEventsDistanceMeters.toFloat(),
                mLocationCallbackNativeApi,
                Looper.getMainLooper())
    } catch (ignored: IllegalArgumentException) {
        ignored.printStackTrace()
    }
}

@SuppressLint("MissingPermission")
override fun onLocationUpdate(): Observable<Location> {
    return locationEmitter
}

override fun stopLocationUpdates() {
    if(isUsingLocationNativeApi)
    locationManager.removeUpdates(mLocationCallbackNativeApi)
  }
}

So everything is fine, but now i want to have the gms implementation of this in different project module(so i don't need to have gms dependencies in the gradle) and also the native implementation to the other module in Android Studio.

The final structure of the project in AndroidStudio will be like location_core, location_gms, location_native.

The location_core must not be aware of location_gms and native, i guess in opposite to them - they will have the dependency to location_core.

So now, i i have just location_core project module and a LocationClient class, which will provide the context:

class LocationClient @Inject constructor(val nexoLocationManager: NexoLocationManager){
companion object {

    private var locationClient: LocationClient? = null

    fun obtainLocationClient(context: Context): LocationClient{
        val result = locationClient ?:
                DaggerLocationComponent
                        .builder()
                        .context(context)
                        .build()
                        .locationClient()

        locationClient = result
        return result
    }
  }
}

It is using some Dagger Component, which provide him all the implementation of different objects.
So i want to move this LocationClient or make it abstract in location_core project module and move the implementation of it in each location_gms and location_native project module in AndroidStudio.

So the LocationClient class in each of them will provide the different implementation of this RxRepository.
For now in each location_gms and location_native project module i have just implementation class which implements the repository rxLocationRepository(which i move from the implementation written above) on its own way.

The problem is i don't know exactly how to manage all of this with Dagger.
Now i am using Dagger like this in my location_core, here is the LocationComponent:

@Singleton
@Component(modules = arrayOf(LocationModule::class))
interface LocationComponent{
fun locationClient(): LocationClient

@Component.Builder
interface Builder {
    @BindsInstance
    fun context(context: Context): Builder
    fun build(): LocationComponent
 }

}

and its module:

@Module
class LocationModule {

//some stuff

    @Provides
@Singleton
fun providesRxLocationRepository(
                                 reactiveLocationProvider: ReactiveLocationProvider,
                                 reactiveLocationRequest: LocationRequest,
                                 @Named("CONFIG_LOCATION_USE_NATIVE_API")isUsingLocationNativeApi: Boolean,
                                 locationManager: LocationManager,
                                 @Named("CONFIG_LOCATION_GEO_EVENTS_DISTANCE_METERS")geoEventsDistanceMeters: Int,
                                 @Named("CONFIG_LOCATION_GEO_EVENTS_INTERVAL_SECONDS")geoEventsIntervalSeconds: Int
): RxLocationRepository = RxLocationRepositoryImpl(
        reactiveLocationProvider,
        reactiveLocationRequest,
        isUsingLocationNativeApi,
        locationManager,
        geoEventsDistanceMeters,
        geoEventsIntervalSeconds)

//some other stuff
}

So how to write the actual LocationClient in each of the modules - location_gms and the location_native? How to provide the implementation of the rxLocationRepository which is in each of the location_gms and location_native project modules with Dagger, so that i can just use the interface RxLocationRepository in my location_core module and don't be bother of its implementation, because it will be in each project module?

Of course i must point, that those 3 modules never be together i guess, it will be 2 modules in each build_variant i guess.
So i have to get rid of the google services dependency in location_core project module build.gradle.

UPDATE

How i can actually don't have Dagger component in my location_core, in which i am using it in tests like:

 val component = DaggerLocationTestInstrumentalComponent.builder().context(InstrumentationRegistry.getContext()).build()
    val database = component.testDatabase()
    val locationManager = component.locationClient().nexoLocationManager


问:
Get only unique elements from two lists
If I have two lists (may be with different len):

```<code>x = [1,2,3,4]
f = [1,11,22,33,44,3,4]

result = [11,22,33,44]
</code>```

im doing:

```<code>for element in f:
    if element in x:
        f.remove(element)
</code>```

I'm getting

```<code>result = [11,22,33,44,4]
</code>```

答:
if you want to get  only unique elements from the two list then you can get it by..</p>

```<code>a=[1,2,3,4,5]
b= [2,4,1]
list(set(a) - set(b))
OP:- [3, 5]
</code>```

Title: Get only unique elements from two lists

Body:
If I have two lists (may be with different len):

x = [1,2,3,4]
f = [1,11,22,33,44,3,4]

result = [11,22,33,44]

im doing:

for element in f:
    if element in x:
        f.remove(element)

I'm getting

result = [11,22,33,44,4]

Body:
if you want to get  only unique elements from the two list then you can get it by..

a=[1,2,3,4,5]
b= [2,4,1]
list(set(a) - set(b))
OP:- [3, 5]


问:
E: Sub-process /usr/bin/dpkg returned an error code (1)
While trying to uninstall php7.0, I got the following error:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Package 'php7.0' is not installed, so not removed
The following packages were automatically installed and are no longer required:
  linux-headers-4.4.0-92 linux-headers-4.4.0-92-generic linux-headers-4.4.0-93 linux-headers-4.4.0-93-generic linux-headers-4.4.0-96
  linux-headers-4.4.0-96-generic linux-image-4.4.0-92-generic linux-image-4.4.0-93-generic linux-image-4.4.0-96-generic
  linux-image-extra-4.4.0-92-generic linux-image-extra-4.4.0-93-generic linux-image-extra-4.4.0-96-generic
  linux-signed-image-4.4.0-92-generic linux-signed-image-4.4.0-93-generic linux-signed-image-4.4.0-96-generic
Use 'sudo apt autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 46 not upgraded.
2 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Setting up libapache2-mod-php7.0 (7.0.22-0ubuntu0.16.04.1) ...
dpkg: error processing package libapache2-mod-php7.0 (--configure):
 subprocess installed post-installation script returned error exit status 1
No apport report written because the error message indicates its a followup error from a previous failure.
                                                                                dpkg: dependency problems prevent configuration of libapache2-mod-php:
 libapache2-mod-php depends on libapache2-mod-php7.0; however:
  Package libapache2-mod-php7.0 is not configured yet.

dpkg: error processing package libapache2-mod-php (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 libapache2-mod-php7.0
 libapache2-mod-php
E: Sub-process /usr/bin/dpkg returned an error code (1)
</code>```

I used the following command:

sudo apt-get remove php7.0

I searched the whole internet and tried all the solutions but did not got the right solution.

答:
This is mostly because some package or dependency got stuck in package manager.

Try the following commands (with sudo):

```<code>apt-get purge
apt-get --autoremove
apt-get --autoclean
</code>```

Then try uninstalling php7.0 using the following command:

```<code>apt-get --purge remove php7.0
</code>```

Body:
While trying to uninstall php7.0, I got the following error:

Reading package lists... Done
Building dependency tree
Reading state information... Done
Package 'php7.0' is not installed, so not removed
The following packages were automatically installed and are no longer required:
  linux-headers-4.4.0-92 linux-headers-4.4.0-92-generic linux-headers-4.4.0-93 linux-headers-4.4.0-93-generic linux-headers-4.4.0-96
  linux-headers-4.4.0-96-generic linux-image-4.4.0-92-generic linux-image-4.4.0-93-generic linux-image-4.4.0-96-generic
  linux-image-extra-4.4.0-92-generic linux-image-extra-4.4.0-93-generic linux-image-extra-4.4.0-96-generic
  linux-signed-image-4.4.0-92-generic linux-signed-image-4.4.0-93-generic linux-signed-image-4.4.0-96-generic
Use 'sudo apt autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 46 not upgraded.
2 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Setting up libapache2-mod-php7.0 (7.0.22-0ubuntu0.16.04.1) ...
dpkg: error processing package libapache2-mod-php7.0 (--configure):
 subprocess installed post-installation script returned error exit status 1
No apport report written because the error message indicates its a followup error from a previous failure.
                                                                                dpkg: dependency problems prevent configuration of libapache2-mod-php:
 libapache2-mod-php depends on libapache2-mod-php7.0; however:
  Package libapache2-mod-php7.0 is not configured yet.

dpkg: error processing package libapache2-mod-php (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 libapache2-mod-php7.0
 libapache2-mod-php
E: Sub-process /usr/bin/dpkg returned an error code (1)

I used the following command:

sudo apt-get remove php7.0

I searched the whole internet and tried all the solutions but did not got the right solution.

Body:
This is mostly because some package or dependency got stuck in package manager.

Try the following commands (with sudo):

apt-get purge
apt-get --autoremove
apt-get --autoclean

Then try uninstalling php7.0 using the following command:

apt-get --purge remove php7.0


问:
Increment column before response download - Laravel
I want to simply increment a column for each download but it adds 2 or more instead of 1. Here is my code:

```<code> public function download(Music $music)
{

    $music->increment('downloads');

    $file=$music->getFilePath();
    return response()->download($file,$music->title);
}
</code>```

However, if I remove response()->download... line it works correctly. What's the problem and how to solve it?

答:
Check if the download function is being called multiple times, not just once.

Implement response download function by yourself.

[update]

IDM issue. Can be solved by separating increment and download routes.

Body:
I want to simply increment a column for each download but it adds 2 or more instead of 1. Here is my code:

 public function download(Music $music)
{

    $music->increment('downloads');

    $file=$music->getFilePath();
    return response()->download($file,$music->title);
}

However, if I remove response()->download... line it works correctly. What's the problem and how to solve it?