问:
IIS rewrite rules using {C:n} as input
I'm trying to rewrite url only in case part of the queryString present in the path as well
For example:

This url: http://www.mywebsite.com/func/api.ashx?method=func&p1=v1 is valid

but this url http://www.mywebsite.com/path/api.ashx?method=func&p1=v1 will not be rewriten.

So far this is what I have:

```<code><rewrite>
        <rules>
            <rule name="Name1" enabled="true">
                <match url="^(.+)" />
                <conditions trackAllCaptures="true">
                    <add input="{QUERY_STRING}" pattern="method=([^&]*)" ignoreCase="false" />
                    <add input="{PATH_INFO}" pattern="\/(.*)\/" />
                    <add input="{{C:1}}" pattern="{{C:2}}" /> <!-- this is not working -->
                </conditions>
                <action type="Rewrite" url="/api.ashx" appendQueryString="true" />
            </rule>
        </rules>
    </rewrite>
</code>```

Is this can be done? whats the best way to check if method is part of the path assuming the value is dynamic.

BTW - I tried using groups in my patterns method=(?<methodName>[^&]*) IIS don't like it.

Thanks

答:
I'm afraid we can't do this in IIS. Because regex expression is not supported in "input" attribute and "{" is not support in "pattern" attribute.  So we can't find a way to match two capture group.

You may need only do this in code level.

Title: IIS rewrite rules using {C:n} as input

Body:
I'm trying to rewrite url only in case part of the queryString present in the path as well
For example:

This url: http://www.mywebsite.com/func/api.ashx?method=func&p1=v1 is valid

but this url http://www.mywebsite.com/path/api.ashx?method=func&p1=v1 will not be rewriten.

So far this is what I have:

<rewrite>
        <rules>
            <rule name="Name1" enabled="true">
                <match url="^(.+)" />
                <conditions trackAllCaptures="true">
                    <add input="{QUERY_STRING}" pattern="method=([^&]*)" ignoreCase="false" />
                    <add input="{PATH_INFO}" pattern="\/(.*)\/" />
                    <add input="{{C:1}}" pattern="{{C:2}}" />
                </conditions>
                <action type="Rewrite" url="/api.ashx" appendQueryString="true" />
            </rule>
        </rules>
    </rewrite>

Is this can be done? whats the best way to check if method is part of the path assuming the value is dynamic.

BTW - I tried using groups in my patterns method=(?<methodName>[^&]*) IIS don't like it.

Thanks


来源: stackexchange

问:
Create a boolean column based on condition in pandas
I have a data frame as shown below

```<code>ID    DURATION   STATUS   CONSIDER
1     30         ACTIVE   True
2     780        CLOSED   True
3     745        ACTIVE   False
4     366        ACTIVE   False
5     367        ACTIVE   True
</code>```

I would like to create a new column ESTIMATION_FLAG, which is True when DURATION < 700 and STATUS == ACTIVE and CONSIDER == True.

Expected output:

```<code>ID    DURATION   STATUS   CONSIDER  ESTIMATION_FLAG
1     30         ACTIVE   True      True
2     780        CLOSED   True      False
3     745        ACTIVE   False     False
4     366        ACTIVE   False     False
5     367        ACTIVE   True      True
</code>```

答:
Use Series.lt and Series.eq for masks and chain by & for bitwise AND, advantage is less ():

```<code>df['ESTIMATION_FLAG'] = df['DURATION'].lt(700) & df['STATUS'].eq('ACTIVE') & df['CONSIDER']
print (df)
   ID  DURATION  STATUS  CONSIDER  ESTIMATION_FLAG
0   1        30  ACTIVE      True             True
1   2       780  CLOSED      True            False
2   3       745  ACTIVE     False            False
3   4       366  ACTIVE     False            False
4   5       367  ACTIVE      True             True
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a data frame as shown below

ID    DURATION   STATUS   CONSIDER
1     30         ACTIVE   True
2     780        CLOSED   True
3     745        ACTIVE   False
4     366        ACTIVE   False
5     367        ACTIVE   True

I would like to create a new column ESTIMATION_FLAG, which is True when DURATION < 700 and STATUS == ACTIVE and CONSIDER == True.

Expected output:

ID    DURATION   STATUS   CONSIDER  ESTIMATION_FLAG
1     30         ACTIVE   True      True
2     780        CLOSED   True      False
3     745        ACTIVE   False     False
4     366        ACTIVE   False     False
5     367        ACTIVE   True      True

Body:
Use Series.lt and Series.eq for masks and chain by & for bitwise AND, advantage is less ():

df['ESTIMATION_FLAG'] = df['DURATION'].lt(700) & df['STATUS'].eq('ACTIVE') & df['CONSIDER']
print (df)
   ID  DURATION  STATUS  CONSIDER  ESTIMATION_FLAG
0   1        30  ACTIVE      True             True
1   2       780  CLOSED      True            False
2   3       745  ACTIVE     False            False
3   4       366  ACTIVE     False            False
4   5       367  ACTIVE      True             True


问:
Join two dataframes to get cartesian product
How to join two dataframes and get the cartesian product of all rows in both dataframes.

df1:

```<code>   values
0       4
1       5
2       6
</code>```

df2:

```<code>   values
0       7
1       8
2       9
</code>```

Expected Output:

```<code>   values_x  values_y
0         4         7
1         4         8
2         4         9
3         5         7
4         5         8
5         5         9
6         6         7
7         6         8
8         6         9
</code>```

答:
You can use a dummy column to merge on:

```<code>df1.assign(dummy=1).merge(df2.assign(dummy=1), on='dummy', how='outer').drop('dummy', axis=1)
</code>```

Output:

```<code>   values_x  values_y
0         4         7
1         4         8
2         4         9
3         5         7
4         5         8
5         5         9
6         6         7
7         6         8
8         6         9
</code>```

Body:
How to join two dataframes and get the cartesian product of all rows in both dataframes.

df1:

   values
0       4
1       5
2       6

df2:

   values
0       7
1       8
2       9

Expected Output:

   values_x  values_y
0         4         7
1         4         8
2         4         9
3         5         7
4         5         8
5         5         9
6         6         7
7         6         8
8         6         9

Body:
You can use a dummy column to merge on:

df1.assign(dummy=1).merge(df2.assign(dummy=1), on='dummy', how='outer').drop('dummy', axis=1)

Output:

   values_x  values_y
0         4         7
1         4         8
2         4         9
3         5         7
4         5         8
5         5         9
6         6         7
7         6         8
8         6         9


问:
Can I have one service that exposes intranet and internet operations?
Assume I have a service that has about 10 operations, but 2 of them are needed for intranet purposes only.  How would I configure the two operations to be restricted only to the intranet?</p>

答:
The same WCF service can expose multiple contracts. Put the internet operations in a seaparate interface and expose it using security settings that make sense for an intranet environment.

For example: Your internet operations could have an endpoint that uses UserName security and publishes the operations via a mex point. The intranet operations could have an endpoint that uses Windows based security and doesn't expose a MEX point.

ContentLicense: CC BY-SA 3.0


问:
What is the difference between if(a == (1,2)) and if(a == 1,2)?
What is the difference betweenif(a == (1,2))  and  if(a == 1,2) ?

```<code>#include<stdio.h>
int main()
{
  int a = 2;
  if(a == (1,2))
    printf("Hello");
  if(a == 1,2)
    printf("World");

  return 0;
}
</code>```

答:
In the both conditions of the if statements there is used the comma operator

The second condition is equivalently can be rewritten like

```<code>if( ( a == 1 ), 2)
</code>```

The value of the comma operator is the value of the second operand. So the condition in the second if statement will always evaluate to true because 2 is not equal to 0.

The condition in the first if statement can be rewritten like

```<code>if(a == 2)
</code>```

because the first expression (the integer constant 1) of the comma operator has no effect.

So the condition of the if statement evaluates to true only when a is equal to 2.

Body:
What is the difference betweenif(a == (1,2))  and  if(a == 1,2) ?

#include<stdio.h>
int main()
{
  int a = 2;
  if(a == (1,2))
    printf("Hello");
  if(a == 1,2)
    printf("World");

  return 0;
}

Body:
In the both conditions of the if statements there is used the comma operator

The second condition is equivalently can be rewritten like

if( ( a == 1 ), 2)

The value of the comma operator is the value of the second operand. So the condition in the second if statement will always evaluate to true because 2 is not equal to 0.

The condition in the first if statement can be rewritten like

if(a == 2)

because the first expression (the integer constant 1) of the comma operator has no effect.

So the condition of the if statement evaluates to true only when a is equal to 2.


问:
How to set Exposed Dropdown Menus' start value?
Failing to set the start value of the newly introduced exposed dropdown menu.

https://github.com/material-components/material-components-android/blob/master/docs/components/Menu.md#exposed-dropdown-menus

I am trying to get the first value set but when I try to use the "selectedItemPosition" I am getting an error, that those attribute has not been found.

Also, trying to achieve this with java code, gave me an error, that there is no index.

// Trying to set it via java code
Binding.dropdownSex.setAdapter(getAdapter(getResources().getStringArray(R.array.fragment_me_spinner_sex)));
        mBinding.dropdownSex.setSelection(1);   // java.lang.IndexOutOfBoundsException: setSpan (1 ... 1) ends beyond length 0

// just a small method to get the adapter
private ArrayAdapter<String> getAdapter(String[] elements) {
        return new ArrayAdapter<>(Objects.requireNonNull(getContext()),
                R.layout.dropdown_menu_popup_item,
                elements);
    }
```

<p>also...</p>

<pre class="lang-xml prettyprint-override"><code><!-- attribute android:selectedItemPosition not found. -->
 <com.google.android.material.textfield.TextInputLayout
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingStart="32dp"
                android:paddingEnd="32dp"
                >

                <AutoCompleteTextView
                    android:id="@+id/dropdown_sex"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/sex"
                    android:focusable="false"
                    android:cursorVisible="false"
</code>```

Someone an idea of how to fix this?

答:
Try below after set adapter method</p>

```<code>dropdown_sex.setText(loadCenterList.get(mViewFlipper.displayedChild - 1), false)
</code>```

Body:
Failing to set the start value of the newly introduced exposed dropdown menu.

https://github.com/material-components/material-components-android/blob/master/docs/components/Menu.md#exposed-dropdown-menus

I am trying to get the first value set but when I try to use the "selectedItemPosition" I am getting an error, that those attribute has not been found.

Also, trying to achieve this with java code, gave me an error, that there is no index.

// Trying to set it via java code
Binding.dropdownSex.setAdapter(getAdapter(getResources().getStringArray(R.array.fragment_me_spinner_sex)));
        mBinding.dropdownSex.setSelection(1);   // java.lang.IndexOutOfBoundsException: setSpan (1 ... 1) ends beyond length 0

// just a small method to get the adapter
private ArrayAdapter<String> getAdapter(String[] elements) {
        return new ArrayAdapter<>(Objects.requireNonNull(getContext()),
                R.layout.dropdown_menu_popup_item,
                elements);
    }

also...

 <com.google.android.material.textfield.TextInputLayout
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingStart="32dp"
                android:paddingEnd="32dp"
                >

                <AutoCompleteTextView
                    android:id="@+id/dropdown_sex"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/sex"
                    android:focusable="false"
                    android:cursorVisible="false"

Someone an idea of how to fix this?

Body:
Try below after set adapter method

dropdown_sex.setText(loadCenterList.get(mViewFlipper.displayedChild - 1), false)


问:
How do i differentiate different subclasses in a array of the superclass?
My setup is the following.
I have a superclass called "bottles" and 2 different subclasses, "water" and "soda". There's an array filled with countless of both of these and my goal is to write a method that returns the total liter values of only one of these subclasses. What would be the best way to accomplish that? As far as i understand 'instanceof' has no use here.

To clarify i only want to know what operator/method is used to compare:

```<code>if (bottles[0]==soda){
      ...
}
</code>```

答:
```<code>if(bottles[i] instanceof Soda) {
    return bottles[i].getRealLiter();
    }
 else if(bottles[i] instanceof Water) {
    return 0;
}
</code>```

Body:
My setup is the following.
I have a superclass called "bottles" and 2 different subclasses, "water" and "soda". There's an array filled with countless of both of these and my goal is to write a method that returns the total liter values of only one of these subclasses. What would be the best way to accomplish that? As far as i understand 'instanceof' has no use here.

To clarify i only want to know what operator/method is used to compare:

if (bottles[0]==soda){
      ...
}


问:
Program to count the number of bits set in c
I have tried to count the number of bits set in an integer value in c.
But for some values it is showing the correct bit set count and for some values it is not.

PFB program code

```<code>int main()
{
    int a=512,i=0,j=1,count=0,k=0;

    for(i=0;i<31;i++)
    {
        if(k=a&j)
        {
            count++;
            j=j<<1;
        }
    }
    printf("the total bit set countis %d",count);
}
</code>```

The output of set bit value count of 512 is showing as zero and if the value used is 511 count is showing as 9.

Please help me to correct the program.

答:
If you're using gcc/clang compiler, you can use the builtin function __builtin_popcount

```<code>unsigned int user_input = 100
int count = __builtin_popcount(n); // count == 3
</code>```

When I'm not looking for cross-platform I'll use this function since its highly optimised.

Body:
I have tried to count the number of bits set in an integer value in c.
But for some values it is showing the correct bit set count and for some values it is not.

PFB program code

int main()
{
    int a=512,i=0,j=1,count=0,k=0;

    for(i=0;i<31;i++)
    {
        if(k=a&j)
        {
            count++;
            j=j<<1;
        }
    }
    printf("the total bit set countis %d",count);
}

The output of set bit value count of 512 is showing as zero and if the value used is 511 count is showing as 9.

Please help me to correct the program.

Body:
If you're using gcc/clang compiler, you can use the builtin function __builtin_popcount

unsigned int user_input = 100
int count = __builtin_popcount(n); // count == 3

When I'm not looking for cross-platform I'll use this function since its highly optimised.


答:
a == 1,2 is equivalent to (a == 1),2 due to operator precedence

And because of how the comma operator works, (a == 1),2 will result in 2. And a == (1,2) will be the same as a == 2.

So in effect your two conditions are like

```<code>if (a == 2)
    printf("Hello");
if(2)
    printf("World");
</code>```

The first condition will be true only if a is equal to 2. The second condition will always be true (only zero is false).

Title: What is the difference between if(a == (1,2)) and if(a == 1,2)?

Body:
a == 1,2 is equivalent to (a == 1),2 due to operator precedence

And because of how the comma operator works, (a == 1),2 will result in 2. And a == (1,2) will be the same as a == 2.

So in effect your two conditions are like

if (a == 2)
    printf("Hello");
if(2)
    printf("World");

The first condition will be true only if a is equal to 2. The second condition will always be true (only zero is false).


问:
How to avoid search Query OF @UniqueConstraint in JPA
I want to improve performance by not doing search query where i know that data will be unique.(In my app every new user will require default data. Which will be created in server side where there is no need to do unique test.)</p>

答: @UniqueConstraint is only used for schema generation. JPA doesn't do any search for unique constraints at runtime.</p>


问:
How can I randomly capitalise letters in a string
I'm sorry if this has been asked before, but I can't seem to find the right answer.

I'm trying to create a random password generator using Javascript. I've set meself 4 basic requirements:

Must contain letters, numbers and special characters

Must be 14 characters

Must have upper and lower case lettering

Must log the result as a string

Here is what I have:

```<code>var characters = 'abcdefghijklmnoqrstuvwxyz0123456789?<>!"£$%^&*()-+./';
var results = '';
var length = characters.length;

function randomPassword() {

for (i=0; i<=13; i++) {
    var mix = characters.charAt(Math.floor(Math.random() * length));
    var newString = results += mix;
    }
    console.log(newString);
}

randomPassword();
</code>```

The code above passes all of my requirements apart from the upper and lower case letters. Is there a way to randomly capitalise some of the letters in my string? I've tried playing with .toUpperCase() in the same way I have to create my 'mix' variable, but I can't work out how to do it.

This isn't for any real life projects. I'm just using this as a way to try to learn Javascript, so any advice would be greatly appreciated :)

Thanks!

答:
Here's one way</p>

```<code>myString.toLowerCase().split('').map(function(c){
return Math.random() < .5? c : c.toUpperCase();
}).join('');
</code>```

Body:
I'm sorry if this has been asked before, but I can't seem to find the right answer.

I'm trying to create a random password generator using Javascript. I've set meself 4 basic requirements:

Must contain letters, numbers and special characters

Must be 14 characters

Must have upper and lower case lettering

Must log the result as a string

Here is what I have:

var characters = 'abcdefghijklmnoqrstuvwxyz0123456789?<>!"£$%^&*()-+./';
var results = '';
var length = characters.length;

function randomPassword() {

for (i=0; i<=13; i++) {
    var mix = characters.charAt(Math.floor(Math.random() * length));
    var newString = results += mix;
    }
    console.log(newString);
}

randomPassword();

The code above passes all of my requirements apart from the upper and lower case letters. Is there a way to randomly capitalise some of the letters in my string? I've tried playing with .toUpperCase() in the same way I have to create my 'mix' variable, but I can't work out how to do it.

This isn't for any real life projects. I'm just using this as a way to try to learn Javascript, so any advice would be greatly appreciated :)

Thanks!

Body:
Here's one way

myString.toLowerCase().split('').map(function(c){
return Math.random() < .5? c : c.toUpperCase();
}).join('');


问:
ClassCastException while executing my app with minifyEnabled true
I have an Android system app that has a custom BroadCastReceiver in manifest (this is to be run in Android M device):
My manifest:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:sharedUserId="android.uid.system"
    package="mypackagename">

   ....

    <!-- custom permissions -->
    <uses-permission android:name="mypackagename.ASK_DISPLAY_INFO"
        android:protectionLevel="signatureOrSystem"/>

    <permission android:name="mypackagename.ASK_DISPLAY_INFO" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        ....

        <!-- custom receiver -->
        <receiver android:name=".CustomReceiver"
            android:permission="mypackagename.ASK_DISPLAY_INFO">
            <intent-filter>
                <action android:name="GET_HDMI_SUPPORTED_MODES"/>
                <action android:name="CHANGE_HDMI_RESOLUTION"/>
            </intent-filter>
        </receiver>

    </application>

</manifest>
</code>```

And I have enabled in gradle Proguard obfuscation:

```<code>        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

        }
</code>```

I have another test app that sends broadcasts to this app. The thing is, with mignifyEnabled false works, but with mignifyEnabled true when receives a broadcast intent it gives the error:

java.lang.RuntimeException: Unable to instantiate receiver mypackagename.CustomReceiver: java.lang.ClassCastException: mypackagename.CustomReceiver cannot be cast to android.content.BroadcastReceiver

Adding the following rule to proguard-rules.pro:

-keep class android.content.BroadcastReceiver { *; }

When receiving an intent throws the error:

java.lang.AbstractMethodError: abstract method "void android.content.BroadcastReceiver.onReceive(android.content.Context, android.content.Intent)"

Here is my broadcastreceiver definition:

```<code>
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

public class CustomReceiver extends BroadcastReceiver {
    ...

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() != null) {
            Log.i(TAG, "CustomReceiver received action: "+intent.getAction());

            if (intent.getAction().equals(GET_HDMI_SUPPORTED_MODES)) {
                new GetHDMIModesTask(context).execute();
            }  else if (intent.getAction().equals(CHANGE_HDMI_RESOLUTION) && intent.getExtras() != null && intent.hasExtra(EXTRA_HDMI_MODE) ) {
                new ChangeHDMIModeTask(context, intent.getStringExtra(EXTRA_HDMI_MODE)).execute();
            }
        }

    }

}
</code>```

As I'm very new to Proguard rules and I need this obfuscated, I would appreciate if someone can tell me which rules can I specify to solve this issue

答:
I have done a workaround in this, removed CustomerReceiver from manifest, added an custom application class and defined the BroadcastReceiver in there. Added the proguard rules:

```<code> -keep class android.app.Application {
        public <fields>;
        private <fields>;
       public <methods>;
    }

    -keep public class * extends android.app.Application
</code>```

The issue was gone

Body:
I have an Android system app that has a custom BroadCastReceiver in manifest (this is to be run in Android M device):
My manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:sharedUserId="android.uid.system"
    package="mypackagename">

   ....

    <uses-permission android:name="mypackagename.ASK_DISPLAY_INFO"
        android:protectionLevel="signatureOrSystem"/>

    <permission android:name="mypackagename.ASK_DISPLAY_INFO" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        ....

        <receiver android:name=".CustomReceiver"
            android:permission="mypackagename.ASK_DISPLAY_INFO">
            <intent-filter>
                <action android:name="GET_HDMI_SUPPORTED_MODES"/>
                <action android:name="CHANGE_HDMI_RESOLUTION"/>
            </intent-filter>
        </receiver>

    </application>

</manifest>

And I have enabled in gradle Proguard obfuscation:

        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

        }

I have another test app that sends broadcasts to this app. The thing is, with mignifyEnabled false works, but with mignifyEnabled true when receives a broadcast intent it gives the error:

java.lang.RuntimeException: Unable to instantiate receiver mypackagename.CustomReceiver: java.lang.ClassCastException: mypackagename.CustomReceiver cannot be cast to android.content.BroadcastReceiver

Adding the following rule to proguard-rules.pro:

-keep class android.content.BroadcastReceiver { *; }

When receiving an intent throws the error:

java.lang.AbstractMethodError: abstract method "void android.content.BroadcastReceiver.onReceive(android.content.Context, android.content.Intent)"

Here is my broadcastreceiver definition:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

public class CustomReceiver extends BroadcastReceiver {
    ...

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() != null) {
            Log.i(TAG, "CustomReceiver received action: "+intent.getAction());

            if (intent.getAction().equals(GET_HDMI_SUPPORTED_MODES)) {
                new GetHDMIModesTask(context).execute();
            }  else if (intent.getAction().equals(CHANGE_HDMI_RESOLUTION) && intent.getExtras() != null && intent.hasExtra(EXTRA_HDMI_MODE) ) {
                new ChangeHDMIModeTask(context, intent.getStringExtra(EXTRA_HDMI_MODE)).execute();
            }
        }

    }

}

As I'm very new to Proguard rules and I need this obfuscated, I would appreciate if someone can tell me which rules can I specify to solve this issue

Body:
I have done a workaround in this, removed CustomerReceiver from manifest, added an custom application class and defined the BroadcastReceiver in there. Added the proguard rules:

 -keep class android.app.Application {
        public <fields>;
        private <fields>;
       public <methods>;
    }

    -keep public class * extends android.app.Application

The issue was gone


问:
Jquery div strobe
I would like to have a div act like a strobe light with jquery. Basicly change the background color from black to white every 500 milliseconds.

How can I do that?

```<code><div id="strobe"></div>
</code>```

Thank you!

答:
The setInterval() function is your friend here.

You don't need to use JQuery, you can do it inn pure javascript - this is how you'd do it:

```<code>var elem = document.getElementById("strobe");
var strobeBackground = function() {
   (elem.style.backgroundColor == "white") ? elem.style.backgroundColor = "black" : elem.style.backgroundColor = "white";
}

setInterval(strobeBackground, 500);
</code>```

However if you want to do it in jQuery, here it is: http://jsfiddle.net/Ru9xt/2/

The HTML would look like this:

```<code> <div id="strobe" class="white">Hello</div>
</code>```

The CSS would look like this:

```<code>.white {
    background-color: white;
}
.black {
    background-color: black;
}
</code>```

And the JS is here:

```<code>setInterval(function () {
        $("#strobe").toggleClass('black');
    }, 500);
</code>```

Title: Jquery div strobe

Body:
I would like to have a div act like a strobe light with jquery. Basicly change the background color from black to white every 500 milliseconds.

How can I do that?

Thank you!

Body:
The setInterval() function is your friend here.

You don't need to use JQuery, you can do it inn pure javascript - this is how you'd do it:

var elem = document.getElementById("strobe");
var strobeBackground = function() {
   (elem.style.backgroundColor == "white") ? elem.style.backgroundColor = "black" : elem.style.backgroundColor = "white";
}

setInterval(strobeBackground, 500);

However if you want to do it in jQuery, here it is: http://jsfiddle.net/Ru9xt/2/

The HTML would look like this:

 <div id="strobe" class="white">Hello</div>

The CSS would look like this:

.white {
    background-color: white;
}
.black {
    background-color: black;
}

And the JS is here:

setInterval(function () {
        $("#strobe").toggleClass('black');
    }, 500);


问:
How to show component inside another dynamically?
I have a component LayersComponent.

```<code>@Component({
  selector: "app-layers",
  templateUrl: "./layers.component.html",
  styleUrls: ["./layers.component.sass"]
})
export class LayersComponent implements OnInit {
}
</code>```

Template is:

```<code><div class="Layers">
  Text

  <!-- Create component below -->
  <app-another-component></app-another-component>
</div>
</code>```

I want to create and show dinamically component <app-another-component></app-another-component> inside current component.

But I need send command create from another component not inside LayersComponent, but somewhere from another component in application.

How to do that?

I have tried:

```<code><div class="Layers">
   Text
   <ng-container *ngTemplateOutlet="app-another-component"></ng-container>
</div>
</code>```

But I dont know how to send command outside LayersComponent?

答:
Using ComponentFactoryResolver in Angular to handle dynamic loader for multiple components:

Here is sample code:

import {
    Component,
    ComponentFactory,
    ComponentRef,
    ComponentFactoryResolver,
    ViewContainerRef,
    ViewChild
} from '@angular/core'
import { AComponent } from './a.component';
import { BComponent } from './b.component';

@Component({
    selector: 'modal-resolver',
    template: `
        <template #modalContainer></template>
    `,
})
export class ModalResolver {
    @ViewChild("modalContainer", { read: ViewContainerRef }) container;
    @Input() name;
    componentRef: ComponentRef;

    listComponent: {
        'modalA': AComponent,
        'modalB': BComponent
    }

    constructor(private resolver: ComponentFactoryResolver) { }

    ngOnInit() {
        this.loadComponent(this.name);
    }
    loadComponent(type) {
        this.container.clear();
        const factory: ComponentFactory = this.resolver.resolveComponentFactory(this.listComponent[this.name]);

        this.componentRef = this.container.createComponent(factory);

        this.componentRef.instance.type = type;

        this.componentRef.instance.output.subscribe(event => console.log(event));

    }

    ngOnDestroy() {
        this.componentRef.destroy();
    }
}
```

<p>Then you use it:</p>

```<modal-resolver name="modalA"></modal-resolver>
```

You can read more from Angular document:
https://angular.io/guide/dynamic-component-loader

Body:
I have a component LayersComponent.

@Component({
  selector: "app-layers",
  templateUrl: "./layers.component.html",
  styleUrls: ["./layers.component.sass"]
})
export class LayersComponent implements OnInit {
}

Template is:

  Text

  <app-another-component></app-another-component>

I want to create and show dinamically component <app-another-component></app-another-component> inside current component.

But I need send command create from another component not inside LayersComponent, but somewhere from another component in application.

How to do that?

I have tried:

   Text
   <ng-container *ngTemplateOutlet="app-another-component"></ng-container>

But I dont know how to send command outside LayersComponent?

Body:
Using ComponentFactoryResolver in Angular to handle dynamic loader for multiple components:

Here is sample code:

import {
    Component,
    ComponentFactory,
    ComponentRef,
    ComponentFactoryResolver,
    ViewContainerRef,
    ViewChild
} from '@angular/core'
import { AComponent } from './a.component';
import { BComponent } from './b.component';

@Component({
    selector: 'modal-resolver',
    template: `
        <template #modalContainer></template>
    `,
})
export class ModalResolver {
    @ViewChild("modalContainer", { read: ViewContainerRef }) container;
    @Input() name;
    componentRef: ComponentRef;

    listComponent: {
        'modalA': AComponent,
        'modalB': BComponent
    }

    constructor(private resolver: ComponentFactoryResolver) { }

    ngOnInit() {
        this.loadComponent(this.name);
    }
    loadComponent(type) {
        this.container.clear();
        const factory: ComponentFactory = this.resolver.resolveComponentFactory(this.listComponent[this.name]);

        this.componentRef = this.container.createComponent(factory);

        this.componentRef.instance.type = type;

        this.componentRef.instance.output.subscribe(event => console.log(event));

    }

    ngOnDestroy() {
        this.componentRef.destroy();
    }
}

Then you use it:

<modal-resolver name="modalA"></modal-resolver>

You can read more from Angular document:
https://angular.io/guide/dynamic-component-loader


问:
Is there a way to show endpoint present in my maven dependencies in swagger-ui
I am trying to list all the endpoints in my application including some of the endpoints present in the dependent libraries using Swagger. Is there any way to do so?</p>

答:
Swagger automatically fetch all the endpoints according to configuration. You have to mention the base url:</p>

```<code>return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .paths(PathSelectors.ant("/admin/**"))
            .build()
            .useDefaultResponseMessages(false);
</code>```

Body:
Swagger automatically fetch all the endpoints according to configuration. You have to mention the base url:

return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .paths(PathSelectors.ant("/admin/**"))
            .build()
            .useDefaultResponseMessages(false);


答:
Use </p>

```<code>df["ESTIMATION_FLAG"] = (df["DURATION"] < 700) & (df["STATUS"]=="ACTIVE") & (df["CONSIDER"]==True)
</code>```

Title: Create a boolean column based on condition in pandas

Body:
I have a data frame as shown below

ID    DURATION   STATUS   CONSIDER
1     30         ACTIVE   True
2     780        CLOSED   True
3     745        ACTIVE   False
4     366        ACTIVE   False
5     367        ACTIVE   True

I would like to create a new column ESTIMATION_FLAG, which is True when DURATION < 700 and STATUS == ACTIVE and CONSIDER == True.

Expected output:

ID    DURATION   STATUS   CONSIDER  ESTIMATION_FLAG
1     30         ACTIVE   True      True
2     780        CLOSED   True      False
3     745        ACTIVE   False     False
4     366        ACTIVE   False     False
5     367        ACTIVE   True      True

Body:
Use

df["ESTIMATION_FLAG"] = (df["DURATION"] < 700) & (df["STATUS"]=="ACTIVE") & (df["CONSIDER"]==True)


问:
NoReverseMatch at ...... in django
I am working on a blog site where you can search for posts by using searching with keywords (basically a normal searchbar).

I have imported Q from django.db.models

The view I created:

```<code>def search(request):
    queryset = Article.objects.all()
    query =  request.GET.get('q')
    if query:
        queryset = queryset.filter(
            Q(title__icontains=query) |
            Q(overview__icontains=query)
        ).distinct()

    context = {
        'queryset': queryset,
    }
    return render(request, 'search_results.html', context)
</code>```

The urlpattern:

```<code>path('search/', search, name='search-results'),
</code>```

The form itself:

```<code><form action="{% url 'search' %}" class="search-form">{% csrf_token %}
              <button type="submit" class="submit"><i class="icon-search"></i></button>
                <div class="form-group">
                  <span class="icon icon-search"></span>
                  <input type="text" class="form-control" name="q" placeholder="Type a keyword and hit enter">
                </div>
              </form>
</code>```

When I want to access the page to which I have put this form in, it says:
Reverse for 'search' not found. 'search' is not a valid view function or pattern name.

Below it also shows this:

```<code>1   <!DOCTYPE html>
2   <html lang="en">
3
4   {% include 'head.html' %}
5
6   <body>
7
8       {% include 'header.html' %}
9
10      {% block content %}
</code>```

I have tried adding/removing csrf_token and the submit button, but the result is always the same. Please help!

答: When you use {% url '' %} tag, it try to find url based on url names. You must use url names inside it . Please change {% url 'search' %} with {% url 'search-results' %}

Title: NoReverseMatch at ...... in django

Body:
I am working on a blog site where you can search for posts by using searching with keywords (basically a normal searchbar).

I have imported Q from django.db.models

The view I created:

def search(request):
    queryset = Article.objects.all()
    query =  request.GET.get('q')
    if query:
        queryset = queryset.filter(
            Q(title__icontains=query) |
            Q(overview__icontains=query)
        ).distinct()

    context = {
        'queryset': queryset,
    }
    return render(request, 'search_results.html', context)

The urlpattern:

path('search/', search, name='search-results'),

The form itself:

<form action="{% url 'search' %}" class="search-form">{% csrf_token %}
              <button type="submit" class="submit"></button>

                  <input type="text" class="form-control" name="q" placeholder="Type a keyword and hit enter">

              </form>

When I want to access the page to which I have put this form in, it says:
Reverse for 'search' not found. 'search' is not a valid view function or pattern name.

Below it also shows this:

1   <!DOCTYPE html>
2
3
4   {% include 'head.html' %}
5
6
7
8       {% include 'header.html' %}
9
10      {% block content %}

I have tried adding/removing csrf_token and the submit button, but the result is always the same. Please help!


问:
Axios interceptor always resolves promise
I am trying to intercept a axios post call in vue.

First I create the Axios in axios.js

```<code>import Vue from 'vue'
import axios from 'axios'

const axiosInstance = axios.create({
  baseURL: `http://localhost:8081/` // the url of our server
})

Vue.prototype.$axios = axiosInstance

export { axiosInstance }
</code>```

Here you see the axios call and the interceptors

```<code>import { axiosInstance } from '../boot/axios'

export default {
  validateUsers: async (username, password) => {
    // var usersPromise = axiosInstance.post('/users', {
    axiosInstance.post('/users', {
      params: {
        name: username,
        password: password
      }
    })
    axiosInstance.interceptors.response.use((response) => {
      console.log('RESPONSE', response)
      if (response.status === 401) {
        console.log('You are not authorized')
        return Promise.reject(response)
      } else if (response.status === 200) {
        console.log('response SUCC')
        return response
      }
    }, (error) => {
      console.log('ERROR RECEIVED BY AXIOS', error.response)
      if (error.response && error.response.status === 401) {
        return Promise.reject(error.response.status)
      }
      console.log('ERR RES', error.message)
      return Promise.reject(error.message)
    })
  }
}
</code>```

And in my Vue component I check for the promise like this

```<code>usersAPI.validateUsers(username, password)
    .then(ok => {
      console.log('ok', ok)
      this.valForm(this.$refs.loginForm)
    }, (error) => {
      if (error === 401) {
        this.getMessage('error', 'User or password wrong')
        return error
      }
      this.getMessage('error', 'Something went wrong. Error: ' + error)
      return error
    })
</code>```

In my nodeJS code I return a 401 if the user login is not correct and I can see that CORS first sends an OPTION call which returns 204 and then I send the 401 (which is correct).

What I expect

Axios interceptors handle the 401 error and reject the promise

What happens

The validateUsers() function returns 'ok' (promise is resolved) instead of rejected by axios.

Why is Axios not handling the 401 error?

答:
I think you should await your axios call and return the promise to make your code work.

```<code>    import Vue from 'vue'
    import axios from 'axios'

    const axiosInstance = axios.create({
      baseURL: `http://localhost:8081/` // the url of our server
    })

    axiosInstance.interceptors.response.use((response) => {
      console.log('RESPONSE', response)
      if (response.status === 401) {
        console.log('You are not authorized')
        return Promise.reject(response)
      } else if (response.status === 200) {
        console.log('response SUCC')
        return response
      }
    }, (error) => {
      console.log('ERROR RECEIVED BY AXIOS', error.response)
      if (error.response && error.response.status === 401) {
        return Promise.reject(error.response.status)
      }
      console.log('ERR RES', error.message)
      return Promise.reject(error.message)
    })

    Vue.prototype.$axios = axiosInstance

    export { axiosInstance }
</code>```

```<code>    import { axiosInstance } from '../boot/axios'

    export default {
      validateUsers: async (username, password) => {
        return axiosInstance.post('/users', {
          params: {
            name: username,
            password: password
          }
        })
      }
    }
</code>```

And in your Vue component the promise should be resolved or rejected correctly.

```<code>
    usersAPI.validateUsers(username, password)
        .then(ok => {
          console.log('ok', ok)
          this.valForm(this.$refs.loginForm)
        }, (error) => {
          if (error === 401) {
            this.getMessage('error', 'User or password wrong')
            return error
          }
          this.getMessage('error', 'Something went wrong. Error: ' + error)
          return error
        })
</code>```

Body:
I am trying to intercept a axios post call in vue.

First I create the Axios in axios.js

import Vue from 'vue'
import axios from 'axios'

const axiosInstance = axios.create({
  baseURL: `http://localhost:8081/` // the url of our server
})

Vue.prototype.$axios = axiosInstance

export { axiosInstance }

Here you see the axios call and the interceptors

import { axiosInstance } from '../boot/axios'

export default {
  validateUsers: async (username, password) => {
    // var usersPromise = axiosInstance.post('/users', {
    axiosInstance.post('/users', {
      params: {
        name: username,
        password: password
      }
    })
    axiosInstance.interceptors.response.use((response) => {
      console.log('RESPONSE', response)
      if (response.status === 401) {
        console.log('You are not authorized')
        return Promise.reject(response)
      } else if (response.status === 200) {
        console.log('response SUCC')
        return response
      }
    }, (error) => {
      console.log('ERROR RECEIVED BY AXIOS', error.response)
      if (error.response && error.response.status === 401) {
        return Promise.reject(error.response.status)
      }
      console.log('ERR RES', error.message)
      return Promise.reject(error.message)
    })
  }
}

And in my Vue component I check for the promise like this

usersAPI.validateUsers(username, password)
    .then(ok => {
      console.log('ok', ok)
      this.valForm(this.$refs.loginForm)
    }, (error) => {
      if (error === 401) {
        this.getMessage('error', 'User or password wrong')
        return error
      }
      this.getMessage('error', 'Something went wrong. Error: ' + error)
      return error
    })

In my nodeJS code I return a 401 if the user login is not correct and I can see that CORS first sends an OPTION call which returns 204 and then I send the 401 (which is correct).

What I expect

Axios interceptors handle the 401 error and reject the promise

What happens

The validateUsers() function returns 'ok' (promise is resolved) instead of rejected by axios.

Why is Axios not handling the 401 error?

Body:
I think you should await your axios call and return the promise to make your code work.

    import Vue from 'vue'
    import axios from 'axios'

    const axiosInstance = axios.create({
      baseURL: `http://localhost:8081/` // the url of our server
    })

    axiosInstance.interceptors.response.use((response) => {
      console.log('RESPONSE', response)
      if (response.status === 401) {
        console.log('You are not authorized')
        return Promise.reject(response)
      } else if (response.status === 200) {
        console.log('response SUCC')
        return response
      }
    }, (error) => {
      console.log('ERROR RECEIVED BY AXIOS', error.response)
      if (error.response && error.response.status === 401) {
        return Promise.reject(error.response.status)
      }
      console.log('ERR RES', error.message)
      return Promise.reject(error.message)
    })

    Vue.prototype.$axios = axiosInstance

    export { axiosInstance }

    import { axiosInstance } from '../boot/axios'

    export default {
      validateUsers: async (username, password) => {
        return axiosInstance.post('/users', {
          params: {
            name: username,
            password: password
          }
        })
      }
    }

And in your Vue component the promise should be resolved or rejected correctly.

    usersAPI.validateUsers(username, password)
        .then(ok => {
          console.log('ok', ok)
          this.valForm(this.$refs.loginForm)
        }, (error) => {
          if (error === 401) {
            this.getMessage('error', 'User or password wrong')
            return error
          }
          this.getMessage('error', 'Something went wrong. Error: ' + error)
          return error
        })


问:
Remove scientific notation formatting for Float values in kotlin android
I am trying to set the float value to an edit text. For this I am using a binding adapter like this below.

```<code>@BindingAdapter("android:text")
@JvmStatic
fun setAmount(editText: EditText, currency: Float?) {
    if (currency!= null && currency!=0.0f) {

       editText.setText(""+Math.round(currency))
    }else{
        editText.setText("")
    }
}
</code>```

Model Class

```<code>class OpportunityModel : BaseObservable(), Serializable {

var accountName = ""
var accountGuid: String? = null
var amount = 0.0
var potentialAmount:Float = 0.0f
get() = field
set(value) {field=value}
var contactPersonName = ""
var fieldOne = ""
var fieldTwo = ""
var fieldThree = ""
var fieldFour = ""
var fieldFive = ""
var opportunityName = ""
var opportunityGuid: String? = null
var opportunityRating = 0
var opportunityReasonGuid: String? = null
var opportunityIntStatus = 2
var opportunityDispStatus = ""
var opportunityNotAvailable = false
var genericFieldUI: GenericFieldDto? = null
@SerializedName("expDateOfClosure")
var dateForServer: String? = null
var expDate = ""
var contactPersonNameGuid: String? = null
var listOfAccountContact = ArrayList<AccountContactPersonModel>()
var listOfReasonMaster = ArrayList<ReasonMasterDto>()}
</code>```

This shows the value properly in the edit text but when this value is added to the model class via data binding, it gets converted to scientific notation and is showing values like 1E+07. How can I stop this conversion to scientific notation ?

答:
You can use String.format, like</p>

```<code>@BindingAdapter("android:text")
@JvmStatic
fun setAmount(editText: EditText, currency: Float?) {
    if (currency!= null && currency!=0.0f) {

       editText.setText(String.format("%.8f", currency))
    }else{
        editText.setText("")
    }
}
</code>```

Body:
I am trying to set the float value to an edit text. For this I am using a binding adapter like this below.

@BindingAdapter("android:text")
@JvmStatic
fun setAmount(editText: EditText, currency: Float?) {
    if (currency!= null && currency!=0.0f) {

       editText.setText(""+Math.round(currency))
    }else{
        editText.setText("")
    }
}

Model Class

class OpportunityModel : BaseObservable(), Serializable {

var accountName = ""
var accountGuid: String? = null
var amount = 0.0
var potentialAmount:Float = 0.0f
get() = field
set(value) {field=value}
var contactPersonName = ""
var fieldOne = ""
var fieldTwo = ""
var fieldThree = ""
var fieldFour = ""
var fieldFive = ""
var opportunityName = ""
var opportunityGuid: String? = null
var opportunityRating = 0
var opportunityReasonGuid: String? = null
var opportunityIntStatus = 2
var opportunityDispStatus = ""
var opportunityNotAvailable = false
var genericFieldUI: GenericFieldDto? = null
@SerializedName("expDateOfClosure")
var dateForServer: String? = null
var expDate = ""
var contactPersonNameGuid: String? = null
var listOfAccountContact = ArrayList<AccountContactPersonModel>()
var listOfReasonMaster = ArrayList<ReasonMasterDto>()}

This shows the value properly in the edit text but when this value is added to the model class via data binding, it gets converted to scientific notation and is showing values like 1E+07. How can I stop this conversion to scientific notation ?

Body:
You can use String.format, like

@BindingAdapter("android:text")
@JvmStatic
fun setAmount(editText: EditText, currency: Float?) {
    if (currency!= null && currency!=0.0f) {

       editText.setText(String.format("%.8f", currency))
    }else{
        editText.setText("")
    }
}


问:
Fonts problems with online version with Gatsby & Netlify
I'm working with gatsby, I deploy with netlify and I have a problem with google fonts. I'm using Raleway (H1) and Open Sans (body). I try to import fonts in css and it works locally and not with online version on netlify, I tried with "gatsby-plugin-google-font" works locally but not on netlify. I don't know where's the problem comes. You can check the website here : https://syter.fr
Any ideas ?
Thank you :)</p>

答:
Best guess without seeing your styling code — it looks like just a CSS specificity error, rather than anything particular to Gatsby or Netlify. You can verify in your devtools "Network" tab that the fonts are loaded correctly; and if you select one of the text elements rendering incorrectly, you see that the correct font (e.g., "Open Sans") is being masked by one or more other fonts. When disabled in devtools, you get the font you're going for:

Delving into your index.css file, I see that:

font-family is declared within a body block multiple times; the one with georgia,serif is taking priority over the one with Open Sans.

Similarly, you have rules with competing specificity for header elements; e.g.,

h1,h2 {
  font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;
  // ...
}
// [futher down]
.landing h1 {
  font-family: Raleway,sans-serif
}
```

Any idea where these CSS rules are coming from? I'd start there.

Regarding why you're seeing different results running locally vs. on Netlify  — keep in mind what you see from running gatsby develop is not equivalent to what will be deployed, since Gatsby cuts some corners in "develop" mode to enable hot-reloading and whatnot, and heavily optimizes in "build" mode for production performance... 99% of the time the results are the same, but occasionally I've run into edge cases where they diverge. Have you tried running gatsby build locally and then testing the static output from that step (either with gatsby serve or just cd'ing into the public directory and launching an HTTP server pointing to index.html)? I'd bet that you'd be able to reproduce locally what you're seeing in Netlify that way, which could help in debugging.

A part ça, c'est très bien conçu

Hope this helps!

Body:
Best guess without seeing your styling code — it looks like just a CSS specificity error, rather than anything particular to Gatsby or Netlify. You can verify in your devtools "Network" tab that the fonts are loaded correctly; and if you select one of the text elements rendering incorrectly, you see that the correct font (e.g., "Open Sans") is being masked by one or more other fonts. When disabled in devtools, you get the font you're going for:

Delving into your index.css file, I see that:

font-family is declared within a body block multiple times; the one with georgia,serif is taking priority over the one with Open Sans.

Similarly, you have rules with competing specificity for header elements; e.g.,

h1,h2 {
  font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;
  // ...
}
// [futher down]
.landing h1 {
  font-family: Raleway,sans-serif
}

Any idea where these CSS rules are coming from? I'd start there.

Regarding why you're seeing different results running locally vs. on Netlify  — keep in mind what you see from running gatsby develop is not equivalent to what will be deployed, since Gatsby cuts some corners in "develop" mode to enable hot-reloading and whatnot, and heavily optimizes in "build" mode for production performance... 99% of the time the results are the same, but occasionally I've run into edge cases where they diverge. Have you tried running gatsby build locally and then testing the static output from that step (either with gatsby serve or just cd'ing into the public directory and launching an HTTP server pointing to index.html)? I'd bet that you'd be able to reproduce locally what you're seeing in Netlify that way, which could help in debugging.

A part ça, c'est très bien conçu

Hope this helps!


问:
Single linked lists C++
Hey guys,
I'm studying for a midterm right now and am working on trying to create a simple program using single linked list.  All I want it to do is insert "1", "2", "3", "4" into the list and print it out.  Please take a look at the following code:

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

class node{
public:
    node(int data);
    friend class slist;
private:
    int data;
    node *next;
};

node::node(int data){
    data = data;
    next = NULL;
}

class slist{
public:
    slist(){
        head = NULL;
    }
    void insert(int item);
    void output();

private:
    node* head;
};

void slist::insert(int item){
    node* newnode = new node(item);
    if(head == NULL)
    {
        head = newnode;
    }
    else
    {
        newnode->next = head;
        head = newnode;
    }
}

void slist::output(){
    node* p = head;
    while (p->next != NULL){
        cout << p->data << " ";
        p = p->next;
    }
    cout << p->data << " ";
}

int main(){
    slist FINAL;

    FINAL.insert(1);
    FINAL.insert(2);
    FINAL.insert(3);
    FINAL.insert(4);

    FINAL.output();

    return 0;
}
</code>```

It compiles fine, but it prints out (I'm guessing) pointers instead of the actual numbers.  Can anyone tell me why?

Thanks so much!

答:
Well, I think both instances of data in

```<code>data = data;
</code>```

are local; so the data member of node never gets anything assigned to it.  What's getting printed are undefined values, not addresses.  That's in any case stylistically terrible; there are many conventions here but a good one is _data for the class member, and data for the function argument.  Make that simple change and see if that doesn't clear up your problem.

Title: Single linked lists C++

Body:
Hey guys,
I'm studying for a midterm right now and am working on trying to create a simple program using single linked list.  All I want it to do is insert "1", "2", "3", "4" into the list and print it out.  Please take a look at the following code:

#include <iostream>
#include <string>
using namespace std;

class node{
public:
    node(int data);
    friend class slist;
private:
    int data;
    node *next;
};

node::node(int data){
    data = data;
    next = NULL;
}

class slist{
public:
    slist(){
        head = NULL;
    }
    void insert(int item);
    void output();

private:
    node* head;
};

void slist::insert(int item){
    node* newnode = new node(item);
    if(head == NULL)
    {
        head = newnode;
    }
    else
    {
        newnode->next = head;
        head = newnode;
    }
}

void slist::output(){
    node* p = head;
    while (p->next != NULL){
        cout <
data << " ";
        p = p->next;
    }
    cout <
data << " ";
}

int main(){
    slist FINAL;

    FINAL.insert(1);
    FINAL.insert(2);
    FINAL.insert(3);
    FINAL.insert(4);

    FINAL.output();

    return 0;
}

It compiles fine, but it prints out (I'm guessing) pointers instead of the actual numbers.  Can anyone tell me why?

Thanks so much!

Body:
Well, I think both instances of data in

data = data;

are local; so the data member of node never gets anything assigned to it.  What's getting printed are undefined values, not addresses.  That's in any case stylistically terrible; there are many conventions here but a good one is _data for the class member, and data for the function argument.  Make that simple change and see if that doesn't clear up your problem.


问:
component interaction in Angular 8
I have two components in angular8. 1) add-files component 2) Discussion Component.

In the discussion component, I am having one button (see below)

```<code><app-add-files></app-add-files>

<div class="col-12 col-sm-6 col-lg-6">
            <input type="submit" value="Send" (click)="removeitems()" class="greenBtn float-right addCommentsBtn"
              [disabled]="commentForm.pristine || commentForm.invalid" onclick="closeCommnetPopupBox()">
          </div>
</code>```

I want to call a function removedoc() that is defined in the add-files component whenever I clicked on the button that is defined in the discussion component.

I tried with the below approach.

I import the add-files component in the discussion component and created an object of the same and then calling the function from the discussion component to the add-files component.

```<code>removeitems()
{
 this.comp.removedoc();
}
</code>```

comp is the object created of the add-files component.

I was doing some research on the internet and found that we can achieve this with @input/@output decorators with event emitters.

I am new to Angular. can anyone suggest me this approach to how to trigger the function form different components using event emitters with @input/@output in Angular?

Thanks in Advance!

答:
You can call the child component class using ViewChild decorator.

// Inside parent component.
@ViewChild('mychild') childComponent: Component2;
  onButtonClick() {

   // Exceute the function of child class.
   console.log( this.childComponent.method1());
  }

// On parent component html.
<component2 #mychild></component2>
```

You can play with it here.

Title: component interaction in Angular 8

Body:
I have two components in angular8. 1) add-files component 2) Discussion Component.

In the discussion component, I am having one button (see below)

<app-add-files></app-add-files>

            <input type="submit" value="Send" (click)="removeitems()" class="greenBtn float-right addCommentsBtn"
              [disabled]="commentForm.pristine || commentForm.invalid" onclick="closeCommnetPopupBox()">

I want to call a function removedoc() that is defined in the add-files component whenever I clicked on the button that is defined in the discussion component.

I tried with the below approach.

I import the add-files component in the discussion component and created an object of the same and then calling the function from the discussion component to the add-files component.

removeitems()
{
 this.comp.removedoc();
}

comp is the object created of the add-files component.

I was doing some research on the internet and found that we can achieve this with @input/@output decorators with event emitters.

I am new to Angular. can anyone suggest me this approach to how to trigger the function form different components using event emitters with @input/@output in Angular?

Thanks in Advance!

Body:
You can call the child component class using ViewChild decorator.

// Inside parent component.
@ViewChild('mychild') childComponent: Component2;
  onButtonClick() {

   // Exceute the function of child class.
   console.log( this.childComponent.method1());
  }

// On parent component html.
<component2 #mychild></component2>

You can play with it here.


问:
Can any one explain the meaning of orderby line of SQL in below code?
Could anyone please explain the meaning of orderby line in below code?</p>

```<code>SELECT winner, subject
FROM nobel
WHERE year=1984
ORDER BY subject IN ('Chemistry', 'Physics'),subject,winner
</code>```

答: You are sorting the data of subject and winner based on their alphabetic order and it is good to use subject IN ('Chemistry', 'Physics') in where clause not with order by</p>

Body:
Could anyone please explain the meaning of orderby line in below code?

SELECT winner, subject
FROM nobel
WHERE year=1984
ORDER BY subject IN ('Chemistry', 'Physics'),subject,winner


问:
How to send an email, using google gmail api in php with cURL?
I have a problem sending mail using the Google Api in Php and cURL,

I tried this one:

```<code>// ENVOIE EMAIL

$message="To: test@example.com\r\nFrom: test@example.com\r\nSubject: GMail test.\r\n My message";
$email=base64_encode($message);

$url_email = 'https://www.googleapis.com/upload/gmail/v1/users/me/messages/send';

$curlPost = array(
    'raw' => $email,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_email);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $AccessToken, 'Accept: application/json','Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));
$data = curl_exec($ch);
// $data = json_decode(curl_exec($ch), true);;
curl_close($ch);
echo '<br/><h2>Send email</h2>';
print_r($data);
</code>```

But I get an error message like this :

{ "error": { "errors": [ { "domain": "global", "reason": "badContent", "message": "Media type 'application/json' is not supported. Valid media types: [message/rfc822]" } ], "code": 400, "message": "Media type 'application/json' is not supported. Valid media types: [message/rfc822]" } }

And when I tried with :

```<code>'Content-Type: message/rfc822';
</code>```

I have a new error message :

{ "error": { "errors": [ { "domain": "global", "reason": "invalidArgument", "message": "Recipient address required" } ], "code": 400, "message": "Recipient address required" } }

I do not want to use the library offered by google.

答:
Looks like you are sending JSON encoded data while you should respect message/rfc822 format.

You should probably not base64-encode + json-encode your message:

```<code><?php
$message = "To: test@example.com\r\nFrom: test@example.com\r\nSubject: GMail test.\r\n My message";

$ch = curl_init('https://www.googleapis.com/upload/gmail/v1/users/me/messages/send');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer $AccessToken", 'Accept: application/json', 'Content-Type: message/rfc822'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
$data = curl_exec($ch);
</code>```

Body:
I have a problem sending mail using the Google Api in Php and cURL,

I tried this one:

// ENVOIE EMAIL

$message="To: test@example.com\r\nFrom: test@example.com\r\nSubject: GMail test.\r\n My message";
$email=base64_encode($message);

$url_email = 'https://www.googleapis.com/upload/gmail/v1/users/me/messages/send';

$curlPost = array(
    'raw' => $email,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_email);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $AccessToken, 'Accept: application/json','Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));
$data = curl_exec($ch);
// $data = json_decode(curl_exec($ch), true);;
curl_close($ch);
echo '

Send email
';
print_r($data);

But I get an error message like this :

{ "error": { "errors": [ { "domain": "global", "reason": "badContent", "message": "Media type 'application/json' is not supported. Valid media types: [message/rfc822]" } ], "code": 400, "message": "Media type 'application/json' is not supported. Valid media types: [message/rfc822]" } }

And when I tried with :

'Content-Type: message/rfc822';

I have a new error message :

{ "error": { "errors": [ { "domain": "global", "reason": "invalidArgument", "message": "Recipient address required" } ], "code": 400, "message": "Recipient address required" } }

I do not want to use the library offered by google.

Body:
Looks like you are sending JSON encoded data while you should respect message/rfc822 format.

You should probably not base64-encode + json-encode your message:

<?php
$message = "To: test@example.com\r\nFrom: test@example.com\r\nSubject: GMail test.\r\n My message";

$ch = curl_init('https://www.googleapis.com/upload/gmail/v1/users/me/messages/send');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer $AccessToken", 'Accept: application/json', 'Content-Type: message/rfc822'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
$data = curl_exec($ch);


问:
(Collapsing)Toolbar title resets its position after Snackbar appearance
I have a layout with CollapsingToolbarLayout and CoordinatorLayout as root element.
Whenever a Snackbar is shown in the activity the title of the toolbar resets its position to the default expanded title position of the CollapsingToolbar even if the toolbar is not (fully) expanded.

The second picture shows that the title is fixed no matter if the toolbar expands or not.

The result is the same when I call snackbar.show() in activity or fragment.

My layout structure looks like this:

```<code><CoordinatorLayout>
<AppBarLayout>
    <CollapsingToolbarLayout>
        <Toolbar />
        <TabLayout />
    </CollapsingToolbarLayout>
</AppBarLayout>
<ViewPager />
<FloatingActionButton />
</code>```

I use the latest dependencies for appcompat and design library (v24.2.1).
I hope that's enough information and somebody has an idea how to solve the issue :P

EDIT:
Also in the template when you start a new project and choose Scrolling activity the same problem appears when snackbar.show()is called. So it's a library issue.

答:
I know a workaround to solve this issue.

Put your CoordinatorLayout inside a FrameLayout. While showing snackbar, instead of passing coordinatorlayout's Id pass FrameLayout's Id.

```<code><FrameLayout     xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rel_full"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout>
</android.support.design.widget.CoordinatorLayout>
</FrameLayout>

Snackbar.make(findViewById(R.id.rel_full), "SNACKBAR",Toast.LENGTH_SHORT).show();
</code>```

Body:
I have a layout with CollapsingToolbarLayout and CoordinatorLayout as root element.
Whenever a Snackbar is shown in the activity the title of the toolbar resets its position to the default expanded title position of the CollapsingToolbar even if the toolbar is not (fully) expanded.

The second picture shows that the title is fixed no matter if the toolbar expands or not.

The result is the same when I call snackbar.show() in activity or fragment.

My layout structure looks like this:

<CoordinatorLayout>
<AppBarLayout>
    <CollapsingToolbarLayout>
        <Toolbar />
        <TabLayout />
    </CollapsingToolbarLayout>
</AppBarLayout>
<ViewPager />
<FloatingActionButton />

I use the latest dependencies for appcompat and design library (v24.2.1).
I hope that's enough information and somebody has an idea how to solve the issue :P

EDIT:
Also in the template when you start a new project and choose Scrolling activity the same problem appears when snackbar.show()is called. So it's a library issue.

Body:
I know a workaround to solve this issue.

Put your CoordinatorLayout inside a FrameLayout. While showing snackbar, instead of passing coordinatorlayout's Id pass FrameLayout's Id.

<FrameLayout     xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rel_full"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout>
</android.support.design.widget.CoordinatorLayout>
</FrameLayout>

Snackbar.make(findViewById(R.id.rel_full), "SNACKBAR",Toast.LENGTH_SHORT).show();


问:
eclipse + ddms - don't copy timestamp etc from ddms logs?
I'm using the eclipse plugin for android development. When I copy/paste log contents from ddms, I always get the timestamp etc in the copy/paste:

```<code>05-16 21:43:09.082: INFO/ActivityManager(110): [message text]
05-16 21:43:09.152: INFO/ActivityManager(110): [message text]
...
</code>```

Is there any way to clip the timestamp + debug level + pid from the paste as seen above, and only get the [message text] copied? It just gets annoying sometimes when sending log details to others as it's a bit noisy for them to look at,

Thanks

答:
Filter your logs with this one-liner:</p>

```<code>perl -pe 's/^(.*?: ){2}//'
</code>```

Body:
I'm using the eclipse plugin for android development. When I copy/paste log contents from ddms, I always get the timestamp etc in the copy/paste:

05-16 21:43:09.082: INFO/ActivityManager(110): [message text]
05-16 21:43:09.152: INFO/ActivityManager(110): [message text]
...

Is there any way to clip the timestamp + debug level + pid from the paste as seen above, and only get the [message text] copied? It just gets annoying sometimes when sending log details to others as it's a bit noisy for them to look at,

Thanks

Body:
Filter your logs with this one-liner:

perl -pe 's/^(.*?: ){2}//'


问:
axios use of data server argument
I am trying to axios to contact a remote server
If I used the following format, my server never seems to parse the data arguments

```<code>axios({
    url: API_URL + 'oauth/token',
    method:'post',
    data: {
        grant_type: 'password',
        username: user.username,
        password: user.password,
        scope: 'webclient'
          },
    auth: {
        username: 'foo',
        password: 'foobar'
    },
    responseType: 'json'
  })
</code>```

But if I use the vulgar format

```<code>axios({
    url: API_URL + 'oauth/token',
    method: 'post',
       data:'grant_type=password&username='+user.username+'&password='+user.password+'&scope=webclient',
    auth: {
        username: 'foo',
        password: 'foobar'
    },
    responseType: 'json'
  })
</code>```

Every works as expected, so can anybody tell me what the difference is between the two different forms of the data argument?

答:
If you pass an object to data then Axios will encode it as JSON, not URL Form Encoded data (which is what your manual encoding uses and thus, presumably, what your server expects).

The documentation has several examples of form encoding data programmatically:

```<code>const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
</code>```

Make sure you also set 'application/x-www-form-urlencoded' as the Content-Type request header.

Title: axios use of data server argument

Body:
I am trying to axios to contact a remote server
If I used the following format, my server never seems to parse the data arguments

axios({
    url: API_URL + 'oauth/token',
    method:'post',
    data: {
        grant_type: 'password',
        username: user.username,
        password: user.password,
        scope: 'webclient'
          },
    auth: {
        username: 'foo',
        password: 'foobar'
    },
    responseType: 'json'
  })

But if I use the vulgar format

axios({
    url: API_URL + 'oauth/token',
    method: 'post',
       data:'grant_type=password&username='+user.username+'&password='+user.password+'&scope=webclient',
    auth: {
        username: 'foo',
        password: 'foobar'
    },
    responseType: 'json'
  })

Every works as expected, so can anybody tell me what the difference is between the two different forms of the data argument?

Body:
If you pass an object to data then Axios will encode it as JSON, not URL Form Encoded data (which is what your manual encoding uses and thus, presumably, what your server expects).

The documentation has several examples of form encoding data programmatically:

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

Make sure you also set 'application/x-www-form-urlencoded' as the Content-Type request header.


问:
Odoo: How to use context to pass value from model to one2many field
I want to pass the value of a many2one field to a one2many field in order to filter results of the latter, i am trying to use context but i don't know if i'm using it correctly or not

The idea is that i want to filter products (part of the one2many field) based on the chosen branch (the many2one field)

my code is as below

```<code>class CustomTransRequest(models.Model):
    _name = 'custom.trans.request'

    branch_from_id = fields.Many2one('custom.branch', string="From", required=True)
    branch_to_id = fields.Many2one('custom.branch', string="To", required=True)
    product_ids = fields.One2many(comodel_name="custom.trans.line", inverse_name="request_id", string="Products", required=False, )

class CustomTransLine(models.Model):
    _name = 'custom.trans.line'

    request_id = fields.Many2one("custom.trans.request", string="Request ID", required=True, )
    product_id = fields.Many2one("custom.product", string="Product", required=True)
    qty = fields.Integer(string="Qty", required=True)

class CustomProduct(models.Model):
    _name = 'custom.product'

    product_name = fields.Char(string="Name", required=False, )
    branch_line = fields.One2many('custom.branch.line', 'product_id', string='Branch', )

class CustomBranchLine(models.Model):
    _name = 'custom.branch.line'

    branch_id = fields.Many2one('custom.branch', string='Branch', ondelete='cascade')
    product_id = fields.Many2one('custom.product', string='Product', required=True, )
    qty = fields.Integer(string="QTY", required=True, )
</code>```

```<code><record id="form_custom_trans_request" model="ir.ui.view">
        <field name="name">custom.trans.request.form</field>
        <field name="model">custom.trans.request</field>
        <field name="arch" type="xml">
            <form string="Transfer Request">
                <sheet>
                    <group>
                        <field name="branch_from_id"/>
                        <field name="branch_to_id"/>
                    </group>
                    <notebook>
                        <page string="Products" name="order_lines">
                            <field name="product_ids" context="{'default_branch_id':branch_from_id}" mode="tree">
                                <tree editable="bottom">
                                    <control>
                                        <create string="Open list view"/>
                                    </control>
                                    <field name="product_id" domain="[('branch_line.branch_id','=',default_branch_id)]" />
                                    <field name="qty"/>
                                </tree>
                            </field>
                        </page>
                    </notebook>
                </sheet>
            </form>
        </field>
    </record>
</code>```

答:
I found the answer on this website
http://learnopenerp.blogspot.com/2018/01/get-parent-form-value-in-one2many-form.html</p>

Body:
I want to pass the value of a many2one field to a one2many field in order to filter results of the latter, i am trying to use context but i don't know if i'm using it correctly or not

The idea is that i want to filter products (part of the one2many field) based on the chosen branch (the many2one field)

my code is as below

class CustomTransRequest(models.Model):
    _name = 'custom.trans.request'

    branch_from_id = fields.Many2one('custom.branch', string="From", required=True)
    branch_to_id = fields.Many2one('custom.branch', string="To", required=True)
    product_ids = fields.One2many(comodel_name="custom.trans.line", inverse_name="request_id", string="Products", required=False, )

class CustomTransLine(models.Model):
    _name = 'custom.trans.line'

    request_id = fields.Many2one("custom.trans.request", string="Request ID", required=True, )
    product_id = fields.Many2one("custom.product", string="Product", required=True)
    qty = fields.Integer(string="Qty", required=True)

class CustomProduct(models.Model):
    _name = 'custom.product'

    product_name = fields.Char(string="Name", required=False, )
    branch_line = fields.One2many('custom.branch.line', 'product_id', string='Branch', )

class CustomBranchLine(models.Model):
    _name = 'custom.branch.line'

    branch_id = fields.Many2one('custom.branch', string='Branch', ondelete='cascade')
    product_id = fields.Many2one('custom.product', string='Product', required=True, )
    qty = fields.Integer(string="QTY", required=True, )

<record id="form_custom_trans_request" model="ir.ui.view">
        <field name="name">custom.trans.request.form</field>
        <field name="model">custom.trans.request</field>
        <field name="arch" type="xml">
            <form string="Transfer Request">
                <sheet>
                    <group>
                        <field name="branch_from_id"/>
                        <field name="branch_to_id"/>
                    </group>
                    <notebook>
                        <page string="Products" name="order_lines">
                            <field name="product_ids" context="{'default_branch_id':branch_from_id}" mode="tree">
                                <tree editable="bottom">
                                    <control>
                                        <create string="Open list view"/>
                                    </control>
                                    <field name="product_id" domain="[('branch_line.branch_id','=',default_branch_id)]" />
                                    <field name="qty"/>
                                </tree>
                            </field>
                        </page>
                    </notebook>
                </sheet>
            </form>
        </field>
    </record>


问:
Using window function in redshift to aggregate conditionally
I have a table with following data:

Link to test data: http://sqlfiddle.com/#!15/dce01/1/0

I want to aggregate the items column (using listagg) for each group in gid in sequence as specified by seq column based on the condition that aggregation ends when pid becomes 0 again for a group.

i.e.
for group g1, there would be 2 aggregations; 1 for seq 1-3 and another for sequence 4-6; since for group g1, the pid becomes 0 for seq 4.

I expect the result for the given example to be as follows (Please note that seq in result is the min value of seq for the group where the pid becomes 0):

答:
I understand your question as a gaps and island problem, where you want to group together adjacent rows having the same gid untiil a pid having value 0 is met.

Here is one way to solve it using a window sum to define the groups: basically, a new island starts everytime a pid of 0 is met. The rest is just aggregation:

```<code>select
    gid,
    min(seq) seq,
    listagg(items, ',') within group(order by seq) items
from (
    select
        t.*,
        sum(case when pid = 0 then 1 else 0 end) over(partition by gid order by seq) grp
    from mytable t
) t
group by gid, grp
order by gid, grp
</code>```

Body:
I understand your question as a gaps and island problem, where you want to group together adjacent rows having the same gid untiil a pid having value 0 is met.

Here is one way to solve it using a window sum to define the groups: basically, a new island starts everytime a pid of 0 is met. The rest is just aggregation:

select
    gid,
    min(seq) seq,
    listagg(items, ',') within group(order by seq) items
from (
    select
        t.*,
        sum(case when pid = 0 then 1 else 0 end) over(partition by gid order by seq) grp
    from mytable t
) t
group by gid, grp
order by gid, grp


Title: Split a data frame by column using a list of vectors

Body:
I want to split this data frame df by column using a list of vectors ind as the column indices.

> df
    1  2  3  4  5  6  7  8  9  10
1   1 11 21 31 41 51 61 71 81  91
2   2 12 22 32 42 52 62 72 82  92
3   3 13 23 33 43 53 63 73 83  93
4   4 14 24 34 44 54 64 74 84  94
5   5 15 25 35 45 55 65 75 85  95
6   6 16 26 36 46 56 66 76 86  96
7   7 17 27 37 47 57 67 77 87  97
8   8 18 28 38 48 58 68 78 88  98
9   9 19 29 39 49 59 69 79 89  99
10 10 20 30 40 50 60 70 80 90 100

The combined length of the vectors are equal to the number of columns in the data frame.

> ind
[[1]]
[1] 1 4 9

[[2]]
[1] 2 5 10 7 3

[[3]]
[1]  8 6

The desired result should look like this:

$`1`
    1  4  9
1   1 31 81
2   2 32 82
3   3 33 83
4   4 34 84
5   5 35 85
6   6 36 86
7   7 37 87
8   8 38 88
9   9 39 89
10 10 40 90

$`2`
    2  5  10  7  3
1  11 41  91 61 21
2  12 42  92 62 22
3  13 43  93 63 23
4  14 44  94 64 24
5  15 45  95 65 25
6  16 46  96 66 26
7  17 47  97 67 27
8  18 48  98 68 28
9  19 49  99 69 29
10 20 50 100 70 30

$`3`
    8  6
1  71 51
2  72 52
3  73 53
4  74 54
5  75 55
6  76 56
7  77 57
8  78 58
9  79 59
10 80 60

Effectively the code generates sub matrices as data frames from the data frame df based on the vectors in the list ind

I have tried using split.defult without achieving the desired result.

split.default(V, rep(seq_along(ind), lengths(ind)))

Body:
You can try the following base R solution using subset + Map

r <- Map(function(k) subset(df,select = k),ind)

such that

> r
[[1]]
   X1 X4 X9
1   1 31 81
2   2 32 82
3   3 33 83
4   4 34 84
5   5 35 85
6   6 36 86
7   7 37 87
8   8 38 88
9   9 39 89
10 10 40 90

[[2]]
   X2 X5 X10 X7 X3
1  11 41  91 61 21
2  12 42  92 62 22
3  13 43  93 63 23
4  14 44  94 64 24
5  15 45  95 65 25
6  16 46  96 66 26
7  17 47  97 67 27
8  18 48  98 68 28
9  19 49  99 69 29
10 20 50 100 70 30

[[3]]
   X8 X6
1  71 51
2  72 52
3  73 53
4  74 54
5  75 55
6  76 56
7  77 57
8  78 58
9  79 59
10 80 60


问:
Add external data in D3 Pie by dbuezas’s
I'm new to D3 and i'm trying to use a d3 chart for some visualizations, but i can't seem to figure out how to add data to this specific graphic:
http://bl.ocks.org/dbuezas/9306799

I tried to use:

```<code> d3.csv("data.csv", type, function(error, data) {
    if (error) throw error; });
</code>```

but i can't seem to find how to use it with the current setup.

I would appreciate if someone could point me in the right direction.

code:

```<code><script>

var svg = d3.select("body")
    .append("svg")
    .append("g")

svg.append("g")
    .attr("class", "slices");
svg.append("g")
    .attr("class", "labels");
svg.append("g")
    .attr("class", "lines");

var width = 960,
    height = 450,
    radius = Math.min(width, height) / 2;

var pie = d3.layout.pie()
    .sort(null)
    .value(function(d) {
        return d.value;
    });

var arc = d3.svg.arc()
    .outerRadius(radius * 0.8)
    .innerRadius(radius * 0.4);

var outerArc = d3.svg.arc()
    .innerRadius(radius * 0.9)
    .outerRadius(radius * 0.9);

svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var key = function(d){ return d.data.label; };

var color = d3.scale.ordinal()
    .domain(["Lorem ipsum", "dolor sit", "amet", "consectetur", "adipisicing", "elit", "sed", "do", "eiusmod", "tempor", "incididunt"])
    .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

function randomData (){
    var labels = color.domain();
    return labels.map(function(label){
        return { label: label, value: Math.random() }
    });
}

change(randomData());

d3.select(".randomize")
    .on("click", function(){
        change(randomData());
    });

function change(data) {

    /* ------- PIE SLICES -------*/
    var slice = svg.select(".slices").selectAll("path.slice")
        .data(pie(data), key);

    slice.enter()
        .insert("path")
        .style("fill", function(d) { return color(d.data.label); })
        .attr("class", "slice");

    slice
        .transition().duration(1000)
        .attrTween("d", function(d) {
            this._current = this._current || d;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                return arc(interpolate(t));
            };
        })

    slice.exit()
        .remove();

    /* ------- TEXT LABELS -------*/

    var text = svg.select(".labels").selectAll("text")
        .data(pie(data), key);

    text.enter()
        .append("text")
        .attr("dy", ".35em")
        .text(function(d) {
            return d.data.label;
        });

    function midAngle(d){
        return d.startAngle + (d.endAngle - d.startAngle)/2;
    }

    text.transition().duration(1000)
        .attrTween("transform", function(d) {
            this._current = this._current || d;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                var d2 = interpolate(t);
                var pos = outerArc.centroid(d2);
                pos[0] = radius * (midAngle(d2) < Math.PI ? 1 : -1);
                return "translate("+ pos +")";
            };
        })
        .styleTween("text-anchor", function(d){
            this._current = this._current || d;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                var d2 = interpolate(t);
                return midAngle(d2) < Math.PI ? "start":"end";
            };
        });

    text.exit()
        .remove();

    /* ------- SLICE TO TEXT POLYLINES -------*/

    var polyline = svg.select(".lines").selectAll("polyline")
        .data(pie(data), key);

    polyline.enter()
        .append("polyline");

    polyline.transition().duration(1000)
        .attrTween("points", function(d){
            this._current = this._current || d;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                var d2 = interpolate(t);
                var pos = outerArc.centroid(d2);
                pos[0] = radius * 0.95 * (midAngle(d2) < Math.PI ? 1 : -1);
                return [arc.centroid(d2), outerArc.centroid(d2), pos];
            };
        });

    polyline.exit()
        .remove();
    };

    </script>
</code>```

答:
I also had the same problem, but in my case, I am coming from a ruby application. Data is loaded off the database and I can't really have a json file to be loaded in JavaScript.

I slightly modified @dbuezas examples only to have a reusable function. I am setting up the svg object and calling change inside.

I'm in a ERB views, and I have my data in ruby instance variables.

```<code><script>
        var colors = d3.scale.ordinal()
            .domain(<%= @pie_categories.inspect.html_safe %>)
            .range(<%= @pie_colors.inspect.html_safe %>);
        var chart_data = <%= @pie_chart_data.to_json.html_safe %>;
        var width = 450, height = 350;
        create_pie_chart_at('#categories_pie_chart',
           colors, chart_data, width, height);
</script>
</code>```

Body:
I'm new to D3 and i'm trying to use a d3 chart for some visualizations, but i can't seem to figure out how to add data to this specific graphic:
http://bl.ocks.org/dbuezas/9306799

I tried to use:

 d3.csv("data.csv", type, function(error, data) {
    if (error) throw error; });

but i can't seem to find how to use it with the current setup.

I would appreciate if someone could point me in the right direction.

code:

Body:
I also had the same problem, but in my case, I am coming from a ruby application. Data is loaded off the database and I can't really have a json file to be loaded in JavaScript.

I slightly modified @dbuezas examples only to have a reusable function. I am setting up the svg object and calling change inside.

I'm in a ERB views, and I have my data in ruby instance variables.

<script>
        var colors = d3.scale.ordinal()
            .domain(<%= @pie_categories.inspect.html_safe %>)
            .range(<%= @pie_colors.inspect.html_safe %>);
        var chart_data = <%= @pie_chart_data.to_json.html_safe %>;
        var width = 450, height = 350;
        create_pie_chart_at('#categories_pie_chart',
           colors, chart_data, width, height);
</script>


问:
Does pip take into account the actual Python version when installing compatible package versions?
I have a library that has to support several Python versions starting from 2.6. E.g., one of my requirements is requests. I know that the last version supporting Python 2.6 is 2.19.1 (the latest version 2.20.0 supports any Python >= 2.7).

So my question is whether pip understands that the line requests~=2.19 in requirements should install 2.19.1 for Python 2.6 and 2.20.0 for any higher version of Python?

Update. The question is not about the syntax, I'm curious whether pip is smart enough and in a Python 2.6 environment will be able not to go beyond 0.19.1.

答:
As far as I know, yes that is possible using version specifiers in your requirements file.

Example:

```<code>requests>=2.19.1,<=2.20.0
</code>```

Using the ~= operator would result in a package in the 2.19 package range for Python 2.7, because it means: install a package greater than or equal to version 2.19.1, but still in the 2.19 version.

Body:
As far as I know, yes that is possible using version specifiers in your requirements file.

Example:

requests>=2.19.1,<=2.20.0

Using the ~= operator would result in a package in the 2.19 package range for Python 2.7, because it means: install a package greater than or equal to version 2.19.1, but still in the 2.19 version.


问:
How to extract sub-directories from the URL using 'REGEXP_EXTRACT' in Data Studio
I'm trying to extract the product name from the URL between the 2 slashes using REGEXP_EXTRACT. For example, I want to extraxt ace-5 from the URLs below:

www.abc.com/products/phones/ace-5/

  www.abc.com/products/phones/ace-5/?cid=dm66363&bid

  www.abc.com/products/phones/ace-5/?fbclid=iwar30dpnmmpwppnla7

  www.abc.com/products/phones/ace-5/?et_cid=em_367029&et_rid=130

I have a RegEx to extract the Domain Name but it is not something I'm actually looking for. Below is the RegEx:

```<code>REGEXP_EXTRACT(page,'^[^.]+.([^.]+)')
</code>```

It gives the following result: abc

答:
The REGEXP_EXTRACT Calculated Field below does the trick, extracting all characters after the 3rd / till the next instance of /:

REGEXP_EXTRACT(Page, "^(?:[^/]+/){3}([^/]+)")
```

Google Data Studio Report and a GIF to elaborate

Body:
I'm trying to extract the product name from the URL between the 2 slashes using REGEXP_EXTRACT. For example, I want to extraxt ace-5 from the URLs below:

www.abc.com/products/phones/ace-5/

  www.abc.com/products/phones/ace-5/?cid=dm66363&bid

  www.abc.com/products/phones/ace-5/?fbclid=iwar30dpnmmpwppnla7

  www.abc.com/products/phones/ace-5/?et_cid=em_367029&et_rid=130

I have a RegEx to extract the Domain Name but it is not something I'm actually looking for. Below is the RegEx:

REGEXP_EXTRACT(page,'^[^.]+.([^.]+)')

It gives the following result: abc

Body:
The REGEXP_EXTRACT Calculated Field below does the trick, extracting all characters after the 3rd / till the next instance of /:

REGEXP_EXTRACT(Page, "^(?:[^/]+/){3}([^/]+)")

Google Data Studio Report and a GIF to elaborate


问:
How to disable user in Asp.NET Identity MVC5
I try to disable any existing user using:

```<code>IdentityResult confirmUserResult = await UserManager.SetConfirmedAsync(userId, confirm);
</code>```

This identity result returns Succeed = true. However, after I 'disable' the user, I try to login with the related user and I can do it.

So, my question is how can I disable a user's account?

Note: I use ASP.Net MVC5 Identity.

答: Check this answer, which explains how to override the PasswordSignInAsync function: https://stackoverflow.com/a/35293561/2908623

Body:
I try to disable any existing user using:

IdentityResult confirmUserResult = await UserManager.SetConfirmedAsync(userId, confirm);

This identity result returns Succeed = true. However, after I 'disable' the user, I try to login with the related user and I can do it.

So, my question is how can I disable a user's account?

Note: I use ASP.Net MVC5 Identity.


问:
Recording state changes in boost::statechart
For Unit Testing, I'm trying to record all the state transactions after I kick off a state machine event.

E.g., if I post_event A to the fifo_scheduler of an async_state_machine, the state machine will go through states B, C, then back to D.
Without being able to record all the event states, I can only check that it went to State D after it was done when doing a unit test :-(

The only thing I can think of is to modify all the react methods or constructors of all the states I create (derived off simple_state) so they do the recording.  This seems a bit hackish when I really want to hook into the async_state_machine just before it calls a state's react() method...

答:
This seems a bit hackish when I really want to hook into the async_state_machine just before it calls a state's react() method...

Why don't you? Create a new class that extends async_state_machine and add your desired hooks into it. If access is a problem (It probably will be), do the ever spectacular #define private public (or protected hack before including statechart.

I've done something similar to add local variables to the history of a state and add a new kind of state-ctor so I have for-real full history.


问:
JSON field for model Django 3.0a
I'm using Django 3.0a with Python 3.7

I had searched a lot for a JSON field that works with the Data base sqlite and other (I know that Django > 2.2 support JSONfield for postgres)

Now I had tried this libraries:

https://github.com/adamchainz/django-jsonfield

https://github.com/dmkoch/django-jsonfield

https://github.com/rpkilby/jsonfield2/

All of them throw very similar error:

```<code>from django.utils import six
ImportError: cannot import name 'six' from 'django.utils' (C:\Program Files (x86)\Python37-32\lib\site-packages\django-3.0a1-py3.7.e
gg\django\utils\__init__.py)
</code>```

I searched the issue and i found that the "six" library which is missing suppose to deal with differences between Python 2 and 3.

How can I fix it or do you know another way around to use JSON fields in the Django model?

Thanks a lot

答:
```<code>import jsonfield
from django.db import models

class Modelname(models.Model):
    data=jsonfield.JSONField()
</code>```

Data column saves the json data in Sqlite database.

Title: JSON field for model Django 3.0a

Body:
I'm using Django 3.0a with Python 3.7

I had searched a lot for a JSON field that works with the Data base sqlite and other (I know that Django > 2.2 support JSONfield for postgres)

Now I had tried this libraries:

https://github.com/adamchainz/django-jsonfield

https://github.com/dmkoch/django-jsonfield

https://github.com/rpkilby/jsonfield2/

All of them throw very similar error:

from django.utils import six
ImportError: cannot import name 'six' from 'django.utils' (C:\Program Files (x86)\Python37-32\lib\site-packages\django-3.0a1-py3.7.e
gg\django\utils\__init__.py)

I searched the issue and i found that the "six" library which is missing suppose to deal with differences between Python 2 and 3.

How can I fix it or do you know another way around to use JSON fields in the Django model?

Thanks a lot

Body:
import jsonfield
from django.db import models

class Modelname(models.Model):
    data=jsonfield.JSONField()

Data column saves the json data in Sqlite database.