问:
Jooq 3.9.3 deletes custom generated java files after generate
This is an issue we face with migration from jooq version 3.4.1 to 3.9.3.

We have a setup in which we extend JavaGenerator and override generatePojo(TableDefinition tableDefinition) to create some custom enum from data in database. This enum is created in a bit hackish way, using PrintWriterand writing the data into FooEnum.java file.

Something like this:

```<code>public class FooGenerator extends JavaGenerator {

    @Override
    protected void generatePojo(TableDefinition table) {
    super.generatePojo(table);
    // this works in jooq 3.4.1 but not in 3.9.3
    generateEnumClasses(table); // loads data and produces FooEnum.java with PrintWriter

    }
}
</code>```

What happens is that the FooEnum.java gets generated and then deleted shortly afterwards. Funny enough, if i create Foo.txt file in the directory where enum should be created, this file survives clean install.

It seems that the enum is deleted after first (of two) generate goals:

```<code>jooq-codegen-maven:3.9.3:generate
</code>```

Any ideas why is the enum getting deleted and how to keep the behavior from version 3.4.1 where it survives ?

This custom generator that we use to extend JavaGenerator is supplied to plugin with:

```<code><groupId>org.jooq</groupId>
<artifactId>jooq-codegen-maven</artifactId>
<executions>
    <execution>
        <goals>
            <goal>generate</goal>
        </goals>
        <id>some id</id>
        <configuration>
            <generator>
                <name>org.jooq.util.FooGenerator</name>
             // ...
            </generator>
        </configuration>
    </execution>
</executions>
</code>```

答:
In case anybody else stumbles upon this, it seems that in newer jooq versions there is some cleanup code in

```<code>JavaGenerator {

    public final void generate(Database db) {
    // .... this deletes 'excess' java files
    log.info("Removing excess files");
    this.empty(this.getStrategy().getFileRoot(),this.scala?".scala":".java", this.files, this.directoriesNotForRemoval);
    this.directoriesNotForRemoval.clear();
    this.files.clear();
    }
}
</code>```

which deletes excess .java files.

Edit

Here is a link to github issue regarding this feature from Lukas comment.

Body:
This is an issue we face with migration from jooq version 3.4.1 to 3.9.3.

We have a setup in which we extend JavaGenerator and override generatePojo(TableDefinition tableDefinition) to create some custom enum from data in database. This enum is created in a bit hackish way, using PrintWriterand writing the data into FooEnum.java file.

Something like this:

public class FooGenerator extends JavaGenerator {

    @Override
    protected void generatePojo(TableDefinition table) {
    super.generatePojo(table);
    // this works in jooq 3.4.1 but not in 3.9.3
    generateEnumClasses(table); // loads data and produces FooEnum.java with PrintWriter

    }
}

What happens is that the FooEnum.java gets generated and then deleted shortly afterwards. Funny enough, if i create Foo.txt file in the directory where enum should be created, this file survives clean install.

It seems that the enum is deleted after first (of two) generate goals:

jooq-codegen-maven:3.9.3:generate

Any ideas why is the enum getting deleted and how to keep the behavior from version 3.4.1 where it survives ?

This custom generator that we use to extend JavaGenerator is supplied to plugin with:

<groupId>org.jooq</groupId>
<artifactId>jooq-codegen-maven</artifactId>
<executions>
    <execution>
        <goals>
            <goal>generate</goal>
        </goals>
        <id>some id</id>
        <configuration>
            <generator>
                <name>org.jooq.util.FooGenerator</name>
             // ...
            </generator>
        </configuration>
    </execution>
</executions>

Body:
In case anybody else stumbles upon this, it seems that in newer jooq versions there is some cleanup code in

JavaGenerator {

    public final void generate(Database db) {
    // .... this deletes 'excess' java files
    log.info("Removing excess files");
    this.empty(this.getStrategy().getFileRoot(),this.scala?".scala":".java", this.files, this.directoriesNotForRemoval);
    this.directoriesNotForRemoval.clear();
    this.files.clear();
    }
}

which deletes excess .java files.

Edit

Here is a link to github issue regarding this feature from Lukas comment.


来源: stackexchange

问:
Reactjs, typescript unable to set initial state inside component
I'm very new to React. I have a component that renders fine, when I try to initialise the state, it says It cannot find the name, as I have not declared it yet, so how do I initialise it properly? I'm using:

"react": "^15.5.4",
      "react-dom": "^15.5.4",

The component errors here on the line below:

```<code>export class Profile extends React.Component<{}, state> {

constructor(props){
    super(props);
    this.state = [{name: 'baz'}, {name: 'shaz'}];
}

public render() {
    return (
        <section>
         <section>
             <h3>profile 1</h3>
             <div>baz</div>
         </section>
            <section>
                <h3>profile 2</h3>
                <div>shaz</div>
            </section>
        </section>
        )

}

 ReactDOM.render(
   >> this is where I call <Profile />,
    document.getElementById('app'),
)
</code>```

Edit

So I managed to solve the issue with everyones help:

```<code>interface State {
    name: string;
}

export class Profile extends React.Component<{}, State> {
    public state: State;

    constructor(props){
        super(props);
            this.state = {
               name: 'baz111'
            };
    }

    public render() {
        return (
            <section>
             <section>
                 <h3>profile 1</h3>
                 <div>baz</div>
             </section>
                <section>
                    <h3>profile 2</h3>
                    <div>{this.state.name}</div>
                </section>
            </section>
        )

    }
}
</code>```

答:
As people said already, this.state has to be an object.

I think the real problem is when you initialize your component.

```<code>export class Profile extends React.Component<{}, state>
</code>```

You see that state? That's the default state! As you didn't declare it, that's undefined. Please remove it or set it as void. Or, you can define it outside of your component:

1 - First alternative

```<code>export class Profile extends React.Component<{}, void> {
   constructor(props) {
    super(props)
    this.state = {
      users: [/* what you need */]
    }
  }
}
</code>```

2 - Second alternative

```<code>type state {
    {
      users: [/* what you need */]
    }
}

export class Profile extends React.Component<{}, state> {
   constructor(props) {
    super(props)
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm very new to React. I have a component that renders fine, when I try to initialise the state, it says It cannot find the name, as I have not declared it yet, so how do I initialise it properly? I'm using:

"react": "^15.5.4",
      "react-dom": "^15.5.4",

The component errors here on the line below:

export class Profile extends React.Component<{}, state> {

constructor(props){
    super(props);
    this.state = [{name: 'baz'}, {name: 'shaz'}];
}

public render() {
    return (

profile 1

baz

profile 2

shaz

        )

}

 ReactDOM.render(
   >> this is where I call <Profile />,
    document.getElementById('app'),
)

Edit

So I managed to solve the issue with everyones help:

interface State {
    name: string;
}

export class Profile extends React.Component<{}, State> {
    public state: State;

    constructor(props){
        super(props);
            this.state = {
               name: 'baz111'
            };
    }

    public render() {
        return (

profile 1

baz

profile 2

{this.state.name}

        )

    }
}

Body:
As people said already, this.state has to be an object.

I think the real problem is when you initialize your component.

export class Profile extends React.Component<{}, state>

You see that state? That's the default state! As you didn't declare it, that's undefined. Please remove it or set it as void. Or, you can define it outside of your component:

1 - First alternative

export class Profile extends React.Component<{}, void> {
   constructor(props) {
    super(props)
    this.state = {
      users: [/* what you need */]
    }
  }
}

2 - Second alternative

type state {
    {
      users: [/* what you need */]
    }
}

export class Profile extends React.Component<{}, state> {
   constructor(props) {
    super(props)
  }
}


问:
Keep folder and tables in sync while backing upp live Laravel app
I need to back up back up my live Laravel app daily, and also the content of a specific folder where the user's uploaded pictures are stored.

I've searched around and understood that it's possible to do this with various Laravel packages, but is there any way to make sure that the database/folder is not altered by users during the backup process?

I want to avoid scenarios like these:

Table D is altered but first
after table A is backed up, messing up the relation between them. So
when the DB backup is complete there could be a different amount of
rows in table A and table D, even though they need to have the same
amount of rows.

A user has 10 picture in his folder and during the backup process he
deletes one picture. The deletion is made after the table keeping track of user images is backed up, but before the users' picture folder is backed up. So
when the backup is done the database will state that the user has 10
images, but there will only be 9 images backed up.

I find it a bit hard to explain but I hope you understand.

Maybe setting up a cronjob would do?

Would it then be possible to set the app in maintenance mode, and only remove that mode once the backup is 100% complete?

If possible I would prefer to do the backing up without having to set up a maintenance mode though.

I'm using mysql and Laravel 5.3 on Digital Ocean, and have Laravel forge, if it's of any relevance.

I would be very grateful for any suggestions, thanks! :)

答:
If you're using Digital Ocean the answer is simple: a Live Snapshot of your server. Works like a charm, 0 downtime, and very easy to revert to should something happen :-)

Mind you this only works if you have the DB hosted on your webserver!


问:
Merging mulit-valued dictionaries
Lets say I have two dictionaries with multiple values per key:

```<code>Dict1 = { key1 : [value1,value2] }
Dict2 = { key1 : [value3,value4], key2 : [value5,value6]}
</code>```

I want to merge them into one dictionary like this:

```<code>mergedDict = { key 1 : [value1,value2,value3,value4], key 2 : [0,0,value5,value6] }
</code>```

答:
Loop over the union of the keys and use dict.get with the default value [0, 0].

```<code>>>> dict1 = {'key1' : [1, 2]}
>>> dict2 = {'key1' : [3, 4], 'key2' : [5, 6]}
>>>
>>> {k:dict1.get(k, [0, 0]) + dict2.get(k, [0, 0]) for k in dict1.viewkeys() | dict2.viewkeys()}
{'key2': [0, 0, 5, 6], 'key1': [1, 2, 3, 4]}
</code>```

Title: Merging mulit-valued dictionaries

Body:
Lets say I have two dictionaries with multiple values per key:

Dict1 = { key1 : [value1,value2] }
Dict2 = { key1 : [value3,value4], key2 : [value5,value6]}

I want to merge them into one dictionary like this:

mergedDict = { key 1 : [value1,value2,value3,value4], key 2 : [0,0,value5,value6] }

Body:
Loop over the union of the keys and use dict.get with the default value [0, 0].

>>> dict1 = {'key1' : [1, 2]}
>>> dict2 = {'key1' : [3, 4], 'key2' : [5, 6]}
>>>
>>> {k:dict1.get(k, [0, 0]) + dict2.get(k, [0, 0]) for k in dict1.viewkeys() | dict2.viewkeys()}
{'key2': [0, 0, 5, 6], 'key1': [1, 2, 3, 4]}


问:
Why the restrictions on protocols with Self or associatedtype?
While designing APIs, I run into this at every corner:

Protocol can only be used as a generic constraint because it has Self or associatedType requirements

What that means is that you basically can not use Self or associatedtype on protocol level if you ever plan to use the protocol type on its own -- otherwise the need for types to be generic themselves cascades out of control.

This is rather annoying (read: makes it next to impossible to design reasonable APIs, e.g. such that expose protocols but hide implementations). For instance, you can not have a simple data container protocol:

```<code>protocol DataContainer: Equatable {
    var id: Int { get }
    var content: Data { get }
}
</code>```

The issue is that Equatable requires static function == which is, of course, expressed using Self. Therefore, you can not have a type like [DataContainer], or any number of other natural things. I first ran into it with groups (arrays) of users (which could be of one of three different types).

The "official" recommended "solution" is to have delegating/wrapper structs that eliminate the type variable, like AnyDataContainer. This feels like a rather silly, hacky workaround, not proper API design.

I honestly don't get why the type system has this restriction. What are the reason? Why can't the compiler implicitly create AnyP for every protocol P to work around it?

答:
Here is one reason I can think of, which actually does not need an arcane setup either. Building on the example from the question, say we could have code like this:

```<code>func contained(element: DataContainer, in list: [DataContainer]) -> Bool {
    for elem in list {
        if elem == element {
            return true
        }
    }
    return false
}
</code>```

The Swift compiler wants to statically dispatch ==; but it can't! There is no single implementation it can pick up; every array element may have its own type and therewith implementation of ==, and element may have a completely different one. The compiler therefore forbids the code at hand.

Two additional thoughts.

I'd argue that the compiler to too defensive. The following code could be compiled easily, for instance:

```<code>func contained(id: Int, in list: [DataContainer]) -> Bool {
    for elem in list {
        if elem.id == id {
            return true
        }
    }
    return false
}
</code>```

Here, we don't need to know the exact types of the array elements; the promise that they each have an Int property id is enough!

So it could allow the use of types like [DataContainer] as long as all accessed properties can be resolved statically.

The compiler could allow Self references if there is no ambiguity where to dispatch and/or generic implementations exist. For instance (pseudo code):

```<code>extension DataContainer {
    static func ==<T: DataCointainer, U: DataContainer>(lhs: T, rhs:U) -> Bool {
        guard T == U else {
            return false
        }

        return T.==(lhs, rhs as! T)
    }
}
</code>```

Such a default implementation could be used in usage contexts as the one above, i.e. if not enough type information is available to select an implementation statically.

I don't know if all problems with generic protocols can be done away with similar ideas, and if we would run into further restrictions along the road.

Body:
While designing APIs, I run into this at every corner:

Protocol can only be used as a generic constraint because it has Self or associatedType requirements

What that means is that you basically can not use Self or associatedtype on protocol level if you ever plan to use the protocol type on its own -- otherwise the need for types to be generic themselves cascades out of control.

This is rather annoying (read: makes it next to impossible to design reasonable APIs, e.g. such that expose protocols but hide implementations). For instance, you can not have a simple data container protocol:

protocol DataContainer: Equatable {
    var id: Int { get }
    var content: Data { get }
}

The issue is that Equatable requires static function == which is, of course, expressed using Self. Therefore, you can not have a type like [DataContainer], or any number of other natural things. I first ran into it with groups (arrays) of users (which could be of one of three different types).

The "official" recommended "solution" is to have delegating/wrapper structs that eliminate the type variable, like AnyDataContainer. This feels like a rather silly, hacky workaround, not proper API design.

I honestly don't get why the type system has this restriction. What are the reason? Why can't the compiler implicitly create AnyP for every protocol P to work around it?

Body:
Here is one reason I can think of, which actually does not need an arcane setup either. Building on the example from the question, say we could have code like this:

func contained(element: DataContainer, in list: [DataContainer]) -> Bool {
    for elem in list {
        if elem == element {
            return true
        }
    }
    return false
}

The Swift compiler wants to statically dispatch ==; but it can't! There is no single implementation it can pick up; every array element may have its own type and therewith implementation of ==, and element may have a completely different one. The compiler therefore forbids the code at hand.

Two additional thoughts.

I'd argue that the compiler to too defensive. The following code could be compiled easily, for instance:

func contained(id: Int, in list: [DataContainer]) -> Bool {
    for elem in list {
        if elem.id == id {
            return true
        }
    }
    return false
}

Here, we don't need to know the exact types of the array elements; the promise that they each have an Int property id is enough!

So it could allow the use of types like [DataContainer] as long as all accessed properties can be resolved statically.

The compiler could allow Self references if there is no ambiguity where to dispatch and/or generic implementations exist. For instance (pseudo code):

extension DataContainer {
    static func ==<T: DataCointainer, U: DataContainer>(lhs: T, rhs:U) -> Bool {
        guard T == U else {
            return false
        }

        return T.==(lhs, rhs as! T)
    }
}

Such a default implementation could be used in usage contexts as the one above, i.e. if not enough type information is available to select an implementation statically.

I don't know if all problems with generic protocols can be done away with similar ideas, and if we would run into further restrictions along the road.


问:
Error "please fix the version conflict either by updating the version of the google services plugin''a
Error:Execution failed for task ':app:processDebugGoogleServices'.
Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 10.2.6.

According to me build.gradle versions are okay

build.gradle(module:app)

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.1'
    defaultConfig {
        applicationId "com.example.deepdepindersingh.mutual"
        minSdkVersion 19
        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'
        }
    }

    buildTypes.each {
        it.buildConfigField 'String', 'UNIQUE_FIREBASE_ROOT_URL', UniqueFirebaseRootUrl
    }

    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'
    }

}

configurations.all {
    resolutionStrategy {
        force 'com.google.code.findbugs:jsr305:1.3.9'
    }
}
configurations {
    compile.exclude group: "org.apache.httpcomponents", module: "httpclient"
}

dependencies {

    compile 'com.google.firebase:firebase-core:10.2.6'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    //compile 'com.android.support:appcompat-v7:24.2.1'

    //compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.firebase:firebase-client-android:2.5.2'
    compile 'com.google.firebase:firebase-auth:9.6.1'
    compile 'com.google.firebase:firebase-core:9.6.1'
    compile 'com.firebaseui:firebase-ui:0.5.3'
    //compile 'com.google.android.gms:play-services-maps:10.2.6'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'

    /* For Google Play Services */
    //compile 'com.google.gms:google-services:3.1.0'
    //compile 'com.google.android.gms:play-services-safetynet:10.2.6'
   // compile 'com.google.android.gms:play-services-auth:10.2.6'
    testCompile 'junit:junit:4.12'

}

apply plugin: 'com.google.gms.google-services'
</code>```

build.gradle(project)

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath 'com.google.gms:google-services:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答:
You are using 10.2.6 for firebase in your dependencies
 compile 'com.google.firebase:firebase-core:10.2.6'

and 9.6.1 for the rest
compile 'com.google.firebase:firebase-auth:9.6.1'
compile 'com.google.firebase:firebase-core:9.6.1'

You have to always use the same versions for google related stuff.
Change firebase auth and core also to 10.2.6

Body:
Error:Execution failed for task ':app:processDebugGoogleServices'.
Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 10.2.6.

According to me build.gradle versions are okay

build.gradle(module:app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.1'
    defaultConfig {
        applicationId "com.example.deepdepindersingh.mutual"
        minSdkVersion 19
        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'
        }
    }

    buildTypes.each {
        it.buildConfigField 'String', 'UNIQUE_FIREBASE_ROOT_URL', UniqueFirebaseRootUrl
    }

    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'
    }

}

configurations.all {
    resolutionStrategy {
        force 'com.google.code.findbugs:jsr305:1.3.9'
    }
}
configurations {
    compile.exclude group: "org.apache.httpcomponents", module: "httpclient"
}

dependencies {

    compile 'com.google.firebase:firebase-core:10.2.6'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    //compile 'com.android.support:appcompat-v7:24.2.1'

    //compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.firebase:firebase-client-android:2.5.2'
    compile 'com.google.firebase:firebase-auth:9.6.1'
    compile 'com.google.firebase:firebase-core:9.6.1'
    compile 'com.firebaseui:firebase-ui:0.5.3'
    //compile 'com.google.android.gms:play-services-maps:10.2.6'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'

    /* For Google Play Services */
    //compile 'com.google.gms:google-services:3.1.0'
    //compile 'com.google.android.gms:play-services-safetynet:10.2.6'
   // compile 'com.google.android.gms:play-services-auth:10.2.6'
    testCompile 'junit:junit:4.12'

}

apply plugin: 'com.google.gms.google-services'

build.gradle(project)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath 'com.google.gms:google-services:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


问:
PowerMockito execption for doNothing for a private method
I have a class which has two private methods I am writing JUnit for one method test() and want the other method test1 to do nothing. It's like this..the method I want to call is test() and i want when it is called the test1() which is called it does nothing as

```<code>class foo{

private void test1() {

//some code;
}

private int test( Element e){

test1(element e);

return 0;
}
}
</code>```

my test class is like this...

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest(Foo.class)

public class FooTest {

private Foo foo= new Foo;

public void testTest() {

element e;

Foo testOb= PowerMockito.spy(foo);

PowerMockito.doNothing().when(testOb, "test1", Matchers.any(Element.class));

 PowerMockito.doCallRealMethod().when(testOb, "test", e);

}
</code>```

Now the problem i am facing that it is showing an exception

```<code>org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java)
E.g. thenReturn() may be missing.

Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();

now if i remove the "PowerMockito.doNothing().when(testOb, "test1", Matchers.any(Element.class));" line then it works fine but adding this produces the exception can anyone please help me..
</code>```

答:
The implementation of doNothing is wrong.

Mockito.doNothing().when(mockedObject).Method();

Body:
I have a class which has two private methods I am writing JUnit for one method test() and want the other method test1 to do nothing. It's like this..the method I want to call is test() and i want when it is called the test1() which is called it does nothing as

class foo{

private void test1() {

//some code;
}

private int test( Element e){

test1(element e);

return 0;
}
}

my test class is like this...

@RunWith(PowerMockRunner.class)
@PrepareForTest(Foo.class)

public class FooTest {

private Foo foo= new Foo;

public void testTest() {

element e;

Foo testOb= PowerMockito.spy(foo);

PowerMockito.doNothing().when(testOb, "test1", Matchers.any(Element.class));

 PowerMockito.doCallRealMethod().when(testOb, "test", e);

}

Now the problem i am facing that it is showing an exception

org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java)
E.g. thenReturn() may be missing.

Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();

now if i remove the "PowerMockito.doNothing().when(testOb, "test1", Matchers.any(Element.class));" line then it works fine but adding this produces the exception can anyone please help me..


问:
How can I disable migrations like that never enabled
I need to disable migrations on my code first project. I just runenable-migrations command. But now I need to disable migrations on my project. I need another changes to my project and after these I will enable migrations because now I got errors on my project.

答: It's quite easy. Just delete the Migrations folder. Be advised that this is not the same as dropping the existing database and creating a new one.</p>


问:
Alert function not working in coffeescript
I found about CoffeeScript in a blog and decided to give it a try ,my first project/code with it was this

```<code>alert "Hello CoffeeScript!"
</code>```

It doesn't work and gives this reply

```<code>ReferenceError: alert is not defined
</code>```

is there anything i am doing wrong?

答:
JavaScript is a language which is strongly tied to the concept of environments. A browser and Node.js are two possible environments to run JS code (CoffeeScript compiles to JavaScript).

When JavaScript is embedded in a browser, the global object is window. But in Node.js, the global object is simply global.

Some methods are available in both environments, like core JavaScript methods...

String.prototype methods

Array.prototype methods

Object.prototype methods

etc.

... and specific window methods like setInterval or setTimeout.

However, window.alert is obviously not available in CLI. If you want this functionality in Node, you will have to use something like alert-node ---> npm i alert-node.

JavaScript

```<code>// alert.js
var alert = require('alert-node');
alert('Hello');
</code>```

Command: node alert.js

CoffeeScript

```<code># alert.coffee
alert = require 'alert-node'
alert 'Hello'
</code>```

Command: coffee alert.coffee

Body:
I found about CoffeeScript in a blog and decided to give it a try ,my first project/code with it was this

alert "Hello CoffeeScript!"

It doesn't work and gives this reply

ReferenceError: alert is not defined

is there anything i am doing wrong?

Body:
JavaScript is a language which is strongly tied to the concept of environments. A browser and Node.js are two possible environments to run JS code (CoffeeScript compiles to JavaScript).

When JavaScript is embedded in a browser, the global object is window. But in Node.js, the global object is simply global.

Some methods are available in both environments, like core JavaScript methods...

String.prototype methods

Array.prototype methods

Object.prototype methods

etc.

... and specific window methods like setInterval or setTimeout.

However, window.alert is obviously not available in CLI. If you want this functionality in Node, you will have to use something like alert-node ---> npm i alert-node.

JavaScript

// alert.js
var alert = require('alert-node');
alert('Hello');

Command: node alert.js

CoffeeScript

# alert.coffee
alert = require 'alert-node'
alert 'Hello'

Command: coffee alert.coffee


问:
Script error when webbrowser loading html page
I'm trying to load local html page using webbrowser tool in Winforms but I got script error message and my page won't load, when I open that page using any web browser it opens with no problem at all! I tried some solutions as editing registry but no fix.

my html page has jscript code and this is the code in my page:

```<code><html>
<head>
<script type="text/javascript"src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script type="text/javascript"src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js?cacheBust=56"></script>
<script type="text/javascript">
FusionCharts.ready(function () {
var csatGauge = new FusionCharts({
    "type": "angulargauge",
    "renderAt": "chart-container",
    "width": "400",
    "height": "250",
    "dataFormat": "json",
        "dataSource": {
               "chart": {
                  "caption": "Customer Satisfaction Score",
                  "subcaption": "Last week",
                  "lowerLimit": "0",
                  "upperLimit": "100",
                  "theme": "fint"
               },
               "colorRange": {
                  "color": [
                     {
                        "minValue": "0",
                        "maxValue": "50",
                        "code": "#e44a00"
                     },
                     {
                        "minValue": "50",
                        "maxValue": "75",
                        "code": "#f8bd19"
                     },
                     {
                        "minValue": "75",
                        "maxValue": "100",
                        "code": "#6baa01"
                     }
                  ]
               },
               "dials": {
                  "dial": [
                     {
                        "value": "67"
                     }
                  ]
               }
        }
  });

csatGauge.render();
});
</script>
</head>
<body>
<div id="chart-container">An angular guage will load here!</div>
</body>
</html>
</code>```

答:
I've managed to solve it by adding this code:

```<code><head>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
</head>
</code>```

I'm still not sure if this is only thing needed or it worked with the change of the registry: solution

Body:
I'm trying to load local html page using webbrowser tool in Winforms but I got script error message and my page won't load, when I open that page using any web browser it opens with no problem at all! I tried some solutions as editing registry but no fix.

my html page has jscript code and this is the code in my page:

An angular guage will load here!

Body:
I've managed to solve it by adding this code:

<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
</head>

I'm still not sure if this is only thing needed or it worked with the change of the registry: solution


答:
Try this

Database.SetInitializer(new CreateDatabaseIfNotExists());

Title: How can I disable migrations like that never enabled

Body: I need to disable migrations on my code first project. I just runenable-migrations command. But now I need to disable migrations on my project. I need another changes to my project and after these I will enable migrations because now I got errors on my project.


问:
Uploading file with the uri starting with content://
I am reading a file from android and uploading it to a remote server.I am getting the file in the form of

```<code>content://com.android.providers.downloads.documents/document/3
</code>```

Since i am using react-native, can the uri above used as a file path?.

I can get the exact file path but when the file picker gets the file and the file has spaces, the picker cannot read the file but the uri takes into account spaces.

What can be done to use content://com.android.providers.downloads.documents/document/3 as the file path?.

答:
If i understand what you want , its something like this</p>

```<code>var x = "content://com.android.providers.downloads.documents/document/3"
const file = {
  uri:  x,
  name: "nameFile",
}

const formdata = new FormData();
formdata.append('Files', file);

fetch('URL', {
   ...
</code>```

Body:
I am reading a file from android and uploading it to a remote server.I am getting the file in the form of

content://com.android.providers.downloads.documents/document/3

Since i am using react-native, can the uri above used as a file path?.

I can get the exact file path but when the file picker gets the file and the file has spaces, the picker cannot read the file but the uri takes into account spaces.

What can be done to use content://com.android.providers.downloads.documents/document/3 as the file path?.

Body:
If i understand what you want , its something like this

var x = "content://com.android.providers.downloads.documents/document/3"
const file = {
  uri:  x,
  name: "nameFile",
}

const formdata = new FormData();
formdata.append('Files', file);

fetch('URL', {
   ...


问:
Correlation matrix for subset of columns from a multiple imputation dataset
I am using the mice package in R to do multiple imputations of a dataset with a large amount of missingness.  There are variables in the raw dataset that are important for the imputation process, and for later analyses.  However, I want to create a correlation matrix using cor() without including some of the variables.  Normally, for a simple dataset x, cor(x[,3:7]) would yield the correlation matrix for columns 3 through 7.  If x is a mids object created by the mice function, one would normally use with to perform a repeated analysis to create a mira object, and then use pool to create a mipo pooled outcomes object.  However, the second element of with is supposed to be a formula that references the columns of the dataset, and that is not the kind of input that goes into cor().  If x is a mids object, cor(x[,3:7]) does not work, and neither does with(x, cor(x[,3:7])).

How can I created a pooled correlation matrix for a subset of the variables from a multiple imputation data set?

```<code>#reproducible example
x = data.frame(matrix(rnorm(100),10,10))  #create random data
x[9:10,] = NA #add missingness
x.mice = mice(x)  #make imputed data set
cor(x.mice[,3:7]) #doesn't work
with(x.mice, cor(x.mice[,3:7])) #doesn't work
with(x.mice[,3:7], cor()) #doesn't work
</code>```

答:
I've had the same problem. The newly added package "miceadds" adds very useful functionality to the mice package.

Specifically, for your problem, look up the function micombine.cor which does inference for correlations and covariances for multiply imputed
datasets.

Eg:

```<code>library(missForest)
library(mice)
library(miceadds)

#Get the data
data <- iris

#introduce missings
iris.mis <- prodNA(iris, noNA = 0.1)

#imputedata
imputed     <-mice(iris.mis, m = 5, maxit = 5, method = "pmm")

#correlations for the first three variables (package miceadds)
correlations<- miceadds::micombine.cor(mi.res=iris.mis, variables = c(1:3))

#and because i am a psychologist and don't like scientific coding...
old_school<-format(correlations$p, scientific=FALSE)
correlations["p_value"] <- NA; correlations$p_value <- old_school;
correlations
</code>```

Body:
I am using the mice package in R to do multiple imputations of a dataset with a large amount of missingness.  There are variables in the raw dataset that are important for the imputation process, and for later analyses.  However, I want to create a correlation matrix using cor() without including some of the variables.  Normally, for a simple dataset x, cor(x[,3:7]) would yield the correlation matrix for columns 3 through 7.  If x is a mids object created by the mice function, one would normally use with to perform a repeated analysis to create a mira object, and then use pool to create a mipo pooled outcomes object.  However, the second element of with is supposed to be a formula that references the columns of the dataset, and that is not the kind of input that goes into cor().  If x is a mids object, cor(x[,3:7]) does not work, and neither does with(x, cor(x[,3:7])).

How can I created a pooled correlation matrix for a subset of the variables from a multiple imputation data set?

#reproducible example
x = data.frame(matrix(rnorm(100),10,10))  #create random data
x[9:10,] = NA #add missingness
x.mice = mice(x)  #make imputed data set
cor(x.mice[,3:7]) #doesn't work
with(x.mice, cor(x.mice[,3:7])) #doesn't work
with(x.mice[,3:7], cor()) #doesn't work

Body:
I've had the same problem. The newly added package "miceadds" adds very useful functionality to the mice package.

Specifically, for your problem, look up the function micombine.cor which does inference for correlations and covariances for multiply imputed
datasets.

Eg:

library(missForest)
library(mice)
library(miceadds)

#Get the data
data <- iris

#introduce missings
iris.mis <- prodNA(iris, noNA = 0.1)

#imputedata
imputed     <-mice(iris.mis, m = 5, maxit = 5, method = "pmm")

#correlations for the first three variables (package miceadds)
correlations<- miceadds::micombine.cor(mi.res=iris.mis, variables = c(1:3))

#and because i am a psychologist and don't like scientific coding...
old_school<-format(correlations$p, scientific=FALSE)
correlations["p_value"] <- NA; correlations$p_value <- old_school;
correlations


问:
DC/OS JMX Access
I have a dc/os cluster deployed to azure. I have deployed to the cluster a container with my java application. But I can't access it via jmx.

Let's take the example of deploying a standart tomcat image:

1) I opened a port 8081 according the next instruction: https://learn.microsoft.com/en-us/azure/container-service/container-service-enable-public-access#open-a-port-portal.

2) I deployed service using the next json:

```<code>{
  "id": "/tomcat",
  "instances": 1,
  "cpus": 1,
  "mem": 512,
  "container": {
    "type": "DOCKER",
    "docker": {
      "image": "tomcat:8.0",
      "network": "BRIDGE",
      "portMappings": [
        { "protocol": "tcp", "hostPort": 8080   , "containerPort": 8080 },
        { "protocol": "tcp", "hostPort": 8081   , "containerPort": 8081 }
      ]
    }
  },
  "requirePorts": true,
  "acceptedResourceRoles": [
    "slave_public"
  ],
  "env": {
    "JAVA_OPTS": "-Dcom.sun.management.jmxremote -Djava.rmi.server.hostname=10.0.0.4 -Dcom.sun.management.jmxremote.port=8081 -Dcom.sun.management.jmxremote.rmi.port=8081 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
  },
  "healthChecks": [
    {
      "gracePeriodSeconds": 120,
      "intervalSeconds": 30,
      "maxConsecutiveFailures": 3,
      "path": "/",
      "portIndex": 0,
      "protocol": "HTTP",
      "timeoutSeconds": 5
    }
  ]
}
</code>```

To connect I use Oracle Java Mission Control. I fill fields 'Host' and 'Port' as 'prefixagents.westeurope.cloudapp.azure.com' and '8081'. But I can't connect and I get a message: 'Unable to connect'.

But for all that I can succesfully connect to this port using telnet client:

telnet prefixagents.westeurope.cloudapp.azure.com 8081

Also I can connect to port 8080 and I can open tomcat web console at the following URL: http://agents.westeurope.cloudapp.azure.com:8080

I installed one more jmx command line client - http://wiki.cyclopsgroup.org/jmxterm/ and tried to connect to the service:

```<code>java -jar jmxterm-1.0-alpha-4-uber.jar  --url service:jmx:rmi:///jndi/rmi://<prefix>agents.westeurope.cloudapp.azure.com:8081/jmxrmi
</code>```

I got the next exception: "java.rmi.ConnectException: Connection refused to host: 10.0.0.4". And 10.0.0.4 is hostname of my public agents node.

I connected to my dc/os cluster ( master node ) using https://learn.microsoft.com/en-us/azure/container-service/container-service-connect. I also installed there jmxterm and tried to connect to the service via jmx:

```<code>java -jar jmxterm.jar --url service:jmx:rmi:///jndi/rmi://10.0.0.4:8081/jmxrmi
</code>```

And I connected succesfully.

Does anybody have any ideas why I can connect to the service via jmx from my master node but I can't from my local machine? Port 8081 is opened.

答:
I changed a value of property -Djava.rmi.server.hostname in JAVA_OPTS string: -Djava.rmi.server.hostname="public agent ip". And it works for me.
Working configuration for a standart tomcat container in case that port 8081 is open:

```<code>{
  "id": "/tomcat",
  "instances": 1,
  "cpus": 1,
  "mem": 512,
  "container": {
    "type": "DOCKER",
    "docker": {
      "image": "tomcat:8.0",
      "network": "BRIDGE",
      "portMappings": [
        { "protocol": "tcp", "hostPort": 8080   , "containerPort": 8080 },
        { "protocol": "tcp", "hostPort": 8081   , "containerPort": 8081 }
      ]
    }
  },
  "requirePorts": true,
  "acceptedResourceRoles": [
    "slave_public"
  ],
  "env": {
    "JAVA_OPTS": "-Dcom.sun.management.jmxremote -Djava.rmi.server.hostname=<public agent ip> -Dcom.sun.management.jmxremote.port=8081 -Dcom.sun.management.jmxremote.rmi.port=8081 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
  },
  "healthChecks": [
    {
      "gracePeriodSeconds": 120,
      "intervalSeconds": 30,
      "maxConsecutiveFailures": 3,
      "path": "/",
      "portIndex": 0,
      "protocol": "HTTP",
      "timeoutSeconds": 5
    }
  ]
}
</code>```

And I can connect to tomcat via jmx using from local machine: host="public agent ip" and port=8081

public agent ip = "prefix"agents.westeurope.cloudapp.azure.com

Title: DC/OS JMX Access

Body:
I have a dc/os cluster deployed to azure. I have deployed to the cluster a container with my java application. But I can't access it via jmx.

Let's take the example of deploying a standart tomcat image:

1) I opened a port 8081 according the next instruction: https://learn.microsoft.com/en-us/azure/container-service/container-service-enable-public-access#open-a-port-portal.

2) I deployed service using the next json:

{
  "id": "/tomcat",
  "instances": 1,
  "cpus": 1,
  "mem": 512,
  "container": {
    "type": "DOCKER",
    "docker": {
      "image": "tomcat:8.0",
      "network": "BRIDGE",
      "portMappings": [
        { "protocol": "tcp", "hostPort": 8080   , "containerPort": 8080 },
        { "protocol": "tcp", "hostPort": 8081   , "containerPort": 8081 }
      ]
    }
  },
  "requirePorts": true,
  "acceptedResourceRoles": [
    "slave_public"
  ],
  "env": {
    "JAVA_OPTS": "-Dcom.sun.management.jmxremote -Djava.rmi.server.hostname=10.0.0.4 -Dcom.sun.management.jmxremote.port=8081 -Dcom.sun.management.jmxremote.rmi.port=8081 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
  },
  "healthChecks": [
    {
      "gracePeriodSeconds": 120,
      "intervalSeconds": 30,
      "maxConsecutiveFailures": 3,
      "path": "/",
      "portIndex": 0,
      "protocol": "HTTP",
      "timeoutSeconds": 5
    }
  ]
}

To connect I use Oracle Java Mission Control. I fill fields 'Host' and 'Port' as 'prefixagents.westeurope.cloudapp.azure.com' and '8081'. But I can't connect and I get a message: 'Unable to connect'.

But for all that I can succesfully connect to this port using telnet client:

telnet prefixagents.westeurope.cloudapp.azure.com 8081

Also I can connect to port 8080 and I can open tomcat web console at the following URL: http://agents.westeurope.cloudapp.azure.com:8080

I installed one more jmx command line client - http://wiki.cyclopsgroup.org/jmxterm/ and tried to connect to the service:

java -jar jmxterm-1.0-alpha-4-uber.jar  --url service:jmx:rmi:///jndi/rmi://<prefix>agents.westeurope.cloudapp.azure.com:8081/jmxrmi

I got the next exception: "java.rmi.ConnectException: Connection refused to host: 10.0.0.4". And 10.0.0.4 is hostname of my public agents node.

I connected to my dc/os cluster ( master node ) using https://learn.microsoft.com/en-us/azure/container-service/container-service-connect. I also installed there jmxterm and tried to connect to the service via jmx:

java -jar jmxterm.jar --url service:jmx:rmi:///jndi/rmi://10.0.0.4:8081/jmxrmi

And I connected succesfully.

Does anybody have any ideas why I can connect to the service via jmx from my master node but I can't from my local machine? Port 8081 is opened.

Body:
I changed a value of property -Djava.rmi.server.hostname in JAVA_OPTS string: -Djava.rmi.server.hostname="public agent ip". And it works for me.
Working configuration for a standart tomcat container in case that port 8081 is open:

{
  "id": "/tomcat",
  "instances": 1,
  "cpus": 1,
  "mem": 512,
  "container": {
    "type": "DOCKER",
    "docker": {
      "image": "tomcat:8.0",
      "network": "BRIDGE",
      "portMappings": [
        { "protocol": "tcp", "hostPort": 8080   , "containerPort": 8080 },
        { "protocol": "tcp", "hostPort": 8081   , "containerPort": 8081 }
      ]
    }
  },
  "requirePorts": true,
  "acceptedResourceRoles": [
    "slave_public"
  ],
  "env": {
    "JAVA_OPTS": "-Dcom.sun.management.jmxremote -Djava.rmi.server.hostname=<public agent ip> -Dcom.sun.management.jmxremote.port=8081 -Dcom.sun.management.jmxremote.rmi.port=8081 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
  },
  "healthChecks": [
    {
      "gracePeriodSeconds": 120,
      "intervalSeconds": 30,
      "maxConsecutiveFailures": 3,
      "path": "/",
      "portIndex": 0,
      "protocol": "HTTP",
      "timeoutSeconds": 5
    }
  ]
}

And I can connect to tomcat via jmx using from local machine: host="public agent ip" and port=8081

public agent ip = "prefix"agents.westeurope.cloudapp.azure.com


问:
Visual Studio 2015 or 2017 does not discover unit tests
EDIT 2016-10-19:

The original question was about an issue specific to VS2015 CTP6 with the XUnit test runner. It's clear from the answers that there is a much broader issue with unit test discovery in Visual Studio which may occur in many different situations. I have cleaned up my question to reflect that.

I have also included a script in my own answer that I still use to this day to solve similar problems when they appear.

Many other answers have also proven helpful in better understanding the intricacies of the VS test runner. I appreciate that people are still sharing their solutions!

Original question 2015-04-10:

Since yesterday, my Visual Studio Test Explorer won't discover tests for any of my projects. It does not show the green loading bar after building, either.

When I go to the Visual Studio Test Explorer and click "Run All", or when I right-click any test method and select "Run Tests", I get the following in my output window:

Could not load file or assembly 'Microsoft.VisualStudio.Web.ProjectSystem, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

I am running Visual Studio 2015 CTP 6 on Windows 10 Pro Technical Preview, build 10041. The .NET Framework version does not seem to matter - it happens on 4.0, 4.5.2 and 4.6.

I tried with the following testing frameworks and all of them give the same behavior:

Microsoft.VisualStudio.QualityTools.UnitTestFramework v14.0.22609.0

xunit v2.1.0-beta1-build2945 with xunit.runner.visualstudio v2.1.0-beta1-build1051

NUnit v2.6.4 with NUnitTestAdapter v2.0.0

I found an issue on GitHub (xunit) that appeared to be similar: Cannot get tests discovered #295, with this comment from the xunit team:

Be aware that Visual Studio 2015 CTP 5 has been reported to be broken
  by many people with unit testing in general (not just xUnit.net), so
  don't expect that to work.

Also, please make sure you've cleaned out Visual Studio's runner
  cache. If it gets corrupted, Visual Studio will permanently misbehave
  until it's deleted. To clear the cache, shut down all instances of
  Visual Studio, then delete the folder
  %TEMP%\VisualStudioTestExplorerExtensions (honestly, it probably
  wouldn't hurt to delete everything in %TEMP% that can be deleted).

I tried their suggestion to delete the folder %TEMP%\VisualStudioTestExplorerExtensions. Unfortunately that did not fix the problem.

I noticed that ReSharper actually is able to discover some tests. It only works for the VS and NUnit tests, not for xunit.

There has to be some sort of temp or cache folder I need to clear, but I know Visual Studio has many of them and not all of them can be deleted without unwanted side-effects.

答:
I had the same issue. The unit test template of Visual Studio 2015 (Update 3) generates a class with TestContext property defined as follow:

```<code>    private TestContext testContextInstance;

    /// <summary>
    ///Gets or sets the test context which provides
    ///information about and functionality for the current test run.
    ///</summary>
    public TestContext TestContext
    {
        get
        {
            return testContextInstance;
        }
        set
        {
            testContextInstance = value;
        }
    }
</code>```

After changing it to a public field (ungly) the test runner could discover the test.

```<code>public TestContext TestContext;
</code>```

Very strange behaviour, but it was the cause of the issue in my case.

ContentLicense: CC BY-SA 4.0

Body:
I had the same issue. The unit test template of Visual Studio 2015 (Update 3) generates a class with TestContext property defined as follow:

    private TestContext testContextInstance;

    /// <summary>
    ///Gets or sets the test context which provides
    ///information about and functionality for the current test run.
    ///</summary>
    public TestContext TestContext
    {
        get
        {
            return testContextInstance;
        }
        set
        {
            testContextInstance = value;
        }
    }

After changing it to a public field (ungly) the test runner could discover the test.

public TestContext TestContext;

Very strange behaviour, but it was the cause of the issue in my case.


问:
Dynamically change QML Theme at runtime on MouseClick
I have Theme1.js which has the property variables related to Theme 1 styling, Similarly like this I have for Theme 2, Theme2.js
Now in main.qml, If I click on the MouseArea, The Theme should toggle between Theme1 to Theme2. I found that conditional import Statements doesn't exist in QML. Is there any other way for this.?

Theme1.js

```<code>var color="red";
var textString="This is Theme1"
</code>```

Theme2.js

```<code>var color="green";
var textString="This is Theme2"
</code>```

main.qml

```<code>import QtQuick 2.3
import QtQuick.Window 2.2
import "Theme1.js" as Theme //default Theme

Window {
    visible: true
    color:Theme.color

    MouseArea {
        anchors.fill: parent
        onClicked: {
            //Change Theme 1 to Theme 2. Basically Toggle Theme here

        }
    }

    Text {
        text: Theme.textString
        anchors.centerIn: parent
    }
}
</code>```

答:
First of all, it is not advised to use a js-library to store values, you will bind to later. This is as it is not advised to bind to var-types. You should consider transforming your libraries into QtObject-singletons.

Use libraries only as libraries for functions.

To change the theme, you might have a one singleton Style

```<code>pragma Singleton
import QtQuick 2.0

QtObject {
    property Theme current: theme1
    property Theme theme1: Theme1 { }
    property Theme theme2: Theme2 { }
}
</code>```

with Theme.qml being something like:

```<code>import QtQuick 2.0
QtObject {
    property color color0
    property color color1
    property color colorX
}
</code>```

and then Theme1.qml

```<code>import QtQuick 2.0
Theme {
    color0: 'green'
    color1: 'blue'
    colorX: 'red'
}
</code>```

and Theme2.qml being:

```<code>import QtQuick 2.0
Theme {
    color0: 'red'
    color1: 'pruple'
    colorX: 'yellow'
}
</code>```

Then you bind your properties to color: Style.current.colorX

To change the style, assign another theme to Style.current

EDIT: It might be an optimization, to use intermediate variables to shorten the paths to the value. It adds the convenience of not needing to use Style.current.color0 but to use Style.color0 instead at least.

You might use this instead for your Style.qml

```<code>pragma Singleton
import QtQuick 2.0

Theme { // Use Theme instead of QtObject
    property Theme current: theme1
    property Theme theme1: Theme1 { }
    property Theme theme2: Theme2 { }

    // Bind the `Theme`s properties as intermediate variables to the current Theme.
    color0: (current && current.color0 ? current.color0 : 'defaultColor0')
    color1: (current && current.color1 ? current.color1 : 'defaultColor1')
    colorX: (current && current.colorX ? current.colorX : 'defaultColorX')
}
</code>```

Body:
I have Theme1.js which has the property variables related to Theme 1 styling, Similarly like this I have for Theme 2, Theme2.js
Now in main.qml, If I click on the MouseArea, The Theme should toggle between Theme1 to Theme2. I found that conditional import Statements doesn't exist in QML. Is there any other way for this.?

Theme1.js

var color="red";
var textString="This is Theme1"

Theme2.js

var color="green";
var textString="This is Theme2"

main.qml

import QtQuick 2.3
import QtQuick.Window 2.2
import "Theme1.js" as Theme //default Theme

Window {
    visible: true
    color:Theme.color

    MouseArea {
        anchors.fill: parent
        onClicked: {
            //Change Theme 1 to Theme 2. Basically Toggle Theme here

        }
    }

    Text {
        text: Theme.textString
        anchors.centerIn: parent
    }
}

Body:
First of all, it is not advised to use a js-library to store values, you will bind to later. This is as it is not advised to bind to var-types. You should consider transforming your libraries into QtObject-singletons.

Use libraries only as libraries for functions.

To change the theme, you might have a one singleton Style

pragma Singleton
import QtQuick 2.0

QtObject {
    property Theme current: theme1
    property Theme theme1: Theme1 { }
    property Theme theme2: Theme2 { }
}

with Theme.qml being something like:

import QtQuick 2.0
QtObject {
    property color color0
    property color color1
    property color colorX
}

and then Theme1.qml

import QtQuick 2.0
Theme {
    color0: 'green'
    color1: 'blue'
    colorX: 'red'
}

and Theme2.qml being:

import QtQuick 2.0
Theme {
    color0: 'red'
    color1: 'pruple'
    colorX: 'yellow'
}

Then you bind your properties to color: Style.current.colorX

To change the style, assign another theme to Style.current

EDIT: It might be an optimization, to use intermediate variables to shorten the paths to the value. It adds the convenience of not needing to use Style.current.color0 but to use Style.color0 instead at least.

You might use this instead for your Style.qml

pragma Singleton
import QtQuick 2.0

Theme { // Use Theme instead of QtObject
    property Theme current: theme1
    property Theme theme1: Theme1 { }
    property Theme theme2: Theme2 { }

    // Bind the `Theme`s properties as intermediate variables to the current Theme.
    color0: (current && current.color0 ? current.color0 : 'defaultColor0')
    color1: (current && current.color1 ? current.color1 : 'defaultColor1')
    colorX: (current && current.colorX ? current.colorX : 'defaultColorX')
}


问:
How to properly defer dom element change until event handler execution in jquery
foo.html

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
    <table>
        <tr>
            <td id="tdTxtBox"><input type="text" id="txtBox"/></td>
            <td id="tdChkBox"><input type="checkbox" id="chkBox"/></td>
        </tr>
    </table>
<script src="foo.js"></script>
</body>
</html>
</code>```

foo.js

```<code>$('#txtBox').on('blur', function(){
    console.log('came out of text box');
});

$('#chkBox').on('click',function(){
    console.log('checked check box');
});
</code>```

Normal flow: Enter a value in the text box, click on the checkbox, which actually triggers both 'blur' on the text box and 'click' on the check box. This outputs:

```<code>came out of text box
checked check box
</code>```

On Changing foo.js like so:

```<code>$('#txtBox').on('blur', function(){
    console.log('came out of text box');
    $('#tdChkBox').html('<input type="checkbox" id="chkBox"/>');
});

$('#chkBox').on('click',function(){
    console.log('checked check box');
});
</code>```

This outputs:

```<code>came out of text box
</code>```

It makes sense because on blur i actually reset the #tdChkBox with another set of dom elements, jquery looses track of the raised event click for the checkbox(is this correct understanding?)

I found a fix for this issue in one the SO Post, to defer change of html using setTimeout, which will let the click event handler execute like so:

foo.js

```<code>$('#txtBox').on('blur', function(){
    console.log('came out of text box');
    setTimeout(function(){
        $('#tdChkBox').html('<input type="checkbox" id="chkBox"/>');
    },100);
});

$('#chkBox').on('click',function(){
    console.log('checked check box');
});
</code>```

Here lies the problem, the 100 ms for setTimeout works, but 0 ms doesn't work. Apparently it took time T for the system to raise the click event and register it to jquery event queue. The time assigned to setTimeout has to be greater than T.

This solution is not full proof. What if tomorrow, it takes more than 100 ms? If i increase this time to let's say 1000 ms, its a usability hit.

How to properly approach this problem? Is the understanding correct here or am i missing something fundamental?

In case this is a standard jquery/javascript problem, can someone point me in the right direction.

答:
Try with mousedown instead click .its execute before blur.Blur run on mouseup that means clicked completed

```<code>$('#txtBox').on('blur', function(){
    console.log('came out of text box');
});

$('#chkBox').on('mousedown',function(){
    console.log('checked check box');
});
</code>```

Working example

$('#txtBox').on('blur', function() {
  console.log('came out of text box');
});

$('#chkBox').on('mousedown', function() {
  console.log('checked check box');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td id="tdTxtBox"><input type="text" id="txtBox" /></td>
    <td id="tdChkBox"><input type="checkbox" id="chkBox" /></td>
  </tr>
</table></code>```

Body:
foo.html

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

            <input type="text" id="txtBox"/>
            <input type="checkbox" id="chkBox"/>

foo.js

$('#txtBox').on('blur', function(){
    console.log('came out of text box');
});

$('#chkBox').on('click',function(){
    console.log('checked check box');
});

Normal flow: Enter a value in the text box, click on the checkbox, which actually triggers both 'blur' on the text box and 'click' on the check box. This outputs:

came out of text box
checked check box

On Changing foo.js like so:

$('#txtBox').on('blur', function(){
    console.log('came out of text box');
    $('#tdChkBox').html('<input type="checkbox" id="chkBox"/>');
});

$('#chkBox').on('click',function(){
    console.log('checked check box');
});

This outputs:

came out of text box

It makes sense because on blur i actually reset the #tdChkBox with another set of dom elements, jquery looses track of the raised event click for the checkbox(is this correct understanding?)

I found a fix for this issue in one the SO Post, to defer change of html using setTimeout, which will let the click event handler execute like so:

foo.js

$('#txtBox').on('blur', function(){
    console.log('came out of text box');
    setTimeout(function(){
        $('#tdChkBox').html('<input type="checkbox" id="chkBox"/>');
    },100);
});

$('#chkBox').on('click',function(){
    console.log('checked check box');
});

Here lies the problem, the 100 ms for setTimeout works, but 0 ms doesn't work. Apparently it took time T for the system to raise the click event and register it to jquery event queue. The time assigned to setTimeout has to be greater than T.

This solution is not full proof. What if tomorrow, it takes more than 100 ms? If i increase this time to let's say 1000 ms, its a usability hit.

How to properly approach this problem? Is the understanding correct here or am i missing something fundamental?

In case this is a standard jquery/javascript problem, can someone point me in the right direction.

Body:
Try with mousedown instead click .its execute before blur.Blur run on mouseup that means clicked completed

$('#txtBox').on('blur', function(){
    console.log('came out of text box');
});

$('#chkBox').on('mousedown',function(){
    console.log('checked check box');
});

Working example

$('#txtBox').on('blur', function() {
  console.log('came out of text box');
});

$('#chkBox').on('mousedown', function() {
  console.log('checked check box');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td id="tdTxtBox"><input type="text" id="txtBox" /></td>
    <td id="tdChkBox"><input type="checkbox" id="chkBox" /></td>
  </tr>
</table>


问:
Why do I keep getting java.lang.NoClassDefFoundError at main when I try to run scalafx code in eclipse?
Please I need help with this very simple example here. I can't get to run this without getting this annoying error messages

Exception in thread "main" java.lang.NoClassDefFoundError:
scalafx/application/JFXApp$class
    at HelloScalaFX$.<init>(HelloScalaFX.scala:6)
    at HelloScalaFX$.<clinit>(HelloScalaFX.scala)
    at HelloScalaFX.main(HelloScalaFX.scala)
Caused by: java.lang.ClassNotFoundException: scalafx.application.JFXApp$class
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
```

<pre class="lang-scala prettyprint-override"><code>import scalafx.application.JFXApp
import scalafx.application.JFXApp.PrimaryStage
import scalafx.scene.Scene
import scalafx.scene.control.Label

object HelloScalaFX extends JFXApp {
    stage = new PrimaryStage {
        scene = new Scene {
            content = new Label {
                text = "Hello ScalaFX"
            }
        }
    }
 }
</code>```

答:
So, from experience, I can honestly say that if you press the run button on eclipse you should get a popup window that will often ask for a class to run. If not try and right click on your eclipse editor (where you wrote your code) go to run, check the options and select run configurations. At that point you will see what your main class is and what file you want to run. The main class usually starts with the name of the package the file is in ... it might be default if you did not name it and followed by dot name of the class like this your case it would be HelloScalaFx... if you do not see it written then you can type it in manually.
.
If this also fails... make sure your code contains the package name! after setting those configurations you should be able to run the program.</p>

Body:
Please I need help with this very simple example here. I can't get to run this without getting this annoying error messages

Exception in thread "main" java.lang.NoClassDefFoundError:
scalafx/application/JFXApp$class
    at HelloScalaFX$.<init>(HelloScalaFX.scala:6)
    at HelloScalaFX$.<clinit>(HelloScalaFX.scala)
    at HelloScalaFX.main(HelloScalaFX.scala)
Caused by: java.lang.ClassNotFoundException: scalafx.application.JFXApp$class
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)

import scalafx.application.JFXApp
import scalafx.application.JFXApp.PrimaryStage
import scalafx.scene.Scene
import scalafx.scene.control.Label

object HelloScalaFX extends JFXApp {
    stage = new PrimaryStage {
        scene = new Scene {
            content = new Label {
                text = "Hello ScalaFX"
            }
        }
    }
 }


问:
Is it possible to pause video recording in iphone sdk?
I want to pause the video recording in iOS is it possible to do that using any library or framework ?</p>

答:
You need to change it from AVCam to CameraEngine     </p>

```<code>    #import "CameraEngine.h"

- (void) startPreview
{
    AVCaptureVideoPreviewLayer* preview = [[CameraEngine engine] getPreviewLayer];
    [preview removeFromSuperlayer];
    preview.frame = self.cameraView.bounds;
    [[preview connection] setVideoOrientation:UIInterfaceOrientationLandscapeRight];

    [self.cameraView.layer addSublayer:preview];
}

    - (IBAction)startRecording:(id)sender
    {
        [[CameraEngine engine] startCapture];
    }

    - (IBAction)pauseRecording:(id)sender
    {
        [[CameraEngine engine] pauseCapture];
    }

    - (IBAction)stopRecording:(id)sender
    {
        [[CameraEngine engine] stopCapture];
    }
    - (IBAction)resumeRecording:(id)sender
    {
        [[CameraEngine engine] resumeCapture];
    }
</code>```

Body:
You need to change it from AVCam to CameraEngine

    #import "CameraEngine.h"

- (void) startPreview
{
    AVCaptureVideoPreviewLayer* preview = [[CameraEngine engine] getPreviewLayer];
    [preview removeFromSuperlayer];
    preview.frame = self.cameraView.bounds;
    [[preview connection] setVideoOrientation:UIInterfaceOrientationLandscapeRight];

    [self.cameraView.layer addSublayer:preview];
}

    - (IBAction)startRecording:(id)sender
    {
        [[CameraEngine engine] startCapture];
    }

    - (IBAction)pauseRecording:(id)sender
    {
        [[CameraEngine engine] pauseCapture];
    }

    - (IBAction)stopRecording:(id)sender
    {
        [[CameraEngine engine] stopCapture];
    }
    - (IBAction)resumeRecording:(id)sender
    {
        [[CameraEngine engine] resumeCapture];
    }


问:
Return same row alternate column value after successful LARGE?
I'm using =LARGE(H5:H24,1) to find the largest value in a column H. I also want the equivalent Column A value, i.e. If this formula returns Column H Row 3, I also want the Column A Row 3 value (this can be returned to a different result/cell). I tried VLookup but keep getting errors in the formula. Thanks

答:
Other way to solve this:

+4 at the end because we start counting from 5th row.

```<code>=INDIRECT("A"&MATCH(LARGE(H5:H24;1);H5:H24;0)+4)
</code>```

Body:
Other way to solve this:

+4 at the end because we start counting from 5th row.

=INDIRECT("A"&MATCH(LARGE(H5:H24;1);H5:H24;0)+4)


问:
Printing certain items in a premade list (python)
I am making a program with lists and selection but I cannot get the programme to output only the sections of the list i want.
the error is somewhere in here:

```<code>print(randomlist[0,3,6,9,12,15,18])
print(randomlist[1,4,7,10,13,16,19])
print(randomlist[2,5,8,11,14,17,20])
</code>```

Before it is asked:
The list works, it is with the right name, and there are 21 items in the list.
Error says 'NoneType' object is not subscriptable' and I don't really know what it means

答:
You cannot access multiple elements from a list by indexing a comma separated string. However, you should familiarize yourself with slice notation.

Since you know the indexes of the elements you are trying to access, I think you're looking for this:

```<code>print([randomlist[i] for i in (0,3,6,9,12,15,18)])
</code>```

Body:
I am making a program with lists and selection but I cannot get the programme to output only the sections of the list i want.
the error is somewhere in here:

print(randomlist[0,3,6,9,12,15,18])
print(randomlist[1,4,7,10,13,16,19])
print(randomlist[2,5,8,11,14,17,20])

Before it is asked:
The list works, it is with the right name, and there are 21 items in the list.
Error says 'NoneType' object is not subscriptable' and I don't really know what it means

Body:
You cannot access multiple elements from a list by indexing a comma separated string. However, you should familiarize yourself with slice notation.

Since you know the indexes of the elements you are trying to access, I think you're looking for this:

print([randomlist[i] for i in (0,3,6,9,12,15,18)])


问:
UIButton label detect tap on specific text
I have the following UIButton to render a checkbox and label;

To create this, I used a UIButton control with an NSMutableAttributedString to give "Terms & Conditions" a different style to the rest of the text.

Just like with a checkbox on a web page, I want the user to be able to tap either the grey text or the image itself to toggle the checkbox on or off.

But if the user clicks "Terms & Conditions" I want that to perform an action (e.g. load a terms URL).

This is really easy to do in Android as you can use checkbox.setMovementMethod(LinkMovementMethod.getInstance());, but in iOS I'm really struggling to find a way to basically create a checkbox with a label that contains a link.

Has anyone ever done this before and how did you approach?

答:
You can use TTTAttributedLabel to make a particular part or word tappable in a UILabel.

For example

```<code>label.text = @"Fork me on GitHub!"; // Repository URL will be automatically detected and linked
NSRange range = [label.text rangeOfString:@"me"];
[label addLinkToURL:[NSURL URLWithString:@"meUrl"] withRange:range];
</code>```

Here me becomes tappable and on tapping that word delegate method didSelectLinkWithURL gets called and you can check for that link inside that function

```<code>(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    NSLog(@"link %@", [url absoluteString]);
   if ([url absoluteString] == @"meUrl") {
   //implement your logic here
   }
    NSLog(@"whole label %@", label);
}
</code>```

Body:
You can use TTTAttributedLabel to make a particular part or word tappable in a UILabel.

For example

label.text = @"Fork me on GitHub!"; // Repository URL will be automatically detected and linked
NSRange range = [label.text rangeOfString:@"me"];
[label addLinkToURL:[NSURL URLWithString:@"meUrl"] withRange:range];

Here me becomes tappable and on tapping that word delegate method didSelectLinkWithURL gets called and you can check for that link inside that function

(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    NSLog(@"link %@", [url absoluteString]);
   if ([url absoluteString] == @"meUrl") {
   //implement your logic here
   }
    NSLog(@"whole label %@", label);
}


问:
How can I start / stop a request stream with node.js?
I have

```<code>return request({
  method: "POST",
  url: response.stream.url,
  json: true,
  forever: true,
  body: {
    sessionid: response.stream.sessionid,
    symbols: symbolParams
  }
}).on("data", onData)
</code>```

That gives me data whenever it comes through. But what if I want to STOP listening on that stream, how can I do that?

答:
You can use https://nodejs.org/api/events.html#events_emitter_removelistener_eventname_listener</p>

```<code>const req = request({
    method: "POST",
    url: response.stream.url,
    json: true,
    forever: true,
    body: {
        sessionid: response.stream.sessionid,
        symbols: symbolParams
    }
}).on("data", onData);
...
req.removeEventListener('data', onData);
</code>```

Body:
I have

return request({
  method: "POST",
  url: response.stream.url,
  json: true,
  forever: true,
  body: {
    sessionid: response.stream.sessionid,
    symbols: symbolParams
  }
}).on("data", onData)

That gives me data whenever it comes through. But what if I want to STOP listening on that stream, how can I do that?

Body:
You can use https://nodejs.org/api/events.html#events_emitter_removelistener_eventname_listener

const req = request({
    method: "POST",
    url: response.stream.url,
    json: true,
    forever: true,
    body: {
        sessionid: response.stream.sessionid,
        symbols: symbolParams
    }
}).on("data", onData);
...
req.removeEventListener('data', onData);


问:
How can I migrate the existing MVC+AngularJS application to Mvc+Angular4 application
I have an existing application written in mvc5 and Angular1.I want to convert all Angular1 code to Angular4 code. Is there any tool available for migration/I have to do manually.</p>

答:
No, There is no such tool available yet.

You have to create it manually. You need to convert all your pages in components as per documentation

These are few document links you can follow though.

https://www.joshmorony.com/how-to-convert-an-ionic-1-application-to-ionic-2/

https://angular.io/docs/ts/latest/guide/upgrade.html

https://www.codementor.io/angularjs/tutorial/migrating-from-angular-1-to-angular-2

https://vsavkin.com/migrating-angular-1-applications-to-angular-2-in-5-simple-steps-40621800a25b


问:
returns null mysql nodejs
please have a look at the dbfn.js file

```<code>/*database function file;*/

var db = require('./connection');

function check_conn(){
    if(db){
        console.log('We are connected to Database server'.bgGreen);
        return true;
    }else{
        console.log('We are not connected to DataBase server'.bgRed);
        return false;
    }
}

module.exports = {

    testCon : function(){
        if(check_conn() === true){
            return 'We are connected to DB';
        }else return 'We are not connected to DB';
    },

    get_user : function(){
        db.query('SELECT * FROM users',function(err,results,fields){
            if(err){
                console.log(err)
                return err;
            }
            if(results){
                console.log(results);
                return results;
            }
            console.log('nothing...');
        });
    }
};
</code>```

Now, look at routes.js file

```<code>var db = require('./dbfn');

module.exports = function(app){

    /*
        Routing starts here
    */

    //root route
    app.get('/', function(req, res){
        res.render('index.ejs');
    });

    //test route
    app.get('/test',function(req,res){

        var x = db.get_user();
        console.log(x);
        res.writeHead(200, {'Content-Type': 'text/json'});
        res.json(x);
    });

    //default it should stay at bottom
    app.get('*',function (req, res) {
        //res.redirect('/');
        res.send(404);
    });
}
</code>```

console.log on dbfn file writes full object from MySQL database but when I call it on routes.js file as var x it null I really don't understands how actually I can overcome with that. Yes, I am new student to NodeJs

Thanks.

答:
Update your query function with a callback:

```<code>get_user : function(callback){
        db.query('SELECT * FROM users',function(err,results,fields){
            if(err){
                console.log(err)
                callback(err);
            }
            if(results){
                console.log(results);
                callback(results;
            }
            console.log('nothing...');
        });
    }
</code>```

Then next in your routes check the results in the callback function

```<code>app.get('/test',function(req,res){

        db.get_user(function(result){
         console.log(result);
     });
 });
</code>```

Title: returns null mysql nodejs

Body:
please have a look at the dbfn.js file

/*database function file;*/

var db = require('./connection');

function check_conn(){
    if(db){
        console.log('We are connected to Database server'.bgGreen);
        return true;
    }else{
        console.log('We are not connected to DataBase server'.bgRed);
        return false;
    }
}

module.exports = {

    testCon : function(){
        if(check_conn() === true){
            return 'We are connected to DB';
        }else return 'We are not connected to DB';
    },

    get_user : function(){
        db.query('SELECT * FROM users',function(err,results,fields){
            if(err){
                console.log(err)
                return err;
            }
            if(results){
                console.log(results);
                return results;
            }
            console.log('nothing...');
        });
    }
};

Now, look at routes.js file

var db = require('./dbfn');

module.exports = function(app){

    /*
        Routing starts here
    */

    //root route
    app.get('/', function(req, res){
        res.render('index.ejs');
    });

    //test route
    app.get('/test',function(req,res){

        var x = db.get_user();
        console.log(x);
        res.writeHead(200, {'Content-Type': 'text/json'});
        res.json(x);
    });

    //default it should stay at bottom
    app.get('*',function (req, res) {
        //res.redirect('/');
        res.send(404);
    });
}

console.log on dbfn file writes full object from MySQL database but when I call it on routes.js file as var x it null I really don't understands how actually I can overcome with that. Yes, I am new student to NodeJs

Thanks.

Body:
Update your query function with a callback:

get_user : function(callback){
        db.query('SELECT * FROM users',function(err,results,fields){
            if(err){
                console.log(err)
                callback(err);
            }
            if(results){
                console.log(results);
                callback(results;
            }
            console.log('nothing...');
        });
    }

Then next in your routes check the results in the callback function

app.get('/test',function(req,res){

        db.get_user(function(result){
         console.log(result);
     });
 });


问:
Using SL API can't get the storage IP of the disk

curl "https://711197_bxadm%40us.ibm.com:<key>@api.softlayer.com/rest/v3/SoftLayer_Network_Storage/6640135/getObject.json?objectMask=serviceResourceBackendIpAddress"
{}
```

We can't get the storage IP of the disk. You can easily recreate the issue with this command.

Code to attach the disk -> https://github.com/cloudfoundry/bosh-softlayer-cpi-release/blob/master/src/bosh-softlayer-cpi/softlayer/vm/softlayer_virtual_guest.go#L230

答: For me the request is working fine, this might be an issue with your storage disk I recommend you to submit a ticket in softlayer in order they take a look at the device.</p>

Body:
curl "https://711197_bxadm%40us.ibm.com:<key>@api.softlayer.com/rest/v3/SoftLayer_Network_Storage/6640135/getObject.json?objectMask=serviceResourceBackendIpAddress"
{}

We can't get the storage IP of the disk. You can easily recreate the issue with this command.

Code to attach the disk -> https://github.com/cloudfoundry/bosh-softlayer-cpi-release/blob/master/src/bosh-softlayer-cpi/softlayer/vm/softlayer_virtual_guest.go#L230


问:
Require at least one element in ZF2 FieldSet
The problem

I have a Form and a FieldSet. I would like to validate that the FieldSet is not empty. Also, I want to validate each field in the FieldSet.

So far, whatever I have tried is validating one or the other, but not both. If elements is present in the Form's input filter specification, then it validates that elements is not empty, but does not validate the bar and baz fields of FieldSet. And, of course, the other way around. Any clue as to how to approach this issue would be much appreciated.

The Form

```<code>class FooForm extends Form implements InputFilterProviderInterface
{
    public function init()
    {
        $this->add([
            'name'     => 'elements',
            'type'     => Collection::class,
            'required' => true,
            'options'  => [
                'target_element' => [
                    'type' => SomeElementFieldSet::class
                ]
            ]
        ]);
    }

    public function getInputFilterSpecification()
    {
        return [
            [
                'name'        => 'elements',
                'required'    => true,
                'validators'  => [
                    ['name' => 'NotEmpty']
                ]
            ]
        ];
    }
}
</code>```

The FieldSet

```<code>class SomeElementFieldSet extends Fieldset implements InputFilterProviderInterface
{
    public function init()
    {
        $this->add(['name' => 'bar']);
        $this->add(['name' => 'baz']);
    }

    public function getInputFilterSpecification()
    {
        return [
            [
                'name'       => 'bar',
                'required'   => true,
                'validators' => [
                    ['name' => 'NotEmpty']
                ]
            ],
            [
                'name'       => 'baz',
                'required'   => true,
                'validators' => [
                    ['name' => 'NotEmpty']
                ]
            ]
        ];
    }
}
</code>```

Edit: Added full validation spec.

答:
Use setValidationGroup() method in the Form object by specifying an array of input fields you want to validate. Please refer to the Doc!

You may give a try this way. Though I have added some extra fields to the form for testing purpose only.

```<code>class FooForm extends Form implements InputFilterProviderInterface
{
     public function __construct($name = null, $options = array())
     {

        parent::__construct($name, $options);

        $this->add(['name' => 'title']);

        $this->add([
            'name'     => 'elements',
            'type'     => Collection::class,
            'required' => true,
            'options'  => [
                'target_element' => [
                    'type' => SomeElementFieldSet::class,
                ],
            ],
        ]);

        $this->add([
            'type' => 'submit',
            'name' => 'submit',
            'attributes' => [
                 'value' => 'Post'
            ],
        ]);

        // I pointed this. Here you can specify fields to be validated
        $this->setValidationGroup([
            'title',
            'elements' => [
                'bar',
            ],
        ]);
     }

    public function getInputFilterSpecification()
    {
        return [
            [
                'name'       => 'title',
                'required'   => true,
                'validators' => [
                    ['name' => 'NotEmpty']
                ]
            ],
        ];
    }
}
</code>```

And your fieldset class should be

```<code>class SomeElementFieldSet extends Fieldset implements InputFilterProviderInterface
{
    public function init()
    {
        $this->add(['name' => 'bar']);
        $this->add(['name' => 'baz']);
    }

    public function getInputFilterSpecification()
    {
        return [
            [
                'name'       => 'bar',
                'required'   => true,
                'validators' => [
                    ['name' => 'NotEmpty']
                ]
            ],
            [
                'name'       => 'baz',
                'required'   => true,
                'validators' => [
                    ['name' => 'NotEmpty']
                ]
            ]
        ];
    }
}
</code>```

Hope this would help!

Body:
The problem

I have a Form and a FieldSet. I would like to validate that the FieldSet is not empty. Also, I want to validate each field in the FieldSet.

So far, whatever I have tried is validating one or the other, but not both. If elements is present in the Form's input filter specification, then it validates that elements is not empty, but does not validate the bar and baz fields of FieldSet. And, of course, the other way around. Any clue as to how to approach this issue would be much appreciated.

The Form

class FooForm extends Form implements InputFilterProviderInterface
{
    public function init()
    {
        $this->add([
            'name'     => 'elements',
            'type'     => Collection::class,
            'required' => true,
            'options'  => [
                'target_element' => [
                    'type' => SomeElementFieldSet::class
                ]
            ]
        ]);
    }

    public function getInputFilterSpecification()
    {
        return [
            [
                'name'        => 'elements',
                'required'    => true,
                'validators'  => [
                    ['name' => 'NotEmpty']
                ]
            ]
        ];
    }
}

The FieldSet

class SomeElementFieldSet extends Fieldset implements InputFilterProviderInterface
{
    public function init()
    {
        $this->add(['name' => 'bar']);
        $this->add(['name' => 'baz']);
    }

    public function getInputFilterSpecification()
    {
        return [
            [
                'name'       => 'bar',
                'required'   => true,
                'validators' => [
                    ['name' => 'NotEmpty']
                ]
            ],
            [
                'name'       => 'baz',
                'required'   => true,
                'validators' => [
                    ['name' => 'NotEmpty']
                ]
            ]
        ];
    }
}

Edit: Added full validation spec.

Body:
Use setValidationGroup() method in the Form object by specifying an array of input fields you want to validate. Please refer to the Doc!

You may give a try this way. Though I have added some extra fields to the form for testing purpose only.

class FooForm extends Form implements InputFilterProviderInterface
{
     public function __construct($name = null, $options = array())
     {

        parent::__construct($name, $options);

        $this->add(['name' => 'title']);

        $this->add([
            'name'     => 'elements',
            'type'     => Collection::class,
            'required' => true,
            'options'  => [
                'target_element' => [
                    'type' => SomeElementFieldSet::class,
                ],
            ],
        ]);

        $this->add([
            'type' => 'submit',
            'name' => 'submit',
            'attributes' => [
                 'value' => 'Post'
            ],
        ]);

        // I pointed this. Here you can specify fields to be validated
        $this->setValidationGroup([
            'title',
            'elements' => [
                'bar',
            ],
        ]);
     }

    public function getInputFilterSpecification()
    {
        return [
            [
                'name'       => 'title',
                'required'   => true,
                'validators' => [
                    ['name' => 'NotEmpty']
                ]
            ],
        ];
    }
}

And your fieldset class should be

class SomeElementFieldSet extends Fieldset implements InputFilterProviderInterface
{
    public function init()
    {
        $this->add(['name' => 'bar']);
        $this->add(['name' => 'baz']);
    }

    public function getInputFilterSpecification()
    {
        return [
            [
                'name'       => 'bar',
                'required'   => true,
                'validators' => [
                    ['name' => 'NotEmpty']
                ]
            ],
            [
                'name'       => 'baz',
                'required'   => true,
                'validators' => [
                    ['name' => 'NotEmpty']
                ]
            ]
        ];
    }
}

Hope this would help!


问:
SQL : Error converting data type nvarchar to float
I want to convert nvarchar data to float type.

In my case I have SalesValue column and I used this command

```<code>UPDATE Overseas
SET SalesValue = CONVERT(FLOAT, REPLACE([SalesValue],',','') )
</code>```

My table has values like

```<code>201.01
40.50
215.12
550
304.201
</code>```

But I get an error

SQL : Error converting data type nvarchar to float.

How can I solve this problem ?

答:
1st cast value by using below query and then update normally </p>

```<code> SELECT
          case when  ISNUMERIC([SalesValue])=1
          then CAST([SalesValue] AS FLOAT) else 0 end AS CastedValue)
      FROM your_table_name
</code>```

Body:
I want to convert nvarchar data to float type.

In my case I have SalesValue column and I used this command

UPDATE Overseas
SET SalesValue = CONVERT(FLOAT, REPLACE([SalesValue],',','') )

My table has values like

201.01
40.50
215.12
550
304.201

But I get an error

SQL : Error converting data type nvarchar to float.

How can I solve this problem ?

Body:
1st cast value by using below query and then update normally

 SELECT
          case when  ISNUMERIC([SalesValue])=1
          then CAST([SalesValue] AS FLOAT) else 0 end AS CastedValue)
      FROM your_table_name


问:
Difference between {$_GET['id']} and '".$_GET['id']."'?
Is the any difference between writing

```
{$_GET['id']}
```

and

'".$_GET['id']."'

in a sql statement? both works the same

答:
Using either of these directly in a SQL statement is a VERY BAD IDEA. It allows for SQL injections. Be sure to sanitize your inputs using something like mysql_real_escape_string.

The main difference between the two is that the top can only be used inside a string that uses double quotes. The bottom, however, can be used with either double or single quotes.

OwnerDisplayName: Bartek

LastEditorDisplayName: Ross

ContentLicense: CC BY-SA 2.5

Body:
Is the any difference between writing

{$_GET['id']}

and

'".$_GET['id']."'

in a sql statement? both works the same

OwnerDisplayName: Evan Fosmark


问:
Packet logging on windows
Are there any methods to log incoming packets other than wincap?</p>

答:
Netmon is a free download.

Network Monitor 3.4 is a protocol
  analyzer. It allows you to capture
  network traffic, view and analyze it.

Title: Packet logging on windows