问:
How to get final verdict out of all returns in Python in a loop?
Sorry, for a stupid question.
Let's say I want to compare elements of two lists using for loop. Now I wrote:-

```<code>for i in range(10):
     if a[i] == b[i]:
         print('True')
     else:
         print('False')
</code>```

where a and b are two list.

Now I will get 10 outputs which will be either true or false. What I want is, if all of them are true then only True is printed and if any of them is false then false is printed (True or False printed only once).

This is just an example, I want to use this method for some other question and that too using for loop.

Please help.

答:
The equivalent of what you want above would be written as:

```<code>if all([a[i] == b[i] for i in range(10)]):
    print("True")
else:
    print("False")
</code>```

This would be comparable to:

```<code>flag = True
for i in range(10):
    flag = flag and a[i] == b[i]  # or flag &= a[i] == b[i] # since bool's are essentially binary
if flag:
    print('True')
else:
    print('False')
</code>```

A function with proper bounds checking would be:

```<code>def compare_lists(a, b, N):
    if len(a) >= N <= len(b):
        return all([a[i] == b[i] for i in range(N)])
    else:
        print('Oops!')
</code>```

The built-in all() function looks at the list of arguments passed and returns True only of all of them are True. Consider it a big 'AND' function.

You can daisy-chain comparison operations, so 0 < N < 10 works instead of having to write 0 < N and N < 10.

The [ blah for blah in blah] is a very powerful concept called list comprehension, which allows you to write compact code.  for example, if you have a list nums = [1, 2, 3], you could make a list of squares with [i*i for i in nums], which would give you [1, 4, 9].

Body:
Sorry, for a stupid question.
Let's say I want to compare elements of two lists using for loop. Now I wrote:-

for i in range(10):
     if a[i] == b[i]:
         print('True')
     else:
         print('False')

where a and b are two list.

Now I will get 10 outputs which will be either true or false. What I want is, if all of them are true then only True is printed and if any of them is false then false is printed (True or False printed only once).

This is just an example, I want to use this method for some other question and that too using for loop.

Please help.

Body:
The equivalent of what you want above would be written as:

if all([a[i] == b[i] for i in range(10)]):
    print("True")
else:
    print("False")

This would be comparable to:

flag = True
for i in range(10):
    flag = flag and a[i] == b[i]  # or flag &= a[i] == b[i] # since bool's are essentially binary
if flag:
    print('True')
else:
    print('False')

A function with proper bounds checking would be:

def compare_lists(a, b, N):
    if len(a) >= N <= len(b):
        return all([a[i] == b[i] for i in range(N)])
    else:
        print('Oops!')

The built-in all() function looks at the list of arguments passed and returns True only of all of them are True. Consider it a big 'AND' function.

You can daisy-chain comparison operations, so 0 < N < 10 works instead of having to write 0 < N and N < 10.

The [ blah for blah in blah] is a very powerful concept called list comprehension, which allows you to write compact code.  for example, if you have a list nums = [1, 2, 3], you could make a list of squares with [i*i for i in nums], which would give you [1, 4, 9].


来源: stackexchange

问:
Failed to link resource after updating gradle and Android studio version
Before I updated to android studio 3 and gradle 3.0.1 I could build my project without a problem, but ever since I updated I keep getting this errors:

```<code>Error:failed linking references.
    Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:Execution failed for task ':app:processDebugResources'.
            > Failed to execute aapt
</code>```

I tried to disable AAPT2 but then I get an error ProcessException for aapt

```<code>Error:java.util.concurrent.ExecutionException:
com.android.ide.common.process.ProcessException: Error while executing
process /build-tools/26.0.2/aapt with arguments {package -f --no-crunch
-I /android-25/android.jar -M
</code>```

I tried to change compile to implementation and api but they all gave the same erros. Can someone please help me solve this...

Here is my gradle file:

```<code>buildscript {
        repositories {
            maven { url 'https://maven.fabric.io/public' }
        }

        dependencies {
            classpath 'io.fabric.tools:gradle:1.+'
        }
    }

    buildscript {
        repositories {

            repositories {
                maven { url 'https://maven.fabric.io/public' }
            }
            maven { url 'https://maven.fabric.io/public' }
        }

        dependencies {
            classpath 'io.fabric.tools:gradle:1.+'
        }
    }
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }
    apply plugin: 'com.android.application'
    apply plugin: 'io.fabric'

    android {
        compileSdkVersion 25
        buildToolsVersion "26.0.0"
        defaultConfig {
            applicationId "com.trynagrub.trynagrub"
            minSdkVersion 21
            targetSdkVersion 25
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    dependencies {
        api fileTree(include: ['*.jar'], dir: 'libs')
        androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })
        api files('libs/signalr-client-sdk.jar')
        api files('libs/signalr-client-sdk-android.jar')
        compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
            transitive = true;
        }
        compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
            transitive = true;
        }
        api 'org.zakariya.stickyheaders:stickyheaders:0.7.6'
        api 'net.danlew:android.joda:2.9.9'
        api 'com.hbb20:ccp:2.0.3'
        api 'com.squareup.picasso:picasso:2.5.2'
        api 'com.xw.repo:bubbleseekbar:3.6'
        api 'com.github.pavlospt:circleview:1.3'
        api 'com.facebook.android:facebook-android-sdk:[4,5)'
        api 'com.amitshekhar.android:android-networking:1.0.0'
        api 'de.hdodenhof:circleimageview:2.2.0'
        api 'com.android.support.constraint:constraint-layout:1.0.2'
        api 'com.github.stfalcon:chatkit:0.2.2'
        api 'com.google.android.gms:play-services-gcm:11.0.4'
        api 'com.snatik:storage:2.1.0'
        api 'com.github.tamir7.contacts:contacts:1.1.7'
        api 'com.google.android.gms:play-services-maps:11.0.4'
        testCompile 'junit:junit:4.12'
    }
    apply plugin: 'com.google.gms.google-services'
</code>```

答:
Use Build Tools 26.0.2 or higher.

Android Plugin for Gradle Release Notes

3.0.0 (October 2017)

This version of the Android plugin requires the following:

  Gradle 4.1 or higher.

  Build Tools 26.0.2 or higher.

NB: 3.0.0 is a version of Gradle plugin (in build.gradle of project).

4.1 is a version of Gradle (in gradle-wrapper.properties).

For information: AAPT2 related questions

corrupted manifest

NB: You also have problems after disabling AAPT2, so these may not work for your case.

My Android manifest is full of errors after updating to Android 3.0.0 [duplicate] and

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

Element hierarchies in the Android manifest

In previous versions of AAPT, elements nested in incorrect nodes in the Android manifest are either ignored or result in a warning.

Non-ASCII or ' '(space) characters in gradle folder path

NB: Same problem also occurs before upgrading in this case, I think.

…com.android.tools.aapt2.Aapt2Exception:.AAPT2 error:check logs for details and

Android Studio 3.0 migration AAPT2 error

ContentLicense: CC BY-SA 3.0

Body:
Before I updated to android studio 3 and gradle 3.0.1 I could build my project without a problem, but ever since I updated I keep getting this errors:

Error:failed linking references.
    Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:Execution failed for task ':app:processDebugResources'.
            > Failed to execute aapt

I tried to disable AAPT2 but then I get an error ProcessException for aapt

Error:java.util.concurrent.ExecutionException:
com.android.ide.common.process.ProcessException: Error while executing
process /build-tools/26.0.2/aapt with arguments {package -f --no-crunch
-I /android-25/android.jar -M

I tried to change compile to implementation and api but they all gave the same erros. Can someone please help me solve this...

Here is my gradle file:

buildscript {
        repositories {
            maven { url 'https://maven.fabric.io/public' }
        }

        dependencies {
            classpath 'io.fabric.tools:gradle:1.+'
        }
    }

    buildscript {
        repositories {

            repositories {
                maven { url 'https://maven.fabric.io/public' }
            }
            maven { url 'https://maven.fabric.io/public' }
        }

        dependencies {
            classpath 'io.fabric.tools:gradle:1.+'
        }
    }
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }
    apply plugin: 'com.android.application'
    apply plugin: 'io.fabric'

    android {
        compileSdkVersion 25
        buildToolsVersion "26.0.0"
        defaultConfig {
            applicationId "com.trynagrub.trynagrub"
            minSdkVersion 21
            targetSdkVersion 25
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    dependencies {
        api fileTree(include: ['*.jar'], dir: 'libs')
        androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })
        api files('libs/signalr-client-sdk.jar')
        api files('libs/signalr-client-sdk-android.jar')
        compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
            transitive = true;
        }
        compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
            transitive = true;
        }
        api 'org.zakariya.stickyheaders:stickyheaders:0.7.6'
        api 'net.danlew:android.joda:2.9.9'
        api 'com.hbb20:ccp:2.0.3'
        api 'com.squareup.picasso:picasso:2.5.2'
        api 'com.xw.repo:bubbleseekbar:3.6'
        api 'com.github.pavlospt:circleview:1.3'
        api 'com.facebook.android:facebook-android-sdk:[4,5)'
        api 'com.amitshekhar.android:android-networking:1.0.0'
        api 'de.hdodenhof:circleimageview:2.2.0'
        api 'com.android.support.constraint:constraint-layout:1.0.2'
        api 'com.github.stfalcon:chatkit:0.2.2'
        api 'com.google.android.gms:play-services-gcm:11.0.4'
        api 'com.snatik:storage:2.1.0'
        api 'com.github.tamir7.contacts:contacts:1.1.7'
        api 'com.google.android.gms:play-services-maps:11.0.4'
        testCompile 'junit:junit:4.12'
    }
    apply plugin: 'com.google.gms.google-services'


问:
How to query edge from graph in networkx 2.0 "by name"
I have a directed multi graph. With networkx 2.0 I found that the edges are returned as tuple made of (start_node, end_node, integer), where the integer is generated to distinguish multiple edges between same nodes.

With networks 1.x I could get an edge using:

```<code>edge = G.edge[start_node][end_node]
</code>```

With v2.0 this doesn't work anymore, because "edges" isn't a nested dict anymore. A change to:

```<code>edge = G.edges(start_node, end_node)
</code>```

doesn't work "{ValueError}too many values to unpack (expected 3)", because it misses the integer to identify the single edge within the multi edge. Whether or not multiple edges exist between nodes isn't fixed, same for the number of multi edges.

Does that mean I always have to iterate over edges?

答:
```<code>edge = networkx.edges(graph, [node1, node2])
</code>```

https://networkx.github.io/documentation/stable/reference/generated/networkx.classes.function.edges.html#networkx.classes.function.edges

Body:
I have a directed multi graph. With networkx 2.0 I found that the edges are returned as tuple made of (start_node, end_node, integer), where the integer is generated to distinguish multiple edges between same nodes.

With networks 1.x I could get an edge using:

edge = G.edge[start_node][end_node]

With v2.0 this doesn't work anymore, because "edges" isn't a nested dict anymore. A change to:

edge = G.edges(start_node, end_node)

doesn't work "{ValueError}too many values to unpack (expected 3)", because it misses the integer to identify the single edge within the multi edge. Whether or not multiple edges exist between nodes isn't fixed, same for the number of multi edges.

Does that mean I always have to iterate over edges?

Body:
edge = networkx.edges(graph, [node1, node2])

https://networkx.github.io/documentation/stable/reference/generated/networkx.classes.function.edges.html#networkx.classes.function.edges


问:
Window.scroll within an iframe
I searched, but couldn't find anything.

I have a sticky header that shows up on the page after scrolling down on the page. This was working wonderfully on the page. However, I now have to unfortunately have to put it within an iframe.

I have to same exact code, but I believe it's the window.scroll that is causing it to trip up. The content is just sitting at the top of the page behind everything and when inspecting the code it stops at that function and goes no further.

Is there an alternative to window.scroll (or scroll function) or is there a way to make it work within an iframe? All my attempts have failed.

My example is here https://www.bootply.com/edHiY15iJy#

My HTML for the header

```<code><div class="container">
        <header class="header-wrapper">
            <div class="sticky-header">
                <div class="row">
                        <div class="col-md-4">
                        <div class="form-group">
                            <label class="bold">Customer Name: </label>
                            <label>Person!! </label>
                        </div>
                        <div class="form-group">
                            <label class="bold">Address: </label>
                            <label>101 Main Street </label>
                        </div>

                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="bold">Email:</label>
                            <label>something@email.com </label>
                        </div>
                        <div class="form-group">
                            <label class="bold">City, State:</label>
                            <label>Tavierner, FL </label>
                        </div>

                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="bold">Phone:</label>
                            <label>555-555-5555 </label>
                        </div>

                        <div class="form-group">
                            <label class="bold">Club Code:</label>
                            <label>456 </label>
                            <label class="bold">Associate#:</label>
                            <label>45 </label>
                        </div>
                    </div>
                </div>
            </div>
        </header>
  <section>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>
    <p>this</p><p>this</p><p>this</p><p>this</p><p>this</p>

  </section>
</div>
</code>```

and my jquery

```<code> if ($('.sticky-header').length >= 1) {
        $(window).scroll(function () {
            var header = $(document).scrollTop();
            var headerHeight = $('.header-wrapper').height();
            if (header > headerHeight) {
                $('.sticky-header').addClass('sticky');
                $('.sticky-header').fadeIn();
            } else {
                $('.sticky-header').removeClass('sticky');
            }
        });
    }
</code>```

A screenshot of what the menu looks like when it's not working:

答: Check the code rendered in your example (https://www.bootply.com/edHiY15iJy#)  it's in "iFrame". I think what you are missing is the "css code" in your inner iframe code. </p>

Title: Window.scroll within an iframe

Body:
I searched, but couldn't find anything.

I have a sticky header that shows up on the page after scrolling down on the page. This was working wonderfully on the page. However, I now have to unfortunately have to put it within an iframe.

I have to same exact code, but I believe it's the window.scroll that is causing it to trip up. The content is just sitting at the top of the page behind everything and when inspecting the code it stops at that function and goes no further.

Is there an alternative to window.scroll (or scroll function) or is there a way to make it work within an iframe? All my attempts have failed.

My example is here https://www.bootply.com/edHiY15iJy#

My HTML for the header

                            Customer Name:
                            Person!!

                            Address:
                            101 Main Street

                            Email:
                            something@email.com

                            City, State:
                            Tavierner, FL

                            Phone:
                            555-555-5555

                            Club Code:
                            456
                            Associate#:
                            45

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

this

and my jquery

 if ($('.sticky-header').length >= 1) {
        $(window).scroll(function () {
            var header = $(document).scrollTop();
            var headerHeight = $('.header-wrapper').height();
            if (header > headerHeight) {
                $('.sticky-header').addClass('sticky');
                $('.sticky-header').fadeIn();
            } else {
                $('.sticky-header').removeClass('sticky');
            }
        });
    }

A screenshot of what the menu looks like when it's not working:


问:
Emacs with nice page break lines?
Under Emacs, how to get nice page-break-lines like these?

答:
Library Pretty Control-L lets you do that.  You can easily customize the appearance of a page-break (aka line feed, aka Control-l character).
The library is pp-c-l.el.

Mode pretty-control-l-mode turns the display on and off.

You have these user options and face, which you can customize:

pp^L-^L-string - Highlighted string displayed in place of each Control-l (^L) character.

pp^L-^L-string-pre - String displayed just before pp^L-^L-string.

pp^L-^L-string-post - String displayed just after pp^L-^L-string (empty by default).

pp^L-^L-string-function - Function to produce string displayed in place of a Control-l (^L) char.  If the option value is non-nil, option pp^L-^L-string is not used.
You can use this option to have a dynamically defined display string.
For example, this value displays a window-width horizontal line:

```<code>(lambda (win) (make-string (1- (window-width win)) ?_))
</code>```

pp^L-highlight (a face, not a variable) - Face used to highlight pp^L-^L-vector.

Title: Emacs with nice page break lines?

Body:
Library Pretty Control-L lets you do that.  You can easily customize the appearance of a page-break (aka line feed, aka Control-l character).
The library is pp-c-l.el.

Mode pretty-control-l-mode turns the display on and off.

You have these user options and face, which you can customize:

pp^L-^L-string - Highlighted string displayed in place of each Control-l (^L) character.

pp^L-^L-string-pre - String displayed just before pp^L-^L-string.

pp^L-^L-string-post - String displayed just after pp^L-^L-string (empty by default).

pp^L-^L-string-function - Function to produce string displayed in place of a Control-l (^L) char.  If the option value is non-nil, option pp^L-^L-string is not used.
You can use this option to have a dynamically defined display string.
For example, this value displays a window-width horizontal line:

(lambda (win) (make-string (1- (window-width win)) ?_))

pp^L-highlight (a face, not a variable) - Face used to highlight pp^L-^L-vector.


问:
WPF overload custom binding constructor
Here is my code:

```<code>public class MyBinding : Binding {

    public MyBinding(string path, bool value) : base(path) { /*...*/ }

    public MyBinding(string path, int value) : base(path) { /*...*/ }

}
</code>```

I can do this:

```<code><Control Property="{MyBinding Variable, True}" />
</code>```

But can't do this:

```<code><Control Property="{MyBinding Variable, 123}" />
</code>```

It seems like only the first constructor is taken into account. Why?

答:
You're not going to get overloading working on the constructor, but you can add typed properties.

```<code>public class MyBinding : Binding
{
    public MyBinding(string path) : base(path)
    {
    }

    private int _intvalue = 0;
    public int IntValue { get => _intvalue; set { _intvalue = value; } }

    private string _stringvalue = null;
    public string StringValue { get => _stringvalue; set { _stringvalue = value; } }
}
</code>```

XAML:

```<code>    <Label Content="{local:MyBinding SomeProperty, IntValue=123}" />
    <Label Content="{local:MyBinding SomeProperty, StringValue=123}" />
</code>```

I would not choose this solution, but it's an option:

```<code>public MyBinding(string path, string param) : base(path)
{
    int x;
    double d;
    bool b;
    if (Int32.TryParse(param, out x))
    {
        //  ...
    }
    else if (Double.TryParse(param, out d))
    {
        //  ...
    }
    else if (Boolean.TryParse(param, out b))
    {
        //  ...
    }
}
</code>```

Title: WPF overload custom binding constructor

Body:
Here is my code:

public class MyBinding : Binding {

    public MyBinding(string path, bool value) : base(path) { /*...*/ }

    public MyBinding(string path, int value) : base(path) { /*...*/ }

}

I can do this:

<Control Property="{MyBinding Variable, True}" />

But can't do this:

<Control Property="{MyBinding Variable, 123}" />

It seems like only the first constructor is taken into account. Why?

Body:
You're not going to get overloading working on the constructor, but you can add typed properties.

public class MyBinding : Binding
{
    public MyBinding(string path) : base(path)
    {
    }

    private int _intvalue = 0;
    public int IntValue { get => _intvalue; set { _intvalue = value; } }

    private string _stringvalue = null;
    public string StringValue { get => _stringvalue; set { _stringvalue = value; } }
}

XAML:

    <Label Content="{local:MyBinding SomeProperty, IntValue=123}" />
    <Label Content="{local:MyBinding SomeProperty, StringValue=123}" />

I would not choose this solution, but it's an option:

public MyBinding(string path, string param) : base(path)
{
    int x;
    double d;
    bool b;
    if (Int32.TryParse(param, out x))
    {
        //  ...
    }
    else if (Double.TryParse(param, out d))
    {
        //  ...
    }
    else if (Boolean.TryParse(param, out b))
    {
        //  ...
    }
}


问:
Regular Expressions in java trying to match a string in specific format (format consists of | sysbol)
Regular Expressions in java

```<code>String s1="Anil-anilorg|anotherorg";
String s2="Anil-anilorg|";
</code>```

I want to find weather s2 is present or sub-string of s1 by using regular expressions, but while I am doing that it is considering this symbol  "|" as logical OR
I am using hbaseStringRegexComparator to compare

答: You need to escape the | as \|, and within a String it becomes "\\|".

Body:
Regular Expressions in java

String s1="Anil-anilorg|anotherorg";
String s2="Anil-anilorg|";

I want to find weather s2 is present or sub-string of s1 by using regular expressions, but while I am doing that it is considering this symbol  "|" as logical OR
I am using hbaseStringRegexComparator to compare


问:
In R, how do I wrap text around all words in a string, but a specific one(going from left to right)? Iteration and string manipulation
I know my question is a little vague, so I have an example of what I'm trying to do.

```<code>input <- c('I go to school')

#Output
'"I " * phantom("go to school")'
'phantom("I ") * "go" * phantom("to school")'
'phantom("I go ") * "to" * phantom("school")'
'phantom("I go to ") * "school"'
</code>```

I've written a function, but I'm having a lot of trouble figuring out how to make it applicable to strings with different numbers of words and I can't figure out how I can include iteration to reduce copied code. It does generate the output above though.

Right now my function only works on strings with 4 words. It also includes no iteration.

My main questions are: How can I include iteration into my function? How can I make it work for any number of words?

```<code>add_phantom <- function(stuff){
  strings <- c()
  stuff <- str_split(stuff, ' ')
  strings[1] <- str_c('"', stuff[[1]][[1]], ' "', ' * ',
                 'phantom("', str_c(stuff[[1]][[2]], stuff[[1]][[3]], stuff[[1]][[4]], sep = ' '), '")')

  strings[2] <- str_c('phantom("', stuff[[1]][[1]], ' ")',
                      ' * "', stuff[[1]][[2]], '" * ',
                      'phantom("', str_c(stuff[[1]][[3]], stuff[[1]][[4]], sep = ' '), '")')

  strings[3] <- str_c('phantom("', str_c(stuff[[1]][[1]], stuff[[1]][[2]], sep = ' '), ' ")',
                      ' * "', stuff[[1]][[3]], '" * ',
                      'phantom("', stuff[[1]][[4]], '")')

  strings[4] <- str_c('phantom("', str_c(stuff[[1]][[1]], stuff[[1]][[2]], stuff[[1]][[3]], sep = ' '), ' ")',
                      ' * "', stuff[[1]][[4]], '"')
  return(strings)
}
</code>```

答:
I would suggest something like this

```<code>library(tidyverse)
library(glue)

test_string <- "i go to school"

str_split(test_string, " ") %>%
  map(~str_split(test_string, .x, simplify = T)) %>%
  flatten() %>%
  map(str_trim) %>%
  keep(~.x != "") %>%
  map(~glue("phantom({string})", string = .x))
</code>```

This code snippet can easily be implemented in a function and will return the following output.

```<code>[[1]]
phantom(i)

[[2]]
phantom(i go)

[[3]]
phantom(i go to)

[[4]]
phantom(go to school)

[[5]]
phantom(to school)

[[6]]
phantom(school)
</code>```

I might have misinterpreted your question -- i am not quite sure if you really want the output to have the same format as in your examplary output.

Body:
I know my question is a little vague, so I have an example of what I'm trying to do.

input <- c('I go to school')

#Output
'"I " * phantom("go to school")'
'phantom("I ") * "go" * phantom("to school")'
'phantom("I go ") * "to" * phantom("school")'
'phantom("I go to ") * "school"'

I've written a function, but I'm having a lot of trouble figuring out how to make it applicable to strings with different numbers of words and I can't figure out how I can include iteration to reduce copied code. It does generate the output above though.

Right now my function only works on strings with 4 words. It also includes no iteration.

My main questions are: How can I include iteration into my function? How can I make it work for any number of words?

add_phantom <- function(stuff){
  strings <- c()
  stuff <- str_split(stuff, ' ')
  strings[1] <- str_c('"', stuff[[1]][[1]], ' "', ' * ',
                 'phantom("', str_c(stuff[[1]][[2]], stuff[[1]][[3]], stuff[[1]][[4]], sep = ' '), '")')

  strings[2] <- str_c('phantom("', stuff[[1]][[1]], ' ")',
                      ' * "', stuff[[1]][[2]], '" * ',
                      'phantom("', str_c(stuff[[1]][[3]], stuff[[1]][[4]], sep = ' '), '")')

  strings[3] <- str_c('phantom("', str_c(stuff[[1]][[1]], stuff[[1]][[2]], sep = ' '), ' ")',
                      ' * "', stuff[[1]][[3]], '" * ',
                      'phantom("', stuff[[1]][[4]], '")')

  strings[4] <- str_c('phantom("', str_c(stuff[[1]][[1]], stuff[[1]][[2]], stuff[[1]][[3]], sep = ' '), ' ")',
                      ' * "', stuff[[1]][[4]], '"')
  return(strings)
}

Body:
I would suggest something like this

library(tidyverse)
library(glue)

test_string <- "i go to school"

str_split(test_string, " ") %>%
  map(~str_split(test_string, .x, simplify = T)) %>%
  flatten() %>%
  map(str_trim) %>%
  keep(~.x != "") %>%
  map(~glue("phantom({string})", string = .x))

This code snippet can easily be implemented in a function and will return the following output.

[[1]]
phantom(i)

[[2]]
phantom(i go)

[[3]]
phantom(i go to)

[[4]]
phantom(go to school)

[[5]]
phantom(to school)

[[6]]
phantom(school)

I might have misinterpreted your question -- i am not quite sure if you really want the output to have the same format as in your examplary output.


问:
.Net Core Async Await is not continuing Execution
I have a list of tasks, that will call a webservice restfully. I begin the execution of them when calling downloadTasksQuery.ToList(). At that point I would like to process each task as they finish, and add the Distance to the database as soon as it finishes.

When I watch this in the console. All records seem to print to the console all at the same time, and I see the outputis from this line. Console.WriteLine(" Google Distance : " + d.google_distance);

The number of times it prints to the console is the number that were in the List of Tasks to begin with.

```<code>IEnumerable<Task<Distances>> downloadTasksQuery =
    (from tup in urlList select ProcessURL(tup));

List<Task<Distances>> downloadTasks = downloadTasksQuery.ToList();

while (downloadTasks.Count > 0)
{
    Task<Distances> thisFinished = await Task.WhenAny(downloadTasks);

    downloadTasks.Remove(thisFinished);
    try
    {
        Distances d = await thisFinished;
        if (d.has_error == false)
        {
            dr.Add(d);
        }
        else
        {
            dr.AddError(d);
        }
        Console.WriteLine(" Google Distance : " + d.google_distance);
    }
    catch (Exception e)
    {
        Console.WriteLine("Deleted task, did not save data");
    }
}
</code>```

Process URL

```<code>private static async Task<Distances> ProcessURL(Tuple<string, int, string> tup)
{
    HttpClient client = new HttpClient();
    Distances d = new Distances();
    try
        {
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
               //// Post is required by the web api
            var stringTask = client.PostAsync("https://website.com" + tup.Item1, new StringContent("null"));

            var msg2 = await stringTask.Result.Content.ReadAsStringAsync();
            d = FromXml<Distances>(msg2.Trim());

        }

    catch (Exception e)
        {
            d.has_error = true;
        }
    d.state_student_identifier = tup.Item3;
    d.student_transportation_id = tup.Item2;
    return d;
}
</code>```

答:
I would suggest utilizing ContinueWith as it seems more suited for what you are trying to do:

```<code>var runningTasks = urlList.Select(tup => ProcessURL(tup)
    .ContinueWith(task =>
    {
        var d = task.Result;
        if (d.has_error)
            dr.AddError(d);
        else
            dr.Add(d);
        Console.WriteLine(" Google Distance : " + d.google_distance);
    }));
await Task.WhenAll(runningTasks);
</code>```

Body:
I have a list of tasks, that will call a webservice restfully. I begin the execution of them when calling downloadTasksQuery.ToList(). At that point I would like to process each task as they finish, and add the Distance to the database as soon as it finishes.

When I watch this in the console. All records seem to print to the console all at the same time, and I see the outputis from this line. Console.WriteLine(" Google Distance : " + d.google_distance);

The number of times it prints to the console is the number that were in the List of Tasks to begin with.

IEnumerable<Task<Distances>> downloadTasksQuery =
    (from tup in urlList select ProcessURL(tup));

List<Task<Distances>> downloadTasks = downloadTasksQuery.ToList();

while (downloadTasks.Count > 0)
{
    Task<Distances> thisFinished = await Task.WhenAny(downloadTasks);

    downloadTasks.Remove(thisFinished);
    try
    {
        Distances d = await thisFinished;
        if (d.has_error == false)
        {
            dr.Add(d);
        }
        else
        {
            dr.AddError(d);
        }
        Console.WriteLine(" Google Distance : " + d.google_distance);
    }
    catch (Exception e)
    {
        Console.WriteLine("Deleted task, did not save data");
    }
}

Process URL

private static async Task<Distances> ProcessURL(Tuple<string, int, string> tup)
{
    HttpClient client = new HttpClient();
    Distances d = new Distances();
    try
        {
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
               //// Post is required by the web api
            var stringTask = client.PostAsync("https://website.com" + tup.Item1, new StringContent("null"));

            var msg2 = await stringTask.Result.Content.ReadAsStringAsync();
            d = FromXml<Distances>(msg2.Trim());

        }

    catch (Exception e)
        {
            d.has_error = true;
        }
    d.state_student_identifier = tup.Item3;
    d.student_transportation_id = tup.Item2;
    return d;
}

Body:
I would suggest utilizing ContinueWith as it seems more suited for what you are trying to do:

var runningTasks = urlList.Select(tup => ProcessURL(tup)
    .ContinueWith(task =>
    {
        var d = task.Result;
        if (d.has_error)
            dr.AddError(d);
        else
            dr.Add(d);
        Console.WriteLine(" Google Distance : " + d.google_distance);
    }));
await Task.WhenAll(runningTasks);


问:
Vb.net Using child instance in a parent-typed variable
I'm more familiar with how Java does polymorphism so I might be doing it wrong in vb

I'm trying use polymorphism and inheritance to have one instance that can take on multiple forms,
the issue is the variable is instantiated as the parent type and initialized as a child class instance but I can't access the child properties.

below is an example what i'm trying to do:

```<code>sub main()
  Dim animal as Animal           'instantiated as parent type
  'some code later
  animal= New Dog()              'no problems here
  dim legs = animal.legs         'this works
  dim fur = animal.fur           'this is an error
end sub

Public Class Animal
  Property legs as integer
End Class

Public Class Dog
  inherits Animal
  Property fur as Boolean = True
End Class
</code>```

It would be great if i could get this to work.

答:
This is actually declaring, not instantiating.

Dim animal as Animal

And if you know it is an animal, then create it as one like so:

Dim doggo As New Dog

The only time you should need to treat the Dog as an Animal is if you are performing something on it's Legs.

For example (in the Animal class):

```<code>Shared Sub AmputateLeg(patient As Animal)
    patient.Legs = patient.Legs - 1
End Sub
</code>```

That you can call from Dog like so:

```<code>Dim doggo As New Dog()
doggo.Legs = 4
Animal.AmputateLeg(doggo)
Console.WriteLine(doggo.Legs) ' Shows 3.
</code>```

As Plutonix commented, a base class should not know anything about the derived class, hence the IDE can't locate the Fur property when the Dog is treated as an Animal type

Perhaps you want something along the lines of an Interface instead

```<code>Public Interface IAnimal
    Property Fur As Boolean
    Property Legs As Integer
End Interface

Public Class Dog
    Implements IAnimal

    Public Property Fur As Boolean = True Implements IAnimal.Fur
    Public Property Legs As Integer = 4 Implements IAnimal.Legs
End Class

Public Class Duck
    Implements IAnimal

    Public Property Fur As Boolean = False Implements IAnimal.Fur
    Public Property Legs As Integer = 2 Implements IAnimal.Legs
End Class
</code>```

Using an Interface this way means that you can always refer to Legs and Fur of any animal.

Body:
I'm more familiar with how Java does polymorphism so I might be doing it wrong in vb

I'm trying use polymorphism and inheritance to have one instance that can take on multiple forms,
the issue is the variable is instantiated as the parent type and initialized as a child class instance but I can't access the child properties.

below is an example what i'm trying to do:

sub main()
  Dim animal as Animal           'instantiated as parent type
  'some code later
  animal= New Dog()              'no problems here
  dim legs = animal.legs         'this works
  dim fur = animal.fur           'this is an error
end sub

Public Class Animal
  Property legs as integer
End Class

Public Class Dog
  inherits Animal
  Property fur as Boolean = True
End Class

It would be great if i could get this to work.

Body:
This is actually declaring, not instantiating.

Dim animal as Animal

And if you know it is an animal, then create it as one like so:

Dim doggo As New Dog

The only time you should need to treat the Dog as an Animal is if you are performing something on it's Legs.

For example (in the Animal class):

Shared Sub AmputateLeg(patient As Animal)
    patient.Legs = patient.Legs - 1
End Sub

That you can call from Dog like so:

Dim doggo As New Dog()
doggo.Legs = 4
Animal.AmputateLeg(doggo)
Console.WriteLine(doggo.Legs) ' Shows 3.

As Plutonix commented, a base class should not know anything about the derived class, hence the IDE can't locate the Fur property when the Dog is treated as an Animal type

Perhaps you want something along the lines of an Interface instead

Public Interface IAnimal
    Property Fur As Boolean
    Property Legs As Integer
End Interface

Public Class Dog
    Implements IAnimal

    Public Property Fur As Boolean = True Implements IAnimal.Fur
    Public Property Legs As Integer = 4 Implements IAnimal.Legs
End Class

Public Class Duck
    Implements IAnimal

    Public Property Fur As Boolean = False Implements IAnimal.Fur
    Public Property Legs As Integer = 2 Implements IAnimal.Legs
End Class

Using an Interface this way means that you can always refer to Legs and Fur of any animal.


问:
Getting date from SQL Server using users input through winform
I'm supposed to take date from the user and then find all dates before that date.

```<code>DateTime dat = dateTimePicker1.Value.Date;
string datS = dat1.ToString("yyyy-MM-dd");
string query = "SELECT * FROM test3table WHERE datum" +
                  " <= " + "datum LIKE '%' + @Datum + '%'";
// '2017-12-06'   -> works fine
SqlCommand comm = new SqlCommand(query, conn);
comm.Parameters.AddWithValue("@Datum", datS);
</code>```

Is something wrong with syntax or it cant be done this way?

答:
Your SQL query has incorrect syntax.  I believe what you need is this:

```<code>string query = "SELECT * FROM test3table WHERE datum" +
               " < '" + @Datum + "'";
</code>```

This should construct a SQL query that looks something like this:

```<code>SELECT * FROM test3table WHERE datum < '2017-12-06'
</code>```

Note that I changed your <= operator to < to match your stated need for "all dates before that date".

Also remember that if datum is of type DATETIME, then a date value will be evaluated with a time of midnight.  So 2017-12-06 is read as 2017-12-06 00:00.

Body:
I'm supposed to take date from the user and then find all dates before that date.

DateTime dat = dateTimePicker1.Value.Date;
string datS = dat1.ToString("yyyy-MM-dd");
string query = "SELECT * FROM test3table WHERE datum" +
                  " <= " + "datum LIKE '%' + @Datum + '%'";
// '2017-12-06'   -> works fine
SqlCommand comm = new SqlCommand(query, conn);
comm.Parameters.AddWithValue("@Datum", datS);

Is something wrong with syntax or it cant be done this way?

Body:
Your SQL query has incorrect syntax.  I believe what you need is this:

string query = "SELECT * FROM test3table WHERE datum" +
               " < '" + @Datum + "'";

This should construct a SQL query that looks something like this:

SELECT * FROM test3table WHERE datum < '2017-12-06'

Note that I changed your <= operator to < to match your stated need for "all dates before that date".

Also remember that if datum is of type DATETIME, then a date value will be evaluated with a time of midnight.  So 2017-12-06 is read as 2017-12-06 00:00.


问:
How do you use the Java word boundary with apostrophes?
I am trying to delete all the occurrences of a word in a list, but I am having trouble when there are apostrophes in the words.

```<code>String phrase="bob has a bike and bob's bike is red";
String word="bob";
phrase=phrase.replaceAll("\\b"+word+"\\b","");
System.out.println(phrase);
</code>```

output:

has a bike and 's bike is red

What I want is

has a bike and bob's bike is red

I have a limited understanding of regex so I'm guessing there is a solution, but I do not now enough to create the regex to handle apostrophes.  Also I would like it to work with dashes so the phrase the new mail is e-mail would only replace the first occurrence of mail.

答:
It all depends on what you understan to be a "word". Perhaps you'd better define what you understand to be a word delimiter: for example, blanks, commas .... And write something as

```<code>phrase=phrase.replaceAll("([ \\s,.;])" + Pattern.quote(word)+ "([ \\s,.;])","$1$2");
</code>```

But you'll have to check additionally for occurrences at the start and the end of the string
For example:

```<code>  String phrase="bob has a bike bob, bob and boba bob's bike is red and \"bob\" stuff.";
  String word="bob";
  phrase=phrase.replaceAll("([\\s,.;])" + Pattern.quote(word) + "([\\s,.;])","$1$2");
  System.out.println(phrase);
</code>```

prints  this

```<code>bob has a bike ,  and boba bob's bike is red and "bob" stuff.
</code>```

Update: If you insist in using \b, considering that the "word boundary" understand Unicode, you can also do this dirty trick: replace all ocurrences of ' by some Unicode letter that you're are sure will not appear in your text, and afterwards do the reverse replacemente. Example:

```<code>  String phrase="bob has a bike bob, bob and boba bob's bike is red and \"bob\" stuff.";
  String word="bob";
  phrase= phrase.replace("'","ñ").replace('"','ö');
  phrase=phrase.replaceAll("\\b" + Pattern.quote(word) + "\\b","");
  phrase= phrase.replace('ö','"').replace("ñ","'");
  System.out.println(phrase);
</code>```

UPDATE: To summarize some comments below: one would expect \w and \b to have the same notion as to which is a "word character", as almost every regular-expression dialect do. Well, Java does not: \w considers ASCII, \b considers Unicode. It's an ugly inconsistence, I agree.

Update 2: Since Java 7 (as pointed out in comments) the UNICODE_CHARACTER_CLASS flag allows to specify a consistent Unicode-only behaviour, see eg here.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to delete all the occurrences of a word in a list, but I am having trouble when there are apostrophes in the words.

String phrase="bob has a bike and bob's bike is red";
String word="bob";
phrase=phrase.replaceAll("\\b"+word+"\\b","");
System.out.println(phrase);

output:

has a bike and 's bike is red

What I want is

has a bike and bob's bike is red

I have a limited understanding of regex so I'm guessing there is a solution, but I do not now enough to create the regex to handle apostrophes.  Also I would like it to work with dashes so the phrase the new mail is e-mail would only replace the first occurrence of mail.

Body:
It all depends on what you understan to be a "word". Perhaps you'd better define what you understand to be a word delimiter: for example, blanks, commas .... And write something as

phrase=phrase.replaceAll("([ \\s,.;])" + Pattern.quote(word)+ "([ \\s,.;])","$1$2");

But you'll have to check additionally for occurrences at the start and the end of the string
For example:

  String phrase="bob has a bike bob, bob and boba bob's bike is red and \"bob\" stuff.";
  String word="bob";
  phrase=phrase.replaceAll("([\\s,.;])" + Pattern.quote(word) + "([\\s,.;])","$1$2");
  System.out.println(phrase);

prints  this

bob has a bike ,  and boba bob's bike is red and "bob" stuff.

Update: If you insist in using \b, considering that the "word boundary" understand Unicode, you can also do this dirty trick: replace all ocurrences of ' by some Unicode letter that you're are sure will not appear in your text, and afterwards do the reverse replacemente. Example:

  String phrase="bob has a bike bob, bob and boba bob's bike is red and \"bob\" stuff.";
  String word="bob";
  phrase= phrase.replace("'","ñ").replace('"','ö');
  phrase=phrase.replaceAll("\\b" + Pattern.quote(word) + "\\b","");
  phrase= phrase.replace('ö','"').replace("ñ","'");
  System.out.println(phrase);

UPDATE: To summarize some comments below: one would expect \w and \b to have the same notion as to which is a "word character", as almost every regular-expression dialect do. Well, Java does not: \w considers ASCII, \b considers Unicode. It's an ugly inconsistence, I agree.

Update 2: Since Java 7 (as pointed out in comments) the UNICODE_CHARACTER_CLASS flag allows to specify a consistent Unicode-only behaviour, see eg here.


问:
ms Access '16 - Continuous form - OrderBy textbox value created with expression
I have a form that shows the records from Table-A, it is a continuous form. I have a textbox that uses a DCount expression to count records from Table-B that share the same SOP-Number.

```<code>=DCount("*","[Table-B]","SOP = " & [SOP])
</code>```

This works but I don't know how I would go about sorting that column based of the resulting values. The other columns are sorted thus:

```<code>" ORDER BY [FIELD NAME] ASC;"
</code>```

So without a field I don't know how (or if) I can sort the form.
Could I create a RecordSet to store the values then sort by that field (I don't know if this is even possible)

Thank you

Dan

Access 2016 (365)

答:
You can't sort the recordsource but you can sort the form itself:

```<code>Me.OrderBy = "NumTasks DESC"
Me.OrderByOn = True
</code>```

(assuming your textbox with the DCount control source is named NumTasks ).

Body:
I have a form that shows the records from Table-A, it is a continuous form. I have a textbox that uses a DCount expression to count records from Table-B that share the same SOP-Number.

=DCount("*","[Table-B]","SOP = " & [SOP])

This works but I don't know how I would go about sorting that column based of the resulting values. The other columns are sorted thus:

" ORDER BY [FIELD NAME] ASC;"

So without a field I don't know how (or if) I can sort the form.
Could I create a RecordSet to store the values then sort by that field (I don't know if this is even possible)

Thank you

Dan

Access 2016 (365)

Body:
You can't sort the recordsource but you can sort the form itself:

Me.OrderBy = "NumTasks DESC"
Me.OrderByOn = True

(assuming your textbox with the DCount control source is named NumTasks ).


问:
Floating point exception error while finding ''Perfect Number" using user defined functions
I have to write a program with checks "Perfect Numbers" in a specific range given by the user. I made a user-defined function to check if a particular number is a perfect number. If it is then 1 is returned, if not then 0. And then I use an if statement to print out the perfect number in the main program. The issue I'm getting is a floating point exception error. I have no idea what to do now. I'll be really grateful for some help. :).</p>

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

int isPerfect(int n);

int main(){
    int num=0,perfectCheck=0;
    cout<<"Enter a value for N: ";
    cin>>num;
    cout<<"Perect numbers between 1 and "<<num<<" are : "<<endl;
    for(int i;i<=num;i++){
        perfectCheck=isPerfect(i);
        if(perfectCheck==1){
              cout<<i<<endl;
        }
    }
    return 0;
}

int isPerfect(int n){
    int sum,mod;
    for(int i;i<n;i++){
        mod=n%i;
        if(mod==0){
            sum=sum+i;
        }
    }
    if(sum==n){
         return 1;
    }
    else{
        return 0;
    }
}
</code>```

答: Your for loop in isPerfect function should start from 1, because n%0 is undefined behavior.</p>

Body:
I have to write a program with checks "Perfect Numbers" in a specific range given by the user. I made a user-defined function to check if a particular number is a perfect number. If it is then 1 is returned, if not then 0. And then I use an if statement to print out the perfect number in the main program. The issue I'm getting is a floating point exception error. I have no idea what to do now. I'll be really grateful for some help. :).

#include <iostream>
using namespace std;

int isPerfect(int n);

int main(){
    int num=0,perfectCheck=0;
    cout<<"Enter a value for N: ";
    cin>>num;
    cout<<"Perect numbers between 1 and "<<num<<" are : "<<endl;
    for(int i;i<=num;i++){
        perfectCheck=isPerfect(i);
        if(perfectCheck==1){
              cout<<i<<endl;
        }
    }
    return 0;
}

int isPerfect(int n){
    int sum,mod;
    for(int i;i<n;i++){
        mod=n%i;
        if(mod==0){
            sum=sum+i;
        }
    }
    if(sum==n){
         return 1;
    }
    else{
        return 0;
    }
}


问:
How to get a key in a dictionary in a dictionary
here's my list :

```<code>data_config = [{'music': {' extension': 'mp3'}},
 {'reports/INFOB131': {' extension': ['doc', 'docx', 'pdf'],
   ' max_size': '100000',
   ' name_contains': 'INFOB131'}},
 {'reports/INFOB132': {' extension': ['doc', 'docx', 'pdf'],
   ' max_size': '100000',
   ' name_contains': 'INFOB132'}},
 {'games': {' name_contains': ['SC2', 'Wesnoth']}},
 {'pictures/Namur': {' extension': 'jpeg',
   ' min_size': '5000000',
   ' name_contains': 'cercle'}},
 {'pictures/autres': {' extension': 'jpeg', ' min_size': '5000000'}}]
</code>```

When I do these instructions, I get :

```<code>for i in data_config[0]['music']:
    print(data_config[0]['music'][i])

output : mp3
</code>```

But when I do this, I get an error:

```<code>print(data_config[0]['music']['extension'])

output : ---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-9-f71c5ad09034> in <module>()
----> 1 print(data_config[0]['music']['extension'])

KeyError: 'extension'
</code>```

Does anyone have an idea ?

Thank you !

答: In a few places, you have whitespaces. To get rid of them you may want to use .strip().

Body:
here's my list :

data_config = [{'music': {' extension': 'mp3'}},
 {'reports/INFOB131': {' extension': ['doc', 'docx', 'pdf'],
   ' max_size': '100000',
   ' name_contains': 'INFOB131'}},
 {'reports/INFOB132': {' extension': ['doc', 'docx', 'pdf'],
   ' max_size': '100000',
   ' name_contains': 'INFOB132'}},
 {'games': {' name_contains': ['SC2', 'Wesnoth']}},
 {'pictures/Namur': {' extension': 'jpeg',
   ' min_size': '5000000',
   ' name_contains': 'cercle'}},
 {'pictures/autres': {' extension': 'jpeg', ' min_size': '5000000'}}]

When I do these instructions, I get :

for i in data_config[0]['music']:
    print(data_config[0]['music'][i])

output : mp3

But when I do this, I get an error:

print(data_config[0]['music']['extension'])

output : ---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-9-f71c5ad09034> in <module>()
----> 1 print(data_config[0]['music']['extension'])

KeyError: 'extension'

Does anyone have an idea ?

Thank you !


问:
Apache Thrift. Method returning type changed after generation
I got an issue after regeneration my thrift file. Method returning type changed in getter and setter after generation, but structs weren't changed.

```<code>> struct Descriptor {
> 1: bool   paramOne,
> 2: i32    paramTwo,
> }
</code>```

before:

```<code>> public void setParamTwo(List<String> paramTwo) {
>   ......
>  }
</code>```

after:

```<code>> public Descriptor setParamTwo(List<String> paramTwo) {
>    ......
> }
</code>```

I used

thrift -r --gen java file.thrift

There are some options for configuring it?

Thanks.

答:
Okay.

Just need to add :beans in gen command

thrift -r --gen java:beans file.thrift

Body:
I got an issue after regeneration my thrift file. Method returning type changed in getter and setter after generation, but structs weren't changed.

> struct Descriptor {
> 1: bool   paramOne,
> 2: i32    paramTwo,
> }

before:

> public void setParamTwo(List<String> paramTwo) {
>   ......
>  }

after:

> public Descriptor setParamTwo(List<String> paramTwo) {
>    ......
> }

I used

thrift -r --gen java file.thrift

There are some options for configuring it?

Thanks.


问:
RabbitMQ is slow to start inside Windows Docker Container
Here is my dockerfile

```<code> FROM microsoft/windowsservercore

 # rabbitmq version used in download url and to rename folder extracted from
 zip file
ENV rabbitmq_version "3.6.11"

#download erlang and RabbitMQ
ADD "http://erlang.org/download/otp_win64_19.3.exe" "erlang_install.exe"
ADD "https://www.rabbitmq.com/releases/rabbitmq-server/v3.6.11/rabbitmq-
server-windows-3.6.11.zip" "rabbitmq.zip"

# erlang will install to this location and rabbitmq will use this
environment variable to locate it
ENV ERLANG_HOME c:\\erlang

# setup powershell options for RUN commands
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop';
$ProgressPreference = 'SilentlyContinue';"]

# install erlang using silent install option, and remove installer when done
RUN Start-Process -Wait -FilePath .\erlang_install.exe -ArgumentList /S,
/D=$env:ERLANG_HOME ; \
Remove-Item -Force erlang_install.exe

# extract rabbitmq, and remove zip file when done
RUN Expand-Archive -Path .\rabbitmq.zip -DestinationPath "c:\\" ; \
Remove-Item -Force rabbitmq.zip

# remove version from rabbitmq folder name
RUN Rename-Item c:\rabbitmq_server-$env:rabbitmq_version c:\rabbitmq

# enable managment plugin
RUN c:\rabbitmq\sbin\rabbitmq-plugins.bat enable rabbitmq_management --
offline

# tell rabbitmq where to find our custom config file
ENV RABBITMQ_CONFIG_FILE "c:\rabbitmq"
RUN ["cmd", "/c", "echo [{rabbit, [{loopback_users, []}]}].>
c:\\rabbitmq.config"]

EXPOSE 15672
EXPOSE 5672

# run server when container starts - container will shut down when this
process ends
CMD "c:\rabbitmq\sbin\rabbitmq-server.bat"
</code>```

When the container starts on my windows 10 machine it takes anywhere between 5-10 minutes to see that the actual broker started in the logs. I also cant hit the management portal and no apps can connect until the broker starts.
Is there any way to get the broker to start faster? It doesnt do this on linux containers

答:
When the container starts on my windows 10 machine it takes anywhere between 5-10 minutes to see that the actual broker started in the logs.

It appears that you are installing Erlang from scratch every time your container starts up (erlang_install.exe).

What Linux container did you try that does not exhibit this issue? Does it have RabbitMQ installed out-of-the-box? Can you use a Windows container with RabbitMQ pre-installed, or create a container image yourself that you can then re-use?

ContentLicense: CC BY-SA 4.0

Body:
Here is my dockerfile

 FROM microsoft/windowsservercore

 # rabbitmq version used in download url and to rename folder extracted from
 zip file
ENV rabbitmq_version "3.6.11"

#download erlang and RabbitMQ
ADD "http://erlang.org/download/otp_win64_19.3.exe" "erlang_install.exe"
ADD "https://www.rabbitmq.com/releases/rabbitmq-server/v3.6.11/rabbitmq-
server-windows-3.6.11.zip" "rabbitmq.zip"

# erlang will install to this location and rabbitmq will use this
environment variable to locate it
ENV ERLANG_HOME c:\\erlang

# setup powershell options for RUN commands
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop';
$ProgressPreference = 'SilentlyContinue';"]

# install erlang using silent install option, and remove installer when done
RUN Start-Process -Wait -FilePath .\erlang_install.exe -ArgumentList /S,
/D=$env:ERLANG_HOME ; \
Remove-Item -Force erlang_install.exe

# extract rabbitmq, and remove zip file when done
RUN Expand-Archive -Path .\rabbitmq.zip -DestinationPath "c:\\" ; \
Remove-Item -Force rabbitmq.zip

# remove version from rabbitmq folder name
RUN Rename-Item c:\rabbitmq_server-$env:rabbitmq_version c:\rabbitmq

# enable managment plugin
RUN c:\rabbitmq\sbin\rabbitmq-plugins.bat enable rabbitmq_management --
offline

# tell rabbitmq where to find our custom config file
ENV RABBITMQ_CONFIG_FILE "c:\rabbitmq"
RUN ["cmd", "/c", "echo [{rabbit, [{loopback_users, []}]}].>
c:\\rabbitmq.config"]

EXPOSE 15672
EXPOSE 5672

# run server when container starts - container will shut down when this
process ends
CMD "c:\rabbitmq\sbin\rabbitmq-server.bat"

When the container starts on my windows 10 machine it takes anywhere between 5-10 minutes to see that the actual broker started in the logs. I also cant hit the management portal and no apps can connect until the broker starts.
Is there any way to get the broker to start faster? It doesnt do this on linux containers


问:
Is there a more optimal way to concatenate this string
I was wondering if there's a more simple way to concatenate this string instead of declaring a temporary variable

```<code>string tempValue = "000000000000000" + moneyValue;
 moneyValue= tempValue.Substring((tempValue).Length - 15, 15);
</code>```

I'm looking to a shorter way of achieving same result , is there any?

答:
PadLeft works when you start with a string. If you want to combine zero padding with formatting of a number, you can use D15 format for integers

```<code>int moneyValue = 123456;
string moneyString = $"{moneyValue:D15}";
</code>```

or a custom format for other numeric types

```<code>decimal moneyValue = 1234.56;
string moneyString = $"{moneyValue:000000000000000}";
</code>```

Body:
I was wondering if there's a more simple way to concatenate this string instead of declaring a temporary variable

string tempValue = "000000000000000" + moneyValue;
 moneyValue= tempValue.Substring((tempValue).Length - 15, 15);

I'm looking to a shorter way of achieving same result , is there any?

Body:
PadLeft works when you start with a string. If you want to combine zero padding with formatting of a number, you can use D15 format for integers

int moneyValue = 123456;
string moneyString = $"{moneyValue:D15}";

or a custom format for other numeric types

decimal moneyValue = 1234.56;
string moneyString = $"{moneyValue:000000000000000}";


答:
```<code>        DateTime dat = dateTimePicker1.Value.Date;

        string query = "SELECT * FROM test3table WHERE datum <= @Datum";

        SqlCommand comm = new SqlCommand(query, conn);
        comm.Parameters.AddWithValue("@Datum", dat );
</code>```

Change your column type to DateTime to save yourself some trouble converting into string and back. Then you can just do the above.

Title: Getting date from SQL Server using users input through winform

Body:
        DateTime dat = dateTimePicker1.Value.Date;

        string query = "SELECT * FROM test3table WHERE datum <= @Datum";

        SqlCommand comm = new SqlCommand(query, conn);
        comm.Parameters.AddWithValue("@Datum", dat );

Change your column type to DateTime to save yourself some trouble converting into string and back. Then you can just do the above.


问:
PDF compressor for DELPHI 2007
Need a PDF compressor that I can use from DELPHI 2007.

What is the best one out there?

UPDATE ---

By PDF compressor I mean some way to compress an existing PDF. I don’t need to create new PDF files.

The usage that I’ll do with it, simple, I have in my applications the possibility to associate a file to a product, an entity, equipment whatever, and if the file is a PDF I want to be able reduce its size.

There some tools that can do this with no need to actually zip the file, what would mean that to see it you would have to decompress(unzip), this tools jut reduce the size.

So a PDF compressor, or call it what you will, is just this.

答:
If you need to create PDF from Delphi code, see this page in Delphi:about.

I'd like to add our Open Source SynPdf unit, working from Delphi 6 up to XE.

Title: PDF compressor for DELPHI 2007


问:
Mocking asynchronous requests within react's getInitialState
When i created this question, my doubt was about how would i be able to test an asynchronous request utilizing mocha/enzyme/chai/sinon.

I am sure that there are different ways, but a possible one is to mock it with a handmade function that returns the appropriate values (check the answer for details).

My getInitialState method is this:

```<code>getInitialState: function() {
    var me = this;
    var documentData = null;
    var promise = me.getDocuments();

    promise.then(function(value) {
        var documents = value.map(function(obj) {
            return Object.keys(obj).sort().map(function(key) {
                return obj[key];
            });
        });

        documentData = documents;
    });

    return ({
        cd: false
    });
},
</code>```

And the getDocuments() function that returns a promise is this:

```<code>getDocuments: function() {
    var deferred = when.defer();

    Collection.fetch({cd: workspaceInfo.getCD()}).then(
        function(results) {
            deferred.resolve(results);
        },
        deferred.reject
    );

    return deferred.promise;
},
</code>```

How can i successfuly test it?
Would i have to mock the getInitialState method itself? (is that even possible)

Or just the getDocuments function with some predictable return values?

Thanks in advance, any help will be appreciated.

答:
I solved this by requiring the Collection (which is a rest API that brings some values from a database)

```<code>var Collection = require("path/to/my/collection/Collection");
</code>```

Afterwards, i use it in my getDefaultProps() method:

```<code>getDefaultProps() {
        return {
            Collection: new Collection()
        };
    },
</code>```

And this in turn enables me to write tests that initialize a mocked Collection (fileDataResponse is a JSON with some data):

```<code>var CollectionMock= {
    fetch: () => {
        return {
            then: callback => callback(fileDataResponse)
        };
    }
};
</code>```

And use it in my test afterwards:

```<code>it("should open the modal without a loaded configuration", function() {
    var instance, wrapper;

    wrapper = mount(
        <DocumentPreview
        Collection={CollectionMock}/>
    );

    instance = wrapper.component.getInstance();
    instance.openModal();
    expect(wrapper.find('#MockedTest' + 'docOid251085').exists()).to.equal(true);

    wrapper.unmount();
});
</code>```

Body:
When i created this question, my doubt was about how would i be able to test an asynchronous request utilizing mocha/enzyme/chai/sinon.

I am sure that there are different ways, but a possible one is to mock it with a handmade function that returns the appropriate values (check the answer for details).

My getInitialState method is this:

getInitialState: function() {
    var me = this;
    var documentData = null;
    var promise = me.getDocuments();

    promise.then(function(value) {
        var documents = value.map(function(obj) {
            return Object.keys(obj).sort().map(function(key) {
                return obj[key];
            });
        });

        documentData = documents;
    });

    return ({
        cd: false
    });
},

And the getDocuments() function that returns a promise is this:

getDocuments: function() {
    var deferred = when.defer();

    Collection.fetch({cd: workspaceInfo.getCD()}).then(
        function(results) {
            deferred.resolve(results);
        },
        deferred.reject
    );

    return deferred.promise;
},

How can i successfuly test it?
Would i have to mock the getInitialState method itself? (is that even possible)

Or just the getDocuments function with some predictable return values?

Thanks in advance, any help will be appreciated.

Body:
I solved this by requiring the Collection (which is a rest API that brings some values from a database)

var Collection = require("path/to/my/collection/Collection");

Afterwards, i use it in my getDefaultProps() method:

getDefaultProps() {
        return {
            Collection: new Collection()
        };
    },

And this in turn enables me to write tests that initialize a mocked Collection (fileDataResponse is a JSON with some data):

var CollectionMock= {
    fetch: () => {
        return {
            then: callback => callback(fileDataResponse)
        };
    }
};

And use it in my test afterwards:

it("should open the modal without a loaded configuration", function() {
    var instance, wrapper;

    wrapper = mount(
        <DocumentPreview
        Collection={CollectionMock}/>
    );

    instance = wrapper.component.getInstance();
    instance.openModal();
    expect(wrapper.find('#MockedTest' + 'docOid251085').exists()).to.equal(true);

    wrapper.unmount();
});


问:
How do I save multiple pictures as different file names vb.net?
I would like to capture images from video screen shot and store them in a file. As the video plays multiple screen shots would we taken and all the picture would be stored in a file. My problem is every time I save my picture it overwrites the previous image captured. Thus leaving me with a single picture at the end instead of a stream of images. I have avoided using show file dialog as I want the picture to be stored automatically.

This code would cause the file A to be over written when the program goes into loop:

```<code>    Bmp.Save("C:\Users\pnasguna\Desktop\A.png", System.Drawing.Imaging.ImageFormat.Png)
</code>```

I would like to obtain a result like :
 A1.png,
 A2.png,
 A3.png,
 ...
 An.png

Please do guide me. Thanks
Attached below is my current code:

```<code>   If mati = 2 Then
   Bmp.Save("C:\Users\pnasguna\Desktop\A.png", System.Drawing.Imaging.ImageFormat.Png)
   ElseIf mati = 5 Then
   Bmp.Save("C:\Users\pnasguna\Desktop\A1.png", System.Drawing.Imaging.ImageFormat.Png)
   ElseIf mati = 8 Then
   Bmp.Save("C:\Users\pnasguna\Desktop\A2.png", System.Drawing.Imaging.ImageFormat.Png)
   ElseIf mati = 11 Then
   Bmp.Save("C:\Users\pnasguna\Desktop\A3.png", System.Drawing.Imaging.ImageFormat.Png)
   ElseIf mati = 14 Then
   Bmp.Save("C:\Users\pnasguna\Desktop\A4.png", System.Drawing.Imaging.ImageFormat.Png)
   ElseIf mati = 18 Then
   Bmp.Save("C:\Users\pnasguna\Desktop\A5.png", System.Drawing.Imaging.ImageFormat.Png)
</code>```

By the way mati is a timer. Is there a proper way for me to create a new file name rather this method?

答:
Picturebox save file in different names

Use following code on a button :

```<code>Static Count As Integer
Count +=1
PictureBox1.Image.Save(("c:\image" & Count.ToString &".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg)
</code>```

Output -- When u click this button then the picbox save the pic in different image names by following path. Thank u.

Body:
I would like to capture images from video screen shot and store them in a file. As the video plays multiple screen shots would we taken and all the picture would be stored in a file. My problem is every time I save my picture it overwrites the previous image captured. Thus leaving me with a single picture at the end instead of a stream of images. I have avoided using show file dialog as I want the picture to be stored automatically.

This code would cause the file A to be over written when the program goes into loop:

    Bmp.Save("C:\Users\pnasguna\Desktop\A.png", System.Drawing.Imaging.ImageFormat.Png)

I would like to obtain a result like :
 A1.png,
 A2.png,
 A3.png,
 ...
 An.png

Please do guide me. Thanks
Attached below is my current code:

   If mati = 2 Then
   Bmp.Save("C:\Users\pnasguna\Desktop\A.png", System.Drawing.Imaging.ImageFormat.Png)
   ElseIf mati = 5 Then
   Bmp.Save("C:\Users\pnasguna\Desktop\A1.png", System.Drawing.Imaging.ImageFormat.Png)
   ElseIf mati = 8 Then
   Bmp.Save("C:\Users\pnasguna\Desktop\A2.png", System.Drawing.Imaging.ImageFormat.Png)
   ElseIf mati = 11 Then
   Bmp.Save("C:\Users\pnasguna\Desktop\A3.png", System.Drawing.Imaging.ImageFormat.Png)
   ElseIf mati = 14 Then
   Bmp.Save("C:\Users\pnasguna\Desktop\A4.png", System.Drawing.Imaging.ImageFormat.Png)
   ElseIf mati = 18 Then
   Bmp.Save("C:\Users\pnasguna\Desktop\A5.png", System.Drawing.Imaging.ImageFormat.Png)

By the way mati is a timer. Is there a proper way for me to create a new file name rather this method?

Body:
Picturebox save file in different names

Use following code on a button :

Static Count As Integer
Count +=1
PictureBox1.Image.Save(("c:\image" & Count.ToString &".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg)

Output -- When u click this button then the picbox save the pic in different image names by following path. Thank u.


问:
Disable App Transport Security in Xcode 9.2?
I cannot disable App Transport Security (ATS) in Xcode 9.2. I have been (for years) disabling ATS when running builds against my local server environment like so:

Transport security has blocked a cleartext HTTP

```<code><key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
</code>```

In Xcode 9.2, a simple request (running against a local Rails app in http mode):

```<code>let session = URLSession(configuration: .default)
let url = URL(string: "http://store.dev/api/products.json")!

let task = session.dataTask(with: url) { data, response, error in
    print(data)
    print(response)
    print(error)
}

task.resume()
</code>```

fails with the error message

Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={_kCFStreamErrorCodeKey=-9802, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSUnderlyingError=0x60c00024afb0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://store.dev/api/products.json, NSErrorFailingURLStringKey=https://store.dev/api/products.json, _kCFStreamErrorDomainKey=3}

This exact same request (same project as well) succeeds on Xcode 9.1.

In both cases, I'm building against a iOS 11.1 deployment target. You can see that Xcode is changing the url from http to https, which I do not want.

Here is a link to the super basic project that works in Xcode 9.1 but fails in 9.2 (https://github.com/chrismanderson/ats-sample).

I've also tried disabling ATS just for the local store.dev domain, and again, it works on Xcode 9.1 but not 9.2.

答:
I didn't originally put it together, but I think what is happening is that with iOS 11, Apple is supporting HSTS.  I believe that support for HSTS preload lists, in combination with Google recently adding the .dev TLD to the HSTS preload list, is likely causing iOS to try to force you to use https, which is failing (I missed that you are trying to use a .dev local domain for testing, which is really the key element here).

I think your only solution is to change your local testing domain to something other than a .dev domain.  If you do that, you should be able to connect, and it won't try to force you to https on your local dev environment.

In short, Google has gotten rights to the .dev top level domain, and recently added it to the HSTS preload list to force all communication with .dev domains to be secure.  On devices that support HSTS preload lists, this causes all traffic to redirect through HTTPS, which will cause errors on servers that don't support HTTPS.

Body:
I cannot disable App Transport Security (ATS) in Xcode 9.2. I have been (for years) disabling ATS when running builds against my local server environment like so:

Transport security has blocked a cleartext HTTP

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

In Xcode 9.2, a simple request (running against a local Rails app in http mode):

let session = URLSession(configuration: .default)
let url = URL(string: "http://store.dev/api/products.json")!

let task = session.dataTask(with: url) { data, response, error in
    print(data)
    print(response)
    print(error)
}

task.resume()

fails with the error message

Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={_kCFStreamErrorCodeKey=-9802, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSUnderlyingError=0x60c00024afb0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://store.dev/api/products.json, NSErrorFailingURLStringKey=https://store.dev/api/products.json, _kCFStreamErrorDomainKey=3}

This exact same request (same project as well) succeeds on Xcode 9.1.

In both cases, I'm building against a iOS 11.1 deployment target. You can see that Xcode is changing the url from http to https, which I do not want.

Here is a link to the super basic project that works in Xcode 9.1 but fails in 9.2 (https://github.com/chrismanderson/ats-sample).

I've also tried disabling ATS just for the local store.dev domain, and again, it works on Xcode 9.1 but not 9.2.


问:
Convert ssh public keys from various formats to Open SSH with node-forge
I'd like to convert ssh public keys provided in various formats into the Open SSH format using node-forge.

I have no problem generating the keys and converting with:

```<code>forge.ssh.publicKeyToOpenSSH(key, comment);
</code>```

but cannot figure out how to read the files into node-forge, Tried:

```<code>pki.publicKeyFromPem(pem);
</code>```

or

```<code>pki.publicKeyFromAsn1(subjectPublicKeyInfo);
</code>```

答:
You can load OpenSSL public keys (PKCS#8) like this:

```<code>var forgePubKey = forge.pki.publicKeyFromPem('-----BEGIN PUBLIC KEY-----' + publicKey + '-----END PUBLIC KEY-----');
</code>```

where publicKey is BASE64 encoded

Body:
I'd like to convert ssh public keys provided in various formats into the Open SSH format using node-forge.

I have no problem generating the keys and converting with:

forge.ssh.publicKeyToOpenSSH(key, comment);

but cannot figure out how to read the files into node-forge, Tried:

pki.publicKeyFromPem(pem);

or

pki.publicKeyFromAsn1(subjectPublicKeyInfo);

Body:
You can load OpenSSL public keys (PKCS#8) like this:

var forgePubKey = forge.pki.publicKeyFromPem('-----BEGIN PUBLIC KEY-----' + publicKey + '-----END PUBLIC KEY-----');

where publicKey is BASE64 encoded


问:
MYSQL Table design help
I have  a table called teams (id, name, ...)   I have a table called divisions (id, name, ......)   I want the diviosn to hold the teams.id  for each team in a divsion  and Teams can be in more than one divsion.  How do I set this up?</p>

答:
You need to create a many-to-many junction table to join division and team tables.</p>

```<code>CREATE TABLE division (division_id INT NOT NULL,
                     PRIMARY KEY (division_id)
);

CREATE TABLE team (team_id INT NOT NULL,
                     PRIMARY KEY (team_id)
);

CREATE TABLE division_team (division_team_id INT,
                    PRIMARY KEY (division_team_id)
                    division_id INT,
                    team_id INT,
                    FOREIGN KEY (division_id) REFERENCES division(division_id),
                    FOREIGN KEY (team_id) REFERENCES team(team_id),
);
</code>```

Title: MYSQL Table design help

Body:
You need to create a many-to-many junction table to join division and team tables.

CREATE TABLE division (division_id INT NOT NULL,
                     PRIMARY KEY (division_id)
);

CREATE TABLE team (team_id INT NOT NULL,
                     PRIMARY KEY (team_id)
);

CREATE TABLE division_team (division_team_id INT,
                    PRIMARY KEY (division_team_id)
                    division_id INT,
                    team_id INT,
                    FOREIGN KEY (division_id) REFERENCES division(division_id),
                    FOREIGN KEY (team_id) REFERENCES team(team_id),
);


问:
Search filter in Angular2
I am new to Angular 2. I am trying out the search filter function using the Pipe. However, I am unable to actually search for an item. I have been watching videos on how to search with filter, but they proved to be futile. Would appreciate if any of you can help me out here.

HTML File:

    Welcome to {{title}}!

 <form id="filter">
Filter car by parts:
<input type="text" ng-Model="term"/>
</form>

 {{carPart.name | uppercase}}

 {{carPart.description}}

 5"> {{carPart.inStock}} in Stock

 Stock running low

 {{carPart.price | currency:'USD'}}

 Special Promotion Only

```
</div>
</div>
</p>

<p>Typescript File:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component } from '@angular/core';
import {FilterPipe} from './filter.pipe';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'List of Car Parts';

   carParts =  [ {
   "id": 1,
   "name": "Regular Tires",
   "description": "Tires for city use",
   "inStock": 10,
   "price": 200,

 },
 {
   "id": 2,
   "name": "Supreme Tires",
   "description": "Tires for all conditions",
   "inStock": 0,
   "price": 350,

 },
 {
   "id": 3,
   "name": "Premium Tires",
   "description": "Tires for all luxury models",
   "inStock": 8,
   "price": 400,

 } ];

}</code>```

filter.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(carParts: any, term: any): any {
    if (term === undefined) return carParts;

 return carParts.filter(function(carPart){
  return carPart.name.toLowerCase().includes(term.toLowerCase());
  })
  }
}```

答:
You are using ngModel incorrectly.

```<code><input type="text" [(ngModel)]="term"/>
</code>```

please check https://angular.io/api/forms/NgModel

Hope it helps!!

Title: Search filter in Angular2

Body:
I am new to Angular 2. I am trying out the search filter function using the Pipe. However, I am unable to actually search for an item. I have been watching videos on how to search with filter, but they proved to be futile. Would appreciate if any of you can help me out here.

HTML File:

    Welcome to {{title}}!

 <form id="filter">
Filter car by parts:
<input type="text" ng-Model="term"/>
</form>

 {{carPart.name | uppercase}}

 {{carPart.description}}

 5"> {{carPart.inStock}} in Stock

 Stock running low

 {{carPart.price | currency:'USD'}}

 Special Promotion Only

Typescript File:

import { Component } from '@angular/core';
import {FilterPipe} from './filter.pipe';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'List of Car Parts';

   carParts =  [ {
   "id": 1,
   "name": "Regular Tires",
   "description": "Tires for city use",
   "inStock": 10,
   "price": 200,

 },
 {
   "id": 2,
   "name": "Supreme Tires",
   "description": "Tires for all conditions",
   "inStock": 0,
   "price": 350,

 },
 {
   "id": 3,
   "name": "Premium Tires",
   "description": "Tires for all luxury models",
   "inStock": 8,
   "price": 400,

 } ];

}

filter.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(carParts: any, term: any): any {
    if (term === undefined) return carParts;

 return carParts.filter(function(carPart){
  return carPart.name.toLowerCase().includes(term.toLowerCase());
  })
  }
}

Body:
You are using ngModel incorrectly.

<input type="text" [(ngModel)]="term"/>

please check https://angular.io/api/forms/NgModel

Hope it helps!!


问:
CSS doesn't apply to dynamically created text field
I have created a dynamic text field for my form. Both the add and delete function works perfectly fine but when I applied CSS it won't work.
I'm a newbie in javascript and really appreciate if you could help me in figure it out. Here is the code:

var counter = 1;
  var limit = 3;

  function showTextBox() {
      var newdiv = document.createElement('div');
      //var add = 'add' + (counter - 1) ;
      console.log(newdiv);
      //console.log(counter);
      var tr = document.getElementById(newdiv);
      console.log(tr);
      newdiv.id = 'add' + counter;
      var sample = newdiv.id;
      //console.log(sample);
      //console.log(newdiv.id);
      newdiv.innerHTML = "Option  <input type='text' >";
      //document.getElementById("newdiv").setAttribute("style", "borderRadius: 10px; borderColor: #777; cursor: text; height: 20px;");
      //newdiv.style.setProperty('border-radius', '10px', 'border-color', '#777', 'cursor', 'text', 'height', '20px');
      newdiv.style.paddingBottom = "10px";
      document.getElementById("tbhold").appendChild(newdiv);
      counter++;
  }

  function hideTextBox() {
      var add = 'add' + (counter - 1);
      //console.log(counter);
      var tr = document.getElementById(add);
      console.log(tr);
      tr.parentNode.removeChild(tr);
      counter--;
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#option{
   font-size: 16px;
   text-align: center;
   top: 250px;
   padding-top: 50px;
  }
  #option > span{
   text-align: center;
   margin-left: 80px;
   top: 50px;
  }
  #tbhold > p > input{
   margin-left: 20px;
   border-radius: 10px;
   border-color: #777;
   cursor: text;
   height: 20px;
  }</code>```

    Name

Option  <input type="text" name="c_field" id="c_field">

     +  -

```

答:
Your Javascript wont work because you need to load first the div before applying styles on it. See the modified code below</p>

```<code>function showTextBox() {
    var newdiv = document.createElement('div');
    var add = 'add' + (counter - 1) ;
    //console.log(newdiv);
    //console.log(counter);
    var tr = document.getElementById(newdiv);
    console.log(tr);
    newdiv.id = 'add' + counter;
    var sample = newdiv.id;

    newdiv.innerHTML = "Option  <input type='text' >";

    newdiv.style.setProperty('border-radius', '10px', 'border-color', '#777', 'cursor', 'text', 'height', '20px');
    newdiv.style.paddingBottom = "10px";
    document.getElementById("tbhold").appendChild(newdiv);
    document.getElementById(sample).setAttribute("style", "borderRadius: 10px; borderColor: #777; cursor: text; height: 20px; font-size:50px;");
    counter++;
}
</code>```

Body:
I have created a dynamic text field for my form. Both the add and delete function works perfectly fine but when I applied CSS it won't work.
I'm a newbie in javascript and really appreciate if you could help me in figure it out. Here is the code:

var counter = 1;
  var limit = 3;

  function showTextBox() {
      var newdiv = document.createElement('div');
      //var add = 'add' + (counter - 1) ;
      console.log(newdiv);
      //console.log(counter);
      var tr = document.getElementById(newdiv);
      console.log(tr);
      newdiv.id = 'add' + counter;
      var sample = newdiv.id;
      //console.log(sample);
      //console.log(newdiv.id);
      newdiv.innerHTML = "Option  <input type='text' >";
      //document.getElementById("newdiv").setAttribute("style", "borderRadius: 10px; borderColor: #777; cursor: text; height: 20px;");
      //newdiv.style.setProperty('border-radius', '10px', 'border-color', '#777', 'cursor', 'text', 'height', '20px');
      newdiv.style.paddingBottom = "10px";
      document.getElementById("tbhold").appendChild(newdiv);
      counter++;
  }

  function hideTextBox() {
      var add = 'add' + (counter - 1);
      //console.log(counter);
      var tr = document.getElementById(add);
      console.log(tr);
      tr.parentNode.removeChild(tr);
      counter--;
  }

#option{
   font-size: 16px;
   text-align: center;
   top: 250px;
   padding-top: 50px;
  }
  #option > span{
   text-align: center;
   margin-left: 80px;
   top: 50px;
  }
  #tbhold > p > input{
   margin-left: 20px;
   border-radius: 10px;
   border-color: #777;
   cursor: text;
   height: 20px;
  }

    Name

Option  <input type="text" name="c_field" id="c_field">

     +  -

Body:
Your Javascript wont work because you need to load first the div before applying styles on it. See the modified code below

function showTextBox() {
    var newdiv = document.createElement('div');
    var add = 'add' + (counter - 1) ;
    //console.log(newdiv);
    //console.log(counter);
    var tr = document.getElementById(newdiv);
    console.log(tr);
    newdiv.id = 'add' + counter;
    var sample = newdiv.id;

    newdiv.innerHTML = "Option  <input type='text' >";

    newdiv.style.setProperty('border-radius', '10px', 'border-color', '#777', 'cursor', 'text', 'height', '20px');
    newdiv.style.paddingBottom = "10px";
    document.getElementById("tbhold").appendChild(newdiv);
    document.getElementById(sample).setAttribute("style", "borderRadius: 10px; borderColor: #777; cursor: text; height: 20px; font-size:50px;");
    counter++;
}


问:
Multiply list with binary
I am trying to create a powerset by multiplying binary counter with array to get

```<code>Value of Counter            Subset
    000                    -> Empty set
    001                    -> a
    010                    -> b
    011                    -> ab
    100                    -> c
    101                    -> ac
    110                    -> bc
    111                    -> abc
</code>```

My code:

```<code>A = ['a','b','c']
n = len(A)
for i in range(2**n):
    print format(i,'b') and A
</code>```

I get all the outputs as ['a','b','c'] . Is there a different way to do the print statement to get the required result.

答:
Try this

```<code>d = {0b1: 'a', 0b10: 'b', 0b100: 'c'}
for i in range(0b1000):
    s = ''
    for k, v in d.items():
        if i & k:
             s += v
    print s
</code>```

Edit: Some explination

So you're trying to associate 'a', 'b', 'c' to 1, 2 and 4 respectively. To do this I used the dictionary above (using binary literals for clarity).

Then, looping through all 0 <= i < 8, you can see if there is a 1 at the relevant position using the & operator.

e.g. is there a 1 at the second position from the right: 0b00 & 0b10 == 0b01 & 0b10 == 0 is false, whereas 0b10 & 0b10 == 0b11 & 0b10 != 0is true.

Title: Multiply list with binary

Body:
I am trying to create a powerset by multiplying binary counter with array to get

Value of Counter            Subset
    000                    -> Empty set
    001                    -> a
    010                    -> b
    011                    -> ab
    100                    -> c
    101                    -> ac
    110                    -> bc
    111                    -> abc

My code:

A = ['a','b','c']
n = len(A)
for i in range(2**n):
    print format(i,'b') and A

I get all the outputs as ['a','b','c'] . Is there a different way to do the print statement to get the required result.

Body:
Try this

d = {0b1: 'a', 0b10: 'b', 0b100: 'c'}
for i in range(0b1000):
    s = ''
    for k, v in d.items():
        if i & k:
             s += v
    print s

Edit: Some explination

So you're trying to associate 'a', 'b', 'c' to 1, 2 and 4 respectively. To do this I used the dictionary above (using binary literals for clarity).

Then, looping through all 0 <= i < 8, you can see if there is a 1 at the relevant position using the & operator.

e.g. is there a 1 at the second position from the right: 0b00 & 0b10 == 0b01 & 0b10 == 0 is false, whereas 0b10 & 0b10 == 0b11 & 0b10 != 0is true.


问:
Animation of a TextView's text size and not the entire TextView
Is there a way to animate only the TextView's text size without scaling the entire TextView's layout?

Am trying to achieve a similar effect, Note the text re-sizes to a single line while its size becomes smaller.

答:
As a follow up on @korrekorre answer: The documentation suggests to use the simpler ObjectAnimator API

```<code>final TextView tv = new TextView(getApplicationContext());

final float endSize = 12;
final int animationDuration = 600; // Animation duration in ms

ValueAnimator animator = ObjectAnimator.ofFloat(tv, "textSize", endSize);
animator.setDuration(animationDuration);

animator.start();
</code>```

There is just one caveat: The property you pass to the constructor ("textSize" in this case) must have a public setter method for this to work.

You can also pass a startSize to the constructor, if you don't then the interpolator will use the current size as starting point

Body:
As a follow up on @korrekorre answer: The documentation suggests to use the simpler ObjectAnimator API

final TextView tv = new TextView(getApplicationContext());

final float endSize = 12;
final int animationDuration = 600; // Animation duration in ms

ValueAnimator animator = ObjectAnimator.ofFloat(tv, "textSize", endSize);
animator.setDuration(animationDuration);

animator.start();

There is just one caveat: The property you pass to the constructor ("textSize" in this case) must have a public setter method for this to work.

You can also pass a startSize to the constructor, if you don't then the interpolator will use the current size as starting point


问:
Compilation fails in VS2010 for C++ programs building fine in Linux
My C++ project builds and runs fine on Linux. Now I am trying to compile it in VS2010. I get many errors seemingly from cmath library like the following one.

```<code>Error   1   error C2061: syntax error : identifier 'acosf'  c:\program files\microsoft visual studio 10.0\vc\include\cmath  19  1   MyPROJ
</code>```

Also I get many file operations related compilation errors like:

```<code>Error   1   error C3861: 'lseek': identifier not found  g:\project\file.cc  274 1   MyPROJ

Error   2   error C3861: 'write': identifier not found  g:\project\file.cc  275 1   MyPROJ
</code>```

How to eliminate these errors.

答:
lseek and write are unix (posix?) calls that are not part of the C standard.
They are available on windows but using the names _lseek and _write

not sure about acosf though

EDIT: acosf should be available, are you include math.h

Edit more: Looking more closely at the original post the error is in cmath which is fine although then you probably have to write std::acosf - but the error is in the include file. It works fine when I try it so something before the include is likely conflicting. What is before the include of cmath in your source?

Body:
My C++ project builds and runs fine on Linux. Now I am trying to compile it in VS2010. I get many errors seemingly from cmath library like the following one.

Error   1   error C2061: syntax error : identifier 'acosf'  c:\program files\microsoft visual studio 10.0\vc\include\cmath  19  1   MyPROJ

Also I get many file operations related compilation errors like:

Error   1   error C3861: 'lseek': identifier not found  g:\project\file.cc  274 1   MyPROJ

Error   2   error C3861: 'write': identifier not found  g:\project\file.cc  275 1   MyPROJ

How to eliminate these errors.