问:
How to find delay between two sets of data in Matlab?
I have two sets of data taken from experiments, and they look very similar, except there is a horizontal offset between them, which I believe is due to some bugs in the instrument setting. Suppose they have the form y1=f(x1) and y2=f(x2)= f(x1+c), what's the best way to determine c so that I can take into account the offset to superimpose two data sets to become one data set?

Edit:
let's say my data sets (index 1 and 2) have the form:

```<code>x1 = 0:0.2:10;
y1 = sin(x1)
x2 = 0:0.3:10;
y2 = sin(x2+0.5)
</code>```

Of course, the real data will have some noise, but say the best fit functions have the above forms. How do I find the offset c=0.5? I have looked into the cross-correlation, but I'm not sure if they can handle two data sets with different number of data (and different step sizes). Also, what if the offset values actually fall between two data points? Cross-correlation only returns the index of the data in the array, not something in between if I understand correctly.

答: write a function which takes the time shift as an input and calculates rms between overlapping portions of the two data sets. Then find the minimum of this function using optimization (fminbnd)</p>

Body:
I have two sets of data taken from experiments, and they look very similar, except there is a horizontal offset between them, which I believe is due to some bugs in the instrument setting. Suppose they have the form y1=f(x1) and y2=f(x2)= f(x1+c), what's the best way to determine c so that I can take into account the offset to superimpose two data sets to become one data set?

Edit:
let's say my data sets (index 1 and 2) have the form:

x1 = 0:0.2:10;
y1 = sin(x1)
x2 = 0:0.3:10;
y2 = sin(x2+0.5)

Of course, the real data will have some noise, but say the best fit functions have the above forms. How do I find the offset c=0.5? I have looked into the cross-correlation, but I'm not sure if they can handle two data sets with different number of data (and different step sizes). Also, what if the offset values actually fall between two data points? Cross-correlation only returns the index of the data in the array, not something in between if I understand correctly.


来源: stackexchange

问:
Abusing Query or QueryAsync when used with CUD operations
I'm trying to implement a repository with Dapper as ORM, I want inserted or updated entities to be returned back. This is what I came up with, it works just fine but I'm wondering if this is abusing the default Query and QueryAsync methods?</p>

```<code>public async Task<Models.TestTable> Insert(Models.TestTable inputObject)
{
    IEnumerable<Models.TestTable> output;

    output = await _connection.QueryAsync<Models.TestTable>(
        sql: string.Format("INSERT INTO TestTable (FirstName, LastName) OUTPUT INSERTED.* VALUES (@FirstName, @LastName)"),
        param: inputObject);

    return output.SingleOrDefault();
}
</code>```

答:
The only actual problem I can see there is the unnecessary string.Format.

Personally I might have been tempted to just update the Id (or whatever) in the existing object, but your OUTPUT INSERTED.* works fine too. I might be very tempted to move the local declaration inline via var output = ..., and of course once I've done that it makes it tempting to make the entire thing inline:

```<code>public async Task<Models.TestTable> Insert(Models.TestTable inputObject)
    => (await _connection.QueryAsync<Models.TestTable>(
    "INSERT INTO TestTable (FirstName, LastName) OUTPUT INSERTED.* VALUES (@FirstName, @LastName)",
    inputObject)).SingleOrDefault();
</code>```

but most of that is trivia and subjective. Heck, even the string.Format is just unnecessary rather than problematic.

One other thing to check: did we (and I can't remember!) add a QuerySingleOrDefaultAsync method? I know we added QuerySingleOrDefault - I just can't remember about the *Async twin.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to implement a repository with Dapper as ORM, I want inserted or updated entities to be returned back. This is what I came up with, it works just fine but I'm wondering if this is abusing the default Query and QueryAsync methods?

public async Task<Models.TestTable> Insert(Models.TestTable inputObject)
{
    IEnumerable<Models.TestTable> output;

    output = await _connection.QueryAsync<Models.TestTable>(
        sql: string.Format("INSERT INTO TestTable (FirstName, LastName) OUTPUT INSERTED.* VALUES (@FirstName, @LastName)"),
        param: inputObject);

    return output.SingleOrDefault();
}

Body:
The only actual problem I can see there is the unnecessary string.Format.

Personally I might have been tempted to just update the Id (or whatever) in the existing object, but your OUTPUT INSERTED.* works fine too. I might be very tempted to move the local declaration inline via var output = ..., and of course once I've done that it makes it tempting to make the entire thing inline:

public async Task<Models.TestTable> Insert(Models.TestTable inputObject)
    => (await _connection.QueryAsync<Models.TestTable>(
    "INSERT INTO TestTable (FirstName, LastName) OUTPUT INSERTED.* VALUES (@FirstName, @LastName)",
    inputObject)).SingleOrDefault();

but most of that is trivia and subjective. Heck, even the string.Format is just unnecessary rather than problematic.

One other thing to check: did we (and I can't remember!) add a QuerySingleOrDefaultAsync method? I know we added QuerySingleOrDefault - I just can't remember about the *Async twin.


问:
What would a basic Gradle script Kotlin file for a Kotlin JS project look like?
I'm trying to use Kotlin-DSL to write a Gradle build script in Kotlin. So far I've seen examples on how this can be done for a Java project. However since I'm developing a React Native app in Kotlin, there isn't any tutorials I've found for making one for Kotlin/JavaScript projects. So what would a basic Gradle script Kotlin file for such a purpose look like?

答: The official Gradle Kotlin DSL repository contains a basic Kotlin/JS sample: https://github.com/gradle/kotlin-dsl/tree/master/samples/hello-js</p>


问:
How does main.js link to Index.html in Vue-cli webpack template
I noticed vue-cli webpack project-name template loads these codes.

main.js

```<code>...
new Vue({
    el: '#app',
    render: h => h(App),
});
</code>```

index.html

```<code>...
<head>
...
</head>
<body>
    <div id="app"></div>  <!-- if I change app to app1, error message states: "Cannot find element app" -->
    <script src="./dist/build.js"></script>
</body>
....
</code>```

The two are linked together. However, how are they linked?
It appears to be a result of build.js but I'm unable to understand the code as it has been compiled and minified, uglified etc...

My webpack.config.js settings is default template.

答:
you project used Webpack as a module bundler - it injects app.js into index.html

to get a non-uglified bundle, edit the Webpack settings like this:

comment call plugin uglifyjs-webpack-plugin in build/webpack.prod.conf.js

before

```<code>...
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
  'process.env': env
}),
new UglifyJsPlugin({
  uglifyOptions: {
    compress: {
      warnings: false
    }
  },
  sourceMap: config.build.productionSourceMap,
  parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
  filename: utils.assetsPath('css/[name].[contenthash].css'),
  // set the following option to `true` if you want to extract CSS from
  // codesplit chunks into this main css file as well.
  // This will result in *all* of your app's CSS being loaded upfront.
  allChunks: false,
})
...
</code>```

after

```<code>...
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
  'process.env': env
}),
// new UglifyJsPlugin({
//   uglifyOptions: {
//     compress: {
//       warnings: false
//     }
//   },
//   sourceMap: config.build.productionSourceMap,
//   parallel: true
// }),
// extract css into its own file
new ExtractTextPlugin({
  filename: utils.assetsPath('css/[name].[contenthash].css'),
  // set the following option to `true` if you want to extract CSS from
  // codesplit chunks into this main css file as well.
  // This will result in *all* of your app's CSS being loaded upfront.
  allChunks: false,
}),
...
</code>```

also if you want to change the name of index.html to foo.html of the input file you can do it here:

line 68 in build/webpack.prod.conf.js change to

```<code>template: 'foo.html',
</code>```

Body:
I noticed vue-cli webpack project-name template loads these codes.

main.js

...
new Vue({
    el: '#app',
    render: h => h(App),
});

index.html

...

...

....

The two are linked together. However, how are they linked?
It appears to be a result of build.js but I'm unable to understand the code as it has been compiled and minified, uglified etc...

My webpack.config.js settings is default template.

Body:
you project used Webpack as a module bundler - it injects app.js into index.html

to get a non-uglified bundle, edit the Webpack settings like this:

comment call plugin uglifyjs-webpack-plugin in build/webpack.prod.conf.js

before

...
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
  'process.env': env
}),
new UglifyJsPlugin({
  uglifyOptions: {
    compress: {
      warnings: false
    }
  },
  sourceMap: config.build.productionSourceMap,
  parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
  filename: utils.assetsPath('css/[name].[contenthash].css'),
  // set the following option to `true` if you want to extract CSS from
  // codesplit chunks into this main css file as well.
  // This will result in *all* of your app's CSS being loaded upfront.
  allChunks: false,
})
...

after

...
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
  'process.env': env
}),
// new UglifyJsPlugin({
//   uglifyOptions: {
//     compress: {
//       warnings: false
//     }
//   },
//   sourceMap: config.build.productionSourceMap,
//   parallel: true
// }),
// extract css into its own file
new ExtractTextPlugin({
  filename: utils.assetsPath('css/[name].[contenthash].css'),
  // set the following option to `true` if you want to extract CSS from
  // codesplit chunks into this main css file as well.
  // This will result in *all* of your app's CSS being loaded upfront.
  allChunks: false,
}),
...

also if you want to change the name of index.html to foo.html of the input file you can do it here:

line 68 in build/webpack.prod.conf.js change to

template: 'foo.html',


问:
Contributing to a GIT repository
The author of a repository on Github asked for contribution on his project by translating some language files. I tried to collaborate by doing the following steps:

Clone the repository and make a Pull

Create a branch "German_locale"

Made changes to language files

commit while adding a message

Push branch to origin (failed)

Intended final step: pull request on Github website

However, the 5. action fails. It asks for Username /Password and doesn't give me access if I'm providing my personal. I think, the system tries to verify me as the original author, which I am not.

The very basic questions are (sorry, I'm new):

What do I have to do in order to push a branch to a foreign repository? Do I have to ask for being a collaborator first? This doesn't seem right.

Would it be a better idea to create a fork in the first place? This doesn't seem right, either.

I'm using SmartGit as a client, so please describe the solution rather then providing command lines. I really want to understand how that works. I have seen other contributors translating other language files on this project successfully but have no idea how that works in general.

答:
Typically in these situations, especially if we're talking about contributing to an open source project, you should fork the project, work on master, and then create a pull request from your fork to the original project.

Of course "typically" is not always. Read the contribution guide of the project (if available) or ask the owner to give it to you so that expectations are clear.

Forking, if you are unfamiliar with it, is like remote cloning ( a copy of the original project is made under your namespace in github ) and you only work on (clone) the fork locally on your workstation.

Forking is not a git client operation so it needs to be done on the server interface (github.com in this case).

Title: Contributing to a GIT repository


问:
own len function with recursion in Go
I'm trying to build simple function to count elements in slice (like len) It must be simple (without additional libs) and with recursion. The problem is when i try to check is slice is empty (is nul).

```<code>package main
import "fmt"

func main() {
  x := []int{1, 2, 3}
  fmt.Println(len2(x))
}
func len2(s []int) int {
  if s == nil {
    return 0
  }
  return 1 + len2(s[1:])
}
</code>```

the result it should be in this example '3'.

It's broken in if s == nil:

```<code>panic: runtime error: slice bounds out of range
</code>```

答:
If you do not want to use len() func, you can use cap()

```<code>func main() {
  x := []int{1, 2, 3}
  fmt.Println(len2(x))
}

func len2(s []int) int {

 if cap(s) == 0 {
    return 0
 }

  return 1 + len2(s[1:])
}
</code>```

Try it again

Original Answer:

In order to check if an array (slice) is empty, you should use the function len()

```<code>  if len(s) == 0 {
    return 0
  }
</code>```

Try it

Title: own len function with recursion in Go

Body:
I'm trying to build simple function to count elements in slice (like len) It must be simple (without additional libs) and with recursion. The problem is when i try to check is slice is empty (is nul).

package main
import "fmt"

func main() {
  x := []int{1, 2, 3}
  fmt.Println(len2(x))
}
func len2(s []int) int {
  if s == nil {
    return 0
  }
  return 1 + len2(s[1:])
}

the result it should be in this example '3'.

It's broken in if s == nil:

panic: runtime error: slice bounds out of range

Body:
If you do not want to use len() func, you can use cap()

func main() {
  x := []int{1, 2, 3}
  fmt.Println(len2(x))
}

func len2(s []int) int {

 if cap(s) == 0 {
    return 0
 }

  return 1 + len2(s[1:])
}

Try it again

Original Answer:

In order to check if an array (slice) is empty, you should use the function len()

  if len(s) == 0 {
    return 0
  }

Try it


问:
CSS not applied to Webpacked module
I'm fairly new to building my own webpack.config.js and I'm trying to use the Noty module (to display modal notifications), installed via npm.

It seems that I manage to import the Noty javascript, but not the CSS: the notification appears at the very bottom of my page without any style whatsoever when it should be a red box at the top center.

My understanding of Webpack being quite shallow, I have no idea what the problem is! Below is my webpack.config.js and the file trying to use Noty.

webpack.config.js

```<code>const path = require('path');

module.exports = {
    entry: './front/app.js',
    output: {
        path: path.resolve(__dirname, 'web/js'),
        filename: 'bundle.js',
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015']
                },
                exclude: /node_modules/,
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                loaders: ['style-loader', 'css-loader'],
            },
            {
                test: /\.css$/,
                include: /node_modules/,
                loaders: ['style-loader', 'css-loader'],
            },
            {
              test: /\.html$/,
              loader: 'html-loader',
            },
        ]
    },
};
</code>```

music.js

```<code>import Noty from 'noty';
import request from './request';

export default class Music {
    loadSongVersion(songVersionId, audioElement) {
        request(`/api/song-version/${songVersionId}`)
            .then((songVersion) => {
                audioElement.src = songVersion.src;
            })
            .catch((err) => {
                console.error(`Could not fetch song version by ID ${songVersionId}`);
                new Noty({
                    text: 'Error while fetching this song version',
                    layout: 'topCenter',
                }).show();
            });
    }
};
</code>```

If any of you has an idea of what the problem is, I'd be infinitely grateful!

答:
Add this to music.js:

```<code>import 'noty/lib/noty.css'
</code>```

Ref: https://github.com/needim/noty/issues/368

Title: CSS not applied to Webpacked module

Body:
I'm fairly new to building my own webpack.config.js and I'm trying to use the Noty module (to display modal notifications), installed via npm.

It seems that I manage to import the Noty javascript, but not the CSS: the notification appears at the very bottom of my page without any style whatsoever when it should be a red box at the top center.

My understanding of Webpack being quite shallow, I have no idea what the problem is! Below is my webpack.config.js and the file trying to use Noty.

webpack.config.js

const path = require('path');

module.exports = {
    entry: './front/app.js',
    output: {
        path: path.resolve(__dirname, 'web/js'),
        filename: 'bundle.js',
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015']
                },
                exclude: /node_modules/,
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                loaders: ['style-loader', 'css-loader'],
            },
            {
                test: /\.css$/,
                include: /node_modules/,
                loaders: ['style-loader', 'css-loader'],
            },
            {
              test: /\.html$/,
              loader: 'html-loader',
            },
        ]
    },
};

music.js

import Noty from 'noty';
import request from './request';

export default class Music {
    loadSongVersion(songVersionId, audioElement) {
        request(`/api/song-version/${songVersionId}`)
            .then((songVersion) => {
                audioElement.src = songVersion.src;
            })
            .catch((err) => {
                console.error(`Could not fetch song version by ID ${songVersionId}`);
                new Noty({
                    text: 'Error while fetching this song version',
                    layout: 'topCenter',
                }).show();
            });
    }
};

If any of you has an idea of what the problem is, I'd be infinitely grateful!

Body:
Add this to music.js:

import 'noty/lib/noty.css'

Ref: https://github.com/needim/noty/issues/368


问:
JavaFX 8: Intercepting appication "exit"
In order to verify that all changes made by the user have been saved I want to intercept the exiting/quitting of a JavaFX application.

Is there a common way-to-go to achieve this like overriding an event or is there more to it?

答:
As they have already said, this is done by intercepting WindowEvent.WINDOW_CLOSE_REQUEST. You can then stop the suspension by calling event.consume().

This is an example of how to capture the event and display a confirmation dialog. Depending on the user's choice, you can take serialization actions if you wish.

```<code>primaryStage.setOnCloseRequest(event -> {
    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.initOwner(primaryStage);
    alert.initModality(Modality.APPLICATION_MODAL);

    alert.setHeaderText("Exit");
    alert.setContentText("Do you want to exit?");

    alert.getDialogPane().getButtonTypes().setAll(ButtonType.OK, ButtonType.NO);
    Optional<ButtonType> optional = alert.showAndWait();

    if(optional.isPresent() && optional.get() == ButtonType.OK) {
        // save data

        return;
    }

    event.consume();
});
</code>```

In order for the implementation to be complete, you need to implement a logic for clear exit from the application from control. For example, when choosing from the File menu -> Close. When capturing the event, you must run WindowEvent.WINDOW_CLOSE_REQUEST to trick the exit logic.

```<code>closeMenuItem.setOnAction(event -> {
    Window window = menuBar.getScene().getWindow();
    window.fireEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSE_REQUEST));
});
</code>```

Body:
As they have already said, this is done by intercepting WindowEvent.WINDOW_CLOSE_REQUEST. You can then stop the suspension by calling event.consume().

This is an example of how to capture the event and display a confirmation dialog. Depending on the user's choice, you can take serialization actions if you wish.

primaryStage.setOnCloseRequest(event -> {
    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.initOwner(primaryStage);
    alert.initModality(Modality.APPLICATION_MODAL);

    alert.setHeaderText("Exit");
    alert.setContentText("Do you want to exit?");

    alert.getDialogPane().getButtonTypes().setAll(ButtonType.OK, ButtonType.NO);
    Optional<ButtonType> optional = alert.showAndWait();

    if(optional.isPresent() && optional.get() == ButtonType.OK) {
        // save data

        return;
    }

    event.consume();
});

In order for the implementation to be complete, you need to implement a logic for clear exit from the application from control. For example, when choosing from the File menu -> Close. When capturing the event, you must run WindowEvent.WINDOW_CLOSE_REQUEST to trick the exit logic.

closeMenuItem.setOnAction(event -> {
    Window window = menuBar.getScene().getWindow();
    window.fireEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSE_REQUEST));
});


问:
How to exclude the support v4 library from the studio?
FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException:
  java.util.zip.ZipException: duplicate entry: android/support/v4/content/Loader$OnLoadCompleteListener.class

Code in build.gradle file

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

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    //compile project(':ActionBarSherlock-4.1.0')
    compile project(':GooglePlayServicesLibrary')
    compile files('libs/eventbus-2.4.0.jar')
    compile (project(':AndroidBetterPickers')){ exclude module: 'support-v4' }
    compile (project(':ZxingFragmentLib')){ exclude module: 'support-v4' }
    compile (project(':RobotoTextView')){ exclude module: 'support-v4' }
    compile (project(':PanesLibrary')){ exclude module: 'support-v4' }
    compile (project(':ShowCaseViewLibrary')){ exclude module: 'support-v4' }
    compile (project(':ActionBarSherlock-4.1.0')){ exclude module: 'support-v4' }

}

buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'
    }

}

allprojects {
    repositories {
        jcenter()
        mavenCentral()
    }
}

android {
    packagingOptions {

        exclude  'META-INF/maven/com.nineoldandroids/library/pom.xml'
        exclude  'META-INF/maven/com.nineoldandroids/library/pom.properties'
        exclude  'META-INF/services/javax.annotation.processing.Processor'

    }

    dexOptions {
        javaMaxHeapSize "4g"
    }
    compileSdkVersion 19
    buildToolsVersion '22.0.1'

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 15
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['.apt_generated','res','src']
            resources.srcDirs = ['.apt_generated','res','src']
            aidl.srcDirs = ['.apt_generated','res','src']
            renderscript.srcDirs = ['.apt_generated','res','src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move the tests to tests/java, tests/res, etc...
        instrumentTest.setRoot('tests')

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }

}
</code>```

答:
```<code>dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    // compile project(':ActionBarSherlock-4.1.0')
    compile project(':GooglePlayServicesLibrary')
    compile files('libs/eventbus-2.4.0.jar')
    compile (project(':AndroidBetterPickers'))
    compile (project(':ZxingFragmentLib'))
    compile (project(':RobotoTextView'))
    compile (project(':PanesLibrary'))
    compile (project(':ShowCaseViewLibrary'))
    compile (project(':ActionBarSherlock-4.1.0'))
compile files('libs/support-v4-19.0.1.jar')
</code>```

Body:
FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException:
  java.util.zip.ZipException: duplicate entry: android/support/v4/content/Loader$OnLoadCompleteListener.class

Code in build.gradle file

   apply plugin: 'com.android.application'

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    //compile project(':ActionBarSherlock-4.1.0')
    compile project(':GooglePlayServicesLibrary')
    compile files('libs/eventbus-2.4.0.jar')
    compile (project(':AndroidBetterPickers')){ exclude module: 'support-v4' }
    compile (project(':ZxingFragmentLib')){ exclude module: 'support-v4' }
    compile (project(':RobotoTextView')){ exclude module: 'support-v4' }
    compile (project(':PanesLibrary')){ exclude module: 'support-v4' }
    compile (project(':ShowCaseViewLibrary')){ exclude module: 'support-v4' }
    compile (project(':ActionBarSherlock-4.1.0')){ exclude module: 'support-v4' }

}

buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'
    }

}

allprojects {
    repositories {
        jcenter()
        mavenCentral()
    }
}

android {
    packagingOptions {

        exclude  'META-INF/maven/com.nineoldandroids/library/pom.xml'
        exclude  'META-INF/maven/com.nineoldandroids/library/pom.properties'
        exclude  'META-INF/services/javax.annotation.processing.Processor'

    }

    dexOptions {
        javaMaxHeapSize "4g"
    }
    compileSdkVersion 19
    buildToolsVersion '22.0.1'

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 15
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['.apt_generated','res','src']
            resources.srcDirs = ['.apt_generated','res','src']
            aidl.srcDirs = ['.apt_generated','res','src']
            renderscript.srcDirs = ['.apt_generated','res','src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move the tests to tests/java, tests/res, etc...
        instrumentTest.setRoot('tests')

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }

}


问:
boost::thread build error (unable to link lib && unresolved external)
I'm trying to follow a simple tutorial of Boost::Thread (ver 1.4-3) in VS 2008:

```<code>#include <boost/thread/thread.hpp>

void Func()
{
    // Do something
}

void main()
{
    boost::thread _thrd(&Func);
    _thrd.join();
    ....
}
</code>```

During compilation it produces this error:

```<code>Error 1 fatal error LNK1104: cannot open file 'libboost_thread-vc90-mt-gd-1_43.lib' CConsole
</code>```

which I have to resolve by adding #define BOOST_ALL_NO_LIB.
However, it gives me another error:

```<code>Error 3 fatal error LNK1120: 2 unresolved externals
C:\xx\Documents\Visual Studio 2008\Projects\CConsole\Debug\CConsole.exe

Error 1 error LNK2019: unresolved external symbol "public: __thiscall boost::thread::~thread(void)" (??1thread@boost@@QAE@XZ) referenced in function _wmain CConsole.obj

Error 2 error LNK2019: unresolved external symbol "private: void __thiscall boost::thread::start_thread(void)" (?start_thread@thread@boost@@AAEXXZ) referenced in function "public: __thiscall boost::thread::thread<void (__cdecl*)(void)>(void (__cdecl*)(void),struct boost::thread::dummy *)" (??$?0P6AXXZ@thread@boost@@QAE@P6AXXZPAUdummy@01@@Z) CConsole.obj
</code>```

Does anyone know how to resolve the issue?

Thanks.

答:
I think a deeper answer than "Read the F*cking Manual" might be helpful!

This kind of link error is a clue that you're trying to link an incompatible Boost library.

I got this when I mistakenly built a 32 bit Boost thread library when I thought I was building a 64 bit library.  It took a while to figure out that when you say --address-model=64 as a bjam command line parameter you have made a subtle mistake.  The address-model parameter must NOT have the -- prefix.  Unfortunately bjam does not inform you when it sees the incorrect syntax.

You can use the dumpbin program to check the symbols provided by your library, versus the symbols that the linker says are unresolved.  I found that the library symbols were decorated with __thiscall and not __cdecl.  This is a screaming good clue of the architecture mismatch.  The Microsoft compiler uses the __thiscall function call protocol for 32-bit builds, but it uses __cdecl for 64-bit builds.  Yes, the Microsoft documentation is a little weak here!!

The best way to check a .lib or .dll to see how it was built is to use the dumpbin program.  Here's an example:

```<code>dumpbin /headers libboost_thread-vc100-mt-gd-1_45.lib | findstr machine
</code>```

You'll have to adjust the library name to suit what you're linking of course.  This will show you unambiguously whether the .lib or .dll is targeted for x86 (which is 32-bit) or x64 (64-bit).

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to follow a simple tutorial of Boost::Thread (ver 1.4-3) in VS 2008:

#include <boost/thread/thread.hpp>

void Func()
{
    // Do something
}

void main()
{
    boost::thread _thrd(&Func);
    _thrd.join();
    ....
}

During compilation it produces this error:

Error 1 fatal error LNK1104: cannot open file 'libboost_thread-vc90-mt-gd-1_43.lib' CConsole

which I have to resolve by adding #define BOOST_ALL_NO_LIB.
However, it gives me another error:

Error 3 fatal error LNK1120: 2 unresolved externals
C:\xx\Documents\Visual Studio 2008\Projects\CConsole\Debug\CConsole.exe

Error 1 error LNK2019: unresolved external symbol "public: __thiscall boost::thread::~thread(void)" (??1thread@boost@@QAE@XZ) referenced in function _wmain CConsole.obj

Error 2 error LNK2019: unresolved external symbol "private: void __thiscall boost::thread::start_thread(void)" (?start_thread@thread@boost@@AAEXXZ) referenced in function "public: __thiscall boost::thread::thread<void (__cdecl*)(void)>(void (__cdecl*)(void),struct boost::thread::dummy *)" (??$?0P6AXXZ@thread@boost@@QAE@P6AXXZPAUdummy@01@@Z) CConsole.obj

Does anyone know how to resolve the issue?

Thanks.

Body:
I think a deeper answer than "Read the F*cking Manual" might be helpful!

This kind of link error is a clue that you're trying to link an incompatible Boost library.

I got this when I mistakenly built a 32 bit Boost thread library when I thought I was building a 64 bit library.  It took a while to figure out that when you say --address-model=64 as a bjam command line parameter you have made a subtle mistake.  The address-model parameter must NOT have the -- prefix.  Unfortunately bjam does not inform you when it sees the incorrect syntax.

You can use the dumpbin program to check the symbols provided by your library, versus the symbols that the linker says are unresolved.  I found that the library symbols were decorated with __thiscall and not __cdecl.  This is a screaming good clue of the architecture mismatch.  The Microsoft compiler uses the __thiscall function call protocol for 32-bit builds, but it uses __cdecl for 64-bit builds.  Yes, the Microsoft documentation is a little weak here!!

The best way to check a .lib or .dll to see how it was built is to use the dumpbin program.  Here's an example:

dumpbin /headers libboost_thread-vc100-mt-gd-1_45.lib | findstr machine

You'll have to adjust the library name to suit what you're linking of course.  This will show you unambiguously whether the .lib or .dll is targeted for x86 (which is 32-bit) or x64 (64-bit).


问:
How to send email in ASP.NET C#
I'm very new to the ASP.NET C# area. I'm planning to send a mail through ASP.NET C# and this is the SMTP address from my ISP:

```<code>smtp-proxy.tm.net.my
</code>```

Below is what I tried to do, but failed.

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="SendMail" %>
<html>
<head id="Head1" runat="server"><title>Email Test Page</title></head>
<body>
    <form id="form1" runat="server">
        Message to: <asp:TextBox ID="txtTo" runat="server" /><br>
        Message from: <asp:TextBox ID="txtFrom" runat="server" /><br>
        Subject: <asp:TextBox ID="txtSubject" runat="server" /><br>
        Message Body:<br>
        <asp:TextBox ID="txtBody" runat="server" Height="171px" TextMode="MultiLine"  Width="270px" /><br>
        <asp:Button ID="Btn_SendMail" runat="server" onclick="Btn_SendMail_Click" Text="Send Email" /><br>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>
</body>
</html>
</code>```

And below is my code-behind:

```<code>using System;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
{
    protected void Btn_SendMail_Click(object sender, EventArgs e)
    {
        MailMessage mailObj = new MailMessage(
            txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
        SmtpClient SMTPServer = new SmtpClient("127.0.0.1");
        try
        {
            SMTPServer.Send(mailObj);
        }
        catch (Exception ex)
        {
            Label1.Text = ex.ToString();
        }
    }
}
</code>```

PS: I'm sorry that I couldn't understand the receiver/sender SMTP concept, and so I am trying to understand the whole concept from here.

答:
This is the easiest script to test.

```<code><%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>

<script language="C#" runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
       //create the mail message
        MailMessage mail = new MailMessage();

        //set the addresses
        mail.From = new MailAddress("From email account");
        mail.To.Add("To email account");

        //set the content
        mail.Subject = "This is a test email from C# script";
        mail.Body = "This is a test email from C# script";
        //send the message
         SmtpClient smtp = new SmtpClient("mail.domainname.com");

         NetworkCredential Credentials = new NetworkCredential("to email account", "Password");
         smtp.Credentials = Credentials;
         smtp.Send(mail);
         lblMessage.Text = "Mail Sent";
    }
</script>
<html>
<body>
    <form runat="server">
        <asp:Label id="lblMessage" runat="server"></asp:Label>
    </form>
</body>
</code>```

Title: How to send email in ASP.NET C#

Body:
I'm very new to the ASP.NET C# area. I'm planning to send a mail through ASP.NET C# and this is the SMTP address from my ISP:

smtp-proxy.tm.net.my

Below is what I tried to do, but failed.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="SendMail" %>

<title>Email Test Page</title>

    <form id="form1" runat="server">
        Message to: <asp:TextBox ID="txtTo" runat="server" />

        Message from: <asp:TextBox ID="txtFrom" runat="server" />

        Subject: <asp:TextBox ID="txtSubject" runat="server" />

        Message Body:

        <asp:TextBox ID="txtBody" runat="server" Height="171px" TextMode="MultiLine"  Width="270px" />

        <asp:Button ID="Btn_SendMail" runat="server" onclick="Btn_SendMail_Click" Text="Send Email" />

        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>

And below is my code-behind:

using System;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
{
    protected void Btn_SendMail_Click(object sender, EventArgs e)
    {
        MailMessage mailObj = new MailMessage(
            txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
        SmtpClient SMTPServer = new SmtpClient("127.0.0.1");
        try
        {
            SMTPServer.Send(mailObj);
        }
        catch (Exception ex)
        {
            Label1.Text = ex.ToString();
        }
    }
}

PS: I'm sorry that I couldn't understand the receiver/sender SMTP concept, and so I am trying to understand the whole concept from here.

Body:
This is the easiest script to test.

<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>

<script language="C#" runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
       //create the mail message
        MailMessage mail = new MailMessage();

        //set the addresses
        mail.From = new MailAddress("From email account");
        mail.To.Add("To email account");

        //set the content
        mail.Subject = "This is a test email from C# script";
        mail.Body = "This is a test email from C# script";
        //send the message
         SmtpClient smtp = new SmtpClient("mail.domainname.com");

         NetworkCredential Credentials = new NetworkCredential("to email account", "Password");
         smtp.Credentials = Credentials;
         smtp.Send(mail);
         lblMessage.Text = "Mail Sent";
    }
</script>
<html>
<body>
    <form runat="server">
        <asp:Label id="lblMessage" runat="server"></asp:Label>
    </form>
</body>


问:
How to preserve processing instructions whilst producing XSL-FO in eXist-db?
Is there a way to make eXist to return processing instruction as it is? It seems it somehow ignores it in the output.

Processing instructions are very useful if I use XEP as my rendering engine, hence it would be great to be able to preserve them before the root of the XSL-FO document or immediately after its start.

If I have in the template:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:tei="http://www.tei-c.org/ns/1.0" version="2.0">
    <xsl:template match="/">
        <fo:root>
        <?xep-pdf-page-layout two-columns-right?>
</code>```

It simply returns:

```<code><fo:root xmlns:tei="http://www.tei-c.org/ns/1.0" xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>
</code>```

I’ve tried to touch preserving of processing instructions with:
declare option exist:serialize "method=xhtml media-type=text/xml process-xsl-pi=yes"; in the prolog of my query but to no avail.

UPDATE I

The steps of my scenario are:

loading the document from the DB

passing it to the transform:transform() function

whilst calling the transform:transform() function, I pass to it one basic stylesheet, which includes other stylesheets

I need to add the processing instruction to a stylesheet for pages-masters, which covers the root of the FO document later used by the rendering engine. This stylesheet is included (<xsl:include/>) into the basic one (gathering all the stylesheets) and passed to the function.

答: With XSLT, to output a processing instruction use https://www.w3.org/TR/xslt/#creating-processing-instructions, that is <xsl:processing-instruction name="xep-pdf-page-layout">two-columns-right</xsl:processing-instruction> to have the pi <?xep-pdf-page-layout two-columns-right?> in the transformation result.

Body:
Is there a way to make eXist to return processing instruction as it is? It seems it somehow ignores it in the output.

Processing instructions are very useful if I use XEP as my rendering engine, hence it would be great to be able to preserve them before the root of the XSL-FO document or immediately after its start.

If I have in the template:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:tei="http://www.tei-c.org/ns/1.0" version="2.0">
    <xsl:template match="/">
        <fo:root>
        <?xep-pdf-page-layout two-columns-right?>

It simply returns:

<fo:root xmlns:tei="http://www.tei-c.org/ns/1.0" xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:layout-master-set>

I’ve tried to touch preserving of processing instructions with:
declare option exist:serialize "method=xhtml media-type=text/xml process-xsl-pi=yes"; in the prolog of my query but to no avail.

UPDATE I

The steps of my scenario are:

loading the document from the DB

passing it to the transform:transform() function

whilst calling the transform:transform() function, I pass to it one basic stylesheet, which includes other stylesheets

I need to add the processing instruction to a stylesheet for pages-masters, which covers the root of the FO document later used by the rendering engine. This stylesheet is included (<xsl:include/>) into the basic one (gathering all the stylesheets) and passed to the function.


问:
shared_from_this() from another thread (a member thread function)
In my code I use boost::threads and I have a class that runs a thread via a member function called fnThread() . In this fnThread() I want to create a shared_from_this() and pass it to listening parties with a signal. But the line boost::shared_ptr<foo> p = shared_from_this() throws an exception as follows;

```<code>boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_weak_ptr> > at memory location 0x04c2f720.
</code>```

The offending command is shared_from_this() . Is it illegal to create a shared_from_this() from another thread or am I doing something wrong ? Any help is appreciated. Thanks !

PS: I plan on changing my signal arguments to plain pointers as it wouldn't affect my structure. But I favor shared_ptr<> and I want to hear any comments about the decision. Maybe it's a bad choice for this particular situation. What do you suggest ?

EDIT:

Here is a simple class for you to test

```<code>class foo : public boost::enable_shared_from_this<foo>
{
public:
    int start()
    {
        foo_thread.reset(new boost::thread(boost::bind(&foo::fn_foo_thread, this)));

        return 0;
    }

    ~foo()
    {
        if (foo_thread->joinable())
            foo_thread->join();
    }

private:
    boost::scoped_ptr<boost::thread> foo_thread;

    void fn_foo_thread()
    {
        boost::shared_ptr<foo> p = shared_from_this();
        std::cout << "foo thread terminated. \n" << std::endl;
    }
};
</code>```

答: You may like to consider changing boost::shared_ptr<> to boost::intrusive_ptr<>. The main difference is that boost::intrusive_ptr<> suggests that the reference counter is stored inside the object (although it is possible to store it elsewhere). With embedded reference counter you can construct an boost::intrusive_ptr<> from this in constructor or from a plain pointer whenever you please (but don't take boost::intrusive_ptr<> from this in the destructor).

Body:
In my code I use boost::threads and I have a class that runs a thread via a member function called fnThread() . In this fnThread() I want to create a shared_from_this() and pass it to listening parties with a signal. But the line boost::shared_ptr<foo> p = shared_from_this() throws an exception as follows;

boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_weak_ptr> > at memory location 0x04c2f720.

The offending command is shared_from_this() . Is it illegal to create a shared_from_this() from another thread or am I doing something wrong ? Any help is appreciated. Thanks !

PS: I plan on changing my signal arguments to plain pointers as it wouldn't affect my structure. But I favor shared_ptr<> and I want to hear any comments about the decision. Maybe it's a bad choice for this particular situation. What do you suggest ?

EDIT:

Here is a simple class for you to test

class foo : public boost::enable_shared_from_this<foo>
{
public:
    int start()
    {
        foo_thread.reset(new boost::thread(boost::bind(&foo::fn_foo_thread, this)));

        return 0;
    }

    ~foo()
    {
        if (foo_thread->joinable())
            foo_thread->join();
    }

private:
    boost::scoped_ptr<boost::thread> foo_thread;

    void fn_foo_thread()
    {
        boost::shared_ptr<foo> p = shared_from_this();
        std::cout << "foo thread terminated. \n" << std::endl;
    }
};


问:
Matlab: How to unit test a Questdlg box?
I have this chunk of code which display a question box with three choices:

Yes

Save as

No

I just want to create a unit test for each of those choices, and I need to interact with the box for it.
When the box is created, every matlab process is frozen until the user react. Of course my tests are automated, and there's no user present.

Is there a solution to send a "Yes" event to Matlab ?
I could use autoit but I would rather avoid that

Thanks

答:
Currently, you're best bet is to structure your code to not depend on the questdlg function directly but to wrap an interface around the function so that you can inject a test specific dependency, or "mock". This might look something like the following:

Source Code Under Test

```<code>function codeWhichUsesQuestDlg(dlgProvider)
validateattributes(dlgProvider, {'DialogProvider'},{});

if (needToAskQuestion)
    result = dlgProvider.provideQuestionDialog(...)
else
    ...
end
</code>```

Source Code Interface/Infrastructure

```<code>classdef DialogProvider < handle
    methods(Abstract)
        result = provideQuestionDialog(varargin);
        % perhaps others? errordlg, etc?
    end
end
</code>```

Production Implementation

```<code>classdef ProductionProvider < DialogProvider
    methods
        function result = provideQuestionDialog(varargin)
            result = questdlg(varargin{:});
        end
    end
end
</code>```

Production Usage

```<code>>> codeWhichUsesQuestDlg(ProductionProvider)
</code>```

Test Usage

```<code>classdef TestCode < matlab.mock.TestCase

    methods(Test)
        function testCode(testCase)
            % Create the test specific "mock" implementation
            [mockProvider, behavior] = testCase.createMock(?DialogProvider);

            % Define mock behavior needed for the test
            when(withAnyInputs(behavior.provideQuestionDialog), ...
                AssignOutputs('Yes'));

            % Call code under test with the mock
            codeWhichUsesQuestDlg(mockProvider);

            % Verify correct result/behavior
            ...
        end
    end
end
</code>```

Take a look at the mocking framework to see more info. Also you might be interested in this post covering the mocking framework as well as this post on dependency injection.

Body:
Currently, you're best bet is to structure your code to not depend on the questdlg function directly but to wrap an interface around the function so that you can inject a test specific dependency, or "mock". This might look something like the following:

Source Code Under Test

function codeWhichUsesQuestDlg(dlgProvider)
validateattributes(dlgProvider, {'DialogProvider'},{});

if (needToAskQuestion)
    result = dlgProvider.provideQuestionDialog(...)
else
    ...
end

Source Code Interface/Infrastructure

classdef DialogProvider < handle
    methods(Abstract)
        result = provideQuestionDialog(varargin);
        % perhaps others? errordlg, etc?
    end
end

Production Implementation

classdef ProductionProvider < DialogProvider
    methods
        function result = provideQuestionDialog(varargin)
            result = questdlg(varargin{:});
        end
    end
end

Production Usage

>> codeWhichUsesQuestDlg(ProductionProvider)

Test Usage

classdef TestCode < matlab.mock.TestCase

    methods(Test)
        function testCode(testCase)
            % Create the test specific "mock" implementation
            [mockProvider, behavior] = testCase.createMock(?DialogProvider);

            % Define mock behavior needed for the test
            when(withAnyInputs(behavior.provideQuestionDialog), ...
                AssignOutputs('Yes'));

            % Call code under test with the mock
            codeWhichUsesQuestDlg(mockProvider);

            % Verify correct result/behavior
            ...
        end
    end
end

Take a look at the mocking framework to see more info. Also you might be interested in this post covering the mocking framework as well as this post on dependency injection.


问:
Writing coil (bit) to Modbus PLC
I’m having a problem writing to a Schneider Modicon M221 PLC.
I’m using a Swift wrapper around the LibModbus Library (in C).
I can read bits and registers no problem - just can’t seem to write to them - although I’m getting a “success” response from the device.

It’s as simple as writing “true” to bit 0 using function 05.

Swift(4) call:

```<code>@objc func writeToPLC() {

    swiftLibModbus.writeBit(address: 0, status: true,
                            success: {
                                    print("writeBit Success")

    },
                            failure: { (error:NSError) in
                                print("Error in WriteBit")

    })

}
</code>```

Which writes to this function in the Swift/ObjC SwiftLibModbus wrapper:

```<code>func writeBit(address: Int32, status: Bool, success: @escaping () -> Void, failure: @escaping (NSError) -> Void) {
    modbusQueue?.async {
        if modbus_write_bit(self.mb!, address, status ? 1 : 0) >= 0 {
            DispatchQueue.main.async {
                success()
            }
        } else {
            let error = self.buildNSError(errno: errno)
            DispatchQueue.main.async {
                failure(error)
            }
        }
    }
}
</code>```

That writes to these C functions in the library:

```<code>int modbus_write_bit(modbus_t *ctx, int addr, int status){
return write_single(ctx, _FC_WRITE_SINGLE_COIL, addr,
                    status ? 0xFF00 : 0);
}
</code>```

then:

```<code>static int write_single(modbus_t *ctx, int function, int addr, int value){
int rc;
int req_length;
uint8_t req[_MIN_REQ_LENGTH];

req_length = ctx->backend->build_request_basis(ctx, function, addr, value, req);

rc = send_msg(ctx, req, req_length);
if (rc > 0) {
    /* Used by write_bit and write_register */
    uint8_t rsp[_MIN_REQ_LENGTH];
    //printf("Print %s, %s, %d ", req, rsp, rc);
    rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
    if (rc == -1)
        return -1;

    rc = check_confirmation(ctx, req, rsp, rc);

}

return rc;}
</code>```

The _FC_WRITE_SINGLE_COIL constant is 0x05

The _MIN_REQ_LENGTH constant is 12

I get "writeBit Success" in the console when running, but the bit status remains the same.

Beginning to wonder if it’s something proprietary with Schneider.

Anyone else had experience in this area?

答:
Okay, so I found out what I was doing wrong. I didn't have the Unit ID set properly. It was at "1" when it should have been "255".

Here's a screenshot of the setting in SoMachine in case anyone else finds themselves in the same situation:

Title: Writing coil (bit) to Modbus PLC

Body:
I’m having a problem writing to a Schneider Modicon M221 PLC.
I’m using a Swift wrapper around the LibModbus Library (in C).
I can read bits and registers no problem - just can’t seem to write to them - although I’m getting a “success” response from the device.

It’s as simple as writing “true” to bit 0 using function 05.

Swift(4) call:

@objc func writeToPLC() {

    swiftLibModbus.writeBit(address: 0, status: true,
                            success: {
                                    print("writeBit Success")

    },
                            failure: { (error:NSError) in
                                print("Error in WriteBit")

    })

}

Which writes to this function in the Swift/ObjC SwiftLibModbus wrapper:

func writeBit(address: Int32, status: Bool, success: @escaping () -> Void, failure: @escaping (NSError) -> Void) {
    modbusQueue?.async {
        if modbus_write_bit(self.mb!, address, status ? 1 : 0) >= 0 {
            DispatchQueue.main.async {
                success()
            }
        } else {
            let error = self.buildNSError(errno: errno)
            DispatchQueue.main.async {
                failure(error)
            }
        }
    }
}

That writes to these C functions in the library:

int modbus_write_bit(modbus_t *ctx, int addr, int status){
return write_single(ctx, _FC_WRITE_SINGLE_COIL, addr,
                    status ? 0xFF00 : 0);
}

then:

static int write_single(modbus_t *ctx, int function, int addr, int value){
int rc;
int req_length;
uint8_t req[_MIN_REQ_LENGTH];

req_length = ctx->backend->build_request_basis(ctx, function, addr, value, req);

rc = send_msg(ctx, req, req_length);
if (rc > 0) {
    /* Used by write_bit and write_register */
    uint8_t rsp[_MIN_REQ_LENGTH];
    //printf("Print %s, %s, %d ", req, rsp, rc);
    rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
    if (rc == -1)
        return -1;

    rc = check_confirmation(ctx, req, rsp, rc);

}

return rc;}

The _FC_WRITE_SINGLE_COIL constant is 0x05

The _MIN_REQ_LENGTH constant is 12

I get "writeBit Success" in the console when running, but the bit status remains the same.

Beginning to wonder if it’s something proprietary with Schneider.

Anyone else had experience in this area?


问:
Updating vs Overwriting items from Staging Tables in DynamoDB
I have a table of aggregated data in DynamoDB that is populated from quality-checked data from staging_table.

I have several scripts that perform a scan in staging_table (all items), do some sort of calculation or verification and potentially need to insert/update an attribute from those staging items, before finally transferring them to the actual table. Note that this full scan happens various times, because each quality check procedure is independent from the others, but they happen in parallel.

What set of DynamoDB operations are best used here in terms of cost and performance? More objectively, the initial alternatives I thought of are:

Use batch item writes to overwrite the old versions of the data (because PutItem is the only batch operation available)

Use sequential UpdateItem operations (many more API calls, but each one less expensive)

Is there a better way? Is this scenario just not a good fit for DynamoDB?

答:
I think your solution will depend on what is important to you;

The monetary cost of your operation

Latency between data hitting your staging table and being available in the main table

Simplicity

BatchWriteItem consumes the same number of write capacity units as PutItem and UpdateItem, so the monetary cost is the same.

BatchWriteItem should reduce latency between your staging table and main table (compared to PutItem or UpdateItem), but it comes at the cost of simplicity as you cannot have more than 25 items in your batch, each item cannot be more then 400KB, and the total batch cannot be more than 16MB. So you have a little more code to write. If you are hitting these limits you can create smaller batches, or consider writing your own parallel threading model with PutItem or UpdateItem.

You can potentially decrease latency by increasing your table RCUs and WCUs. You would need to optimise these for your particular operation between the two tables.

Minimising your writing time is only likely to be important if it is significant compared to your read/analysis time though. If it takes one minute to do your Scan and one second to do subsequent writes with UpdateItem, there is very little point in using batchwriteitem.

I would suggest you will see little or no difference between PutItem or UpdateItem. They consume the same number of WCUs so assuming you are throughput limited, there will be no difference.

One thing to consider is that Scan is not read consistent by default, meaning the table may change between the start and end of the Scan. Depending on your quality scans, you may want to set ConsistentRead to true.

I think ideally you would prototype the process using the most simple approach, and then analyse the solution to see which bits take significant time. You can then look to optimise those parts of the process.


问:
escape hidden character that is causing JSON validation to fail
I have a hidden character that is causing JSON parsing to fail. What is the best way to escape a string properly just that hidden characters like these done crash my json?

Here is the code, the invisible character is between the n and the s in "brains" until you remove that invisible character JSON.parse() will fail... question is, how to strip the invisible character?

```<code>var mystring='{"invis":"their brains process differently"}';
console.log("cool" + mystring);
console.log(JSON.parse(mystring));
</code>```

Note I found that in the above code actually removed the invisible character, but it is here on pastie, if you want to copy and paste to see the issue:
See the code on pastie

答:
I found another JSON parser that doesnt crash with these hidden characters, it is located here:

https://github.com/douglascrockford/JSON-js

Body:
I have a hidden character that is causing JSON parsing to fail. What is the best way to escape a string properly just that hidden characters like these done crash my json?

Here is the code, the invisible character is between the n and the s in "brains" until you remove that invisible character JSON.parse() will fail... question is, how to strip the invisible character?

var mystring='{"invis":"their brains process differently"}';
console.log("cool" + mystring);
console.log(JSON.parse(mystring));

Note I found that in the above code actually removed the invisible character, but it is here on pastie, if you want to copy and paste to see the issue:
See the code on pastie


问:
Angular 2/4 template cache-busting is not working
We have a Problem with our Angular 4 application regarding cache-busting.
It seems, that old template-files are cached when we release new versions (Ctrl + F5 solves the problem).

We use angular-cli (--prod) to build our application which should handle cache-busting when new versions are released. The compiled js-file-names contain a hash-number for every version so that files won't be cached. And the html should be included in the javascript-files. Still old template-stuff seems to be cached.

One possible solution might be this one here: How to prevent Browser cache on Angular 2 site?
Why should this change anything as not the template but js-files are requested?
What's the best solution for this problem`?

答:
The solution was to set cache-expires header for the index.html file in our amazon S3-bucket.

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html#ExpirationAddingHeadersInS3


问:
How to handle invalid cast from Observable Collection to Generic LIst
I am trying delete from a Gridview.

```<code>if (this.gridView.SelectedItems.Count == 0)
{
    return;
}

ObservableCollection<Query> itemsToRemove = new ObservableCollection<Query>();

foreach (Query item in this.gridView.SelectedItems)
{
    itemsToRemove.Add(item);
}

foreach (Query item in itemsToRemove)
{
    //this line causes the invalid cast
    ((ObservableCollection<Query>)this.gridView.ItemsSource).Remove(item as Query);

    Code = item.CODE;
}
</code>```

Removal of items from the Gridview

Invalid cast exception
Unable to cast object of type
'System.Collections.Generic.List1[Inventory.Query]' to type 'System.Collections.ObjectModel.ObservableCollection1[Inventory.Query]'.

答:
You are adding Query items to itemsToRemove but you should remove them from the ItemsSource collection which apparently is a List<Query>.

This should work:

```<code>var items = this.gridView.ItemsSource as List<Query>;
foreach (Query item in itemsToRemove)
{
    if(items.Contains(item))
        items.Remove(item);

    Code = item.CODE;
    this.gridView.ItemsSource = items;
}
</code>```

Note that you will have to re-assign the ItemsSource property since a List<T> doesn't raise any notifications when items are added or removed.

Body:
I am trying delete from a Gridview.

if (this.gridView.SelectedItems.Count == 0)
{
    return;
}

ObservableCollection<Query> itemsToRemove = new ObservableCollection<Query>();

foreach (Query item in this.gridView.SelectedItems)
{
    itemsToRemove.Add(item);
}

foreach (Query item in itemsToRemove)
{
    //this line causes the invalid cast
    ((ObservableCollection<Query>)this.gridView.ItemsSource).Remove(item as Query);

    Code = item.CODE;
}

Removal of items from the Gridview

Invalid cast exception
Unable to cast object of type
'System.Collections.Generic.List1[Inventory.Query]' to type 'System.Collections.ObjectModel.ObservableCollection1[Inventory.Query]'.

Body:
You are adding Query items to itemsToRemove but you should remove them from the ItemsSource collection which apparently is a List<Query>.

This should work:

var items = this.gridView.ItemsSource as List<Query>;
foreach (Query item in itemsToRemove)
{
    if(items.Contains(item))
        items.Remove(item);

    Code = item.CODE;
    this.gridView.ItemsSource = items;
}

Note that you will have to re-assign the ItemsSource property since a List<T> doesn't raise any notifications when items are added or removed.


问:
Docker compose not persisting data
I have the following docker-compose.yml file:

```<code>version: '2'
services:
  web:
    image: myspringapp:1
    ports:
      - "8080:8080"
    depends_on:
      - myspringapp_postgres
  myspringapp_postgres:
    image: postgres:9.4
    ports:
      - "5432:5432"
    volumes:
      - ./pgdata:/var/lib/postgresql/data
volumes:
  pgdata: {}
</code>```

myspringapp is a docker image I build previously. The problem with this is that the data is lost after doing a docker-compose stop.  Anyone know what the problem is?

答:
Looks like you're defining a volume, but specifying a bind-mount to be used.

The different here, is a volume is actually it's own isolated "drive" in a sense, where a bind-mount needs to map to a specific file path on your local system.

If you check in your local ./pgdata directory, you should find all your previous data; and to fix your issue you'll want to remove the ./ from that and just specify the name pgdata so that it uses the volume as defined. Of course, this will start you fresh again.

compose-file.yml

```<code>version: '2'
services:
  web:
    image: myspringapp:1
    ports:
      - "8080:8080"
    depends_on:
      - myspringapp_postgres

  myspringapp_postgres:
    image: postgres:9.4
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
volumes:
  pgdata: {}
</code>```

Title: Docker compose not persisting data

Body:
I have the following docker-compose.yml file:

version: '2'
services:
  web:
    image: myspringapp:1
    ports:
      - "8080:8080"
    depends_on:
      - myspringapp_postgres
  myspringapp_postgres:
    image: postgres:9.4
    ports:
      - "5432:5432"
    volumes:
      - ./pgdata:/var/lib/postgresql/data
volumes:
  pgdata: {}

myspringapp is a docker image I build previously. The problem with this is that the data is lost after doing a docker-compose stop.  Anyone know what the problem is?

Body:
Looks like you're defining a volume, but specifying a bind-mount to be used.

The different here, is a volume is actually it's own isolated "drive" in a sense, where a bind-mount needs to map to a specific file path on your local system.

If you check in your local ./pgdata directory, you should find all your previous data; and to fix your issue you'll want to remove the ./ from that and just specify the name pgdata so that it uses the volume as defined. Of course, this will start you fresh again.

compose-file.yml

version: '2'
services:
  web:
    image: myspringapp:1
    ports:
      - "8080:8080"
    depends_on:
      - myspringapp_postgres

  myspringapp_postgres:
    image: postgres:9.4
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
volumes:
  pgdata: {}


问:
How to count the number of steel rods in a video
I need to count the number of steel rods , in Python using opencv for the following image.

Image with the steel rods at the center
I have initially converted the image to grayscale,then used erode function followed with canny edge function to detect the edges as shown below.
image after canny edge
Later find contours and used bounding rotated rectangle to count the rods.  I am not able to get the correct count.

```<code>kernel = np.ones((4,4),np.uint8)
erosion = cv2.erode(gray,kernel,iterations = 1)
cv2.imshow('Erode',erosion)
canny=cv2.Canny(erosion,100,200)
cv2.imshow('Canny',canny)
kernele=np.array([[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]],np.uint8)
dilation = cv2.dilate(canny,kernele,iterations = 1)
cv2.imshow('dilate',dilation)
c,cnt,h=cv2.findContours(dilation,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
if cnt:
    i=0
    for cnt in contours:
        rect = cv2.minAreaRect(cnt)
        box = cv2.boxPoints(rect)
        box = np.int0(box)
        if rect[1][0]>1 and rect[1][0]<15:  #width of rod
           i+=1
</code>```

Kindly suggest what to modify or how to get the count.
Thank You

Next Image

答:
Instead of finding edges and then going by width, there is this alternative way that you can try.

I assume your image setup is constant and hence you can crop the region containing the rods (it would be very difficult otherwise).

Adaptive threshold the image with appropriate size and constant.

Then choose 100 random rows in the image and count the number of black or white strips in it.

Find the median of these 100 rows and subtract an appropriate condition to eliminate the wrong border counts (the white strip before the first rod and after the last rod)

Code:

```<code>import cv2
import numpy as np
from random import randint
from itertools import groupby

img = cv2.imread('img.jpg',0)
rod_count = []
rows, cols =img.shape[:2]
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
                    cv2.THRESH_BINARY,11, 2)

count = 100
while( count!=0 ):

    count = count-1
    random_row = randint(0, rows-1)

    arr = th2[random_row:random_row+1, :]
    arr2 = np.array(arr)[0].tolist()
    temp = [a[0] for a in groupby(arr2)]
    b = sum(x == 0 for x in temp)
    rod_count.append(b)

print np.median(rod_count)-2
</code>```

Output: 15

Body:
I need to count the number of steel rods , in Python using opencv for the following image.

Image with the steel rods at the center
I have initially converted the image to grayscale,then used erode function followed with canny edge function to detect the edges as shown below.
image after canny edge
Later find contours and used bounding rotated rectangle to count the rods.  I am not able to get the correct count.

kernel = np.ones((4,4),np.uint8)
erosion = cv2.erode(gray,kernel,iterations = 1)
cv2.imshow('Erode',erosion)
canny=cv2.Canny(erosion,100,200)
cv2.imshow('Canny',canny)
kernele=np.array([[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]],np.uint8)
dilation = cv2.dilate(canny,kernele,iterations = 1)
cv2.imshow('dilate',dilation)
c,cnt,h=cv2.findContours(dilation,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
if cnt:
    i=0
    for cnt in contours:
        rect = cv2.minAreaRect(cnt)
        box = cv2.boxPoints(rect)
        box = np.int0(box)
        if rect[1][0]>1 and rect[1][0]<15:  #width of rod
           i+=1

Kindly suggest what to modify or how to get the count.
Thank You

Next Image

Body:
Instead of finding edges and then going by width, there is this alternative way that you can try.

I assume your image setup is constant and hence you can crop the region containing the rods (it would be very difficult otherwise).

Adaptive threshold the image with appropriate size and constant.

Then choose 100 random rows in the image and count the number of black or white strips in it.

Find the median of these 100 rows and subtract an appropriate condition to eliminate the wrong border counts (the white strip before the first rod and after the last rod)

Code:

import cv2
import numpy as np
from random import randint
from itertools import groupby

img = cv2.imread('img.jpg',0)
rod_count = []
rows, cols =img.shape[:2]
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
                    cv2.THRESH_BINARY,11, 2)

count = 100
while( count!=0 ):

    count = count-1
    random_row = randint(0, rows-1)

    arr = th2[random_row:random_row+1, :]
    arr2 = np.array(arr)[0].tolist()
    temp = [a[0] for a in groupby(arr2)]
    b = sum(x == 0 for x in temp)
    rod_count.append(b)

print np.median(rod_count)-2

Output: 15


问:
Contributing to a GIT repository
The author of a repository on Github asked for contribution on his project by translating some language files. I tried to collaborate by doing the following steps:

Clone the repository and make a Pull

Create a branch "German_locale"

Made changes to language files

commit while adding a message

Push branch to origin (failed)

Intended final step: pull request on Github website

However, the 5. action fails. It asks for Username /Password and doesn't give me access if I'm providing my personal. I think, the system tries to verify me as the original author, which I am not.

The very basic questions are (sorry, I'm new):

What do I have to do in order to push a branch to a foreign repository? Do I have to ask for being a collaborator first? This doesn't seem right.

Would it be a better idea to create a fork in the first place? This doesn't seem right, either.

I'm using SmartGit as a client, so please describe the solution rather then providing command lines. I really want to understand how that works. I have seen other contributors translating other language files on this project successfully but have no idea how that works in general.

答:
As for github, there is another way to contribute.

Fork the original repo. This will create the same repository in your github account with reference to original. Now you have your own repository, so there will be no push fails.

Do your changes, commit and push them to your fork.

Navigate to github.com and create a pull request, so the author of the original repo can review and accept (or decline) your contribution.

Git official tutorial

Title: Contributing to a GIT repository


问:
Is it possible to customise Dynamics 365? Web Design?
Is it possible to edit Dynamics 365 in a way to change how certain entities look when they are opened. I don't mean forms, apps or views. I want to be able to change how the accounts entity looks, such as; a smaller view box, the location of the search bar and additional helpful information from other entities.

I simple would like to know if this is possible to achieve with Dynamics 365?

I can supply more info of what I would like to do if it helps to answer my question.

Cheers.

答:
UI wise you can control the following:

Form layout, i.e. what fields appear and where.

You can include data from related entities (associated record grids, and quick view forms).

Colours, using branding.

Size of text boxes.

You can't change:

The location of the search bar.

Not sure what a "a smaller view box" would be, but you might be able to achieve something similar by changing the form layout.


问:
How to update every value of the keyset in a LinkedHashMap in Scala, having a LinkedHashMap[Int, ListBuffer[Int]]?
I have a LinkedHashMap of type:

```<code>var map: LinkedHashMap[Int, ListBuffer[Int]] = ((1 -> (2, 1)), (2 -> 2), (3 -> (5, 3)))
</code>```

I want to add an element to every list of every key, let's say i want to add "6" in order to have:

```<code>((1 -> (6, 2, 1)), (2 -> (6, 2)), (3 -> (6, 5, 3)))
</code>```

How do i do this?

答:
Like this:

```<code>val map: mutable.LinkedHashMap[Int, ListBuffer[Int]] =
  mutable.LinkedHashMap(1 -> ListBuffer(2, 1),
                        2 -> ListBuffer(2, 2),
                        3 -> ListBuffer(5, 3))

val res = map.mapValues(lstBuffer => lstBuffer += 6)
println(res)
</code>```

Yields:

```<code>Map(1 -> ListBuffer(2, 1, 6), 2 -> ListBuffer(2, 2, 6), 3 -> ListBuffer(5, 3, 6))
</code>```

Note that mapValues is lazy and won't execute unless materialized. If we want to make this strict and execute immediately, we can use map:

```<code>val res = map.map { case (_, lstBuffer) => lstBuffer += 6 }
</code>```

If you want to prepend, use .prepend instead (which returns Unit and is side effecting on the current Map instance):

```<code>map.foreach { case (_, lstBuffer) => lstBuffer.prepend(6) }
</code>```

I want to note that usually, if you want to iterate the entire Map[K, V] sequentially, it's a sign you're using the wrong data structure. Although without more information I can't really establish a basis for that hypothesis.

Body:
I have a LinkedHashMap of type:

var map: LinkedHashMap[Int, ListBuffer[Int]] = ((1 -> (2, 1)), (2 -> 2), (3 -> (5, 3)))

I want to add an element to every list of every key, let's say i want to add "6" in order to have:

((1 -> (6, 2, 1)), (2 -> (6, 2)), (3 -> (6, 5, 3)))

How do i do this?

Body:
Like this:

val map: mutable.LinkedHashMap[Int, ListBuffer[Int]] =
  mutable.LinkedHashMap(1 -> ListBuffer(2, 1),
                        2 -> ListBuffer(2, 2),
                        3 -> ListBuffer(5, 3))

val res = map.mapValues(lstBuffer => lstBuffer += 6)
println(res)

Yields:

Map(1 -> ListBuffer(2, 1, 6), 2 -> ListBuffer(2, 2, 6), 3 -> ListBuffer(5, 3, 6))

Note that mapValues is lazy and won't execute unless materialized. If we want to make this strict and execute immediately, we can use map:

val res = map.map { case (_, lstBuffer) => lstBuffer += 6 }

If you want to prepend, use .prepend instead (which returns Unit and is side effecting on the current Map instance):

map.foreach { case (_, lstBuffer) => lstBuffer.prepend(6) }

I want to note that usually, if you want to iterate the entire Map[K, V] sequentially, it's a sign you're using the wrong data structure. Although without more information I can't really establish a basis for that hypothesis.


问:
How to populate dropdown menu from sql table in PHP
I tried inserting this into my code to generate a dropdown menu through an sql table but it responds with nothing in the dropdown. When I execute the sql query it doesn't show any error as well. Please be kind enough to fix my error. Thank you</p>

```<code> <?php
            $db = mysqli_connect('localhost', 'root', '', 'registration');
            $sql = "Select (unitid) from unit where (unitname)=
('$unitname')";
            mysqli_query($db, $sql);

            echo "<select name='unitid'>";
            while ($row = mysql_fetch_array($sql)) {
               echo "<option value='" .$row['unitid']."'> ".$row['unitname'] . "</option>";
            }
            echo "</select>";
            ?>
</code>```

答:
Try saving the result of mysqli_query:

```<code>$result = mysqli_query($db, $sql);
</code>```

And then using it in the while condition:

```<code>while ($row = mysqli_fetch_array($result)) {
</code>```

The select should be also "Select unitid, unitname ..." to return also the unitname used in the options:

```<code>$sql = "SELECT unitid, unitname FROM unit WHERE unitname = '$unitname'";
</code>```

And you should use prepared statements if you want to prevent it from SQL injection attacks.

If you want all the units to be shown on the combo change the select to:

```<code>$sql = "SELECT unitid, unitname FROM unit";
</code>```

So, the code should be now:

```<code> <?php
        $db = mysqli_connect('localhost', 'root', '', 'registration');
        $sql = "Select unitid, unitname from unit";
        $result = mysqli_query($db, $sql);

        echo "<select name='unitid'>";
        while ($row = mysqli_fetch_array($result)) {
           echo "<option value='" .$row['unitid']."'> ".$row['unitname'] . "</option>";
        }
        echo "</select>";
 ?>
</code>```

Body:
I tried inserting this into my code to generate a dropdown menu through an sql table but it responds with nothing in the dropdown. When I execute the sql query it doesn't show any error as well. Please be kind enough to fix my error. Thank you

 <?php
            $db = mysqli_connect('localhost', 'root', '', 'registration');
            $sql = "Select (unitid) from unit where (unitname)=
('$unitname')";
            mysqli_query($db, $sql);

            echo "<select name='unitid'>";
            while ($row = mysql_fetch_array($sql)) {
               echo "<option value='" .$row['unitid']."'> ".$row['unitname'] . "</option>";
            }
            echo "</select>";
            ?>

Body:
Try saving the result of mysqli_query:

$result = mysqli_query($db, $sql);

And then using it in the while condition:

while ($row = mysqli_fetch_array($result)) {

The select should be also "Select unitid, unitname ..." to return also the unitname used in the options:

$sql = "SELECT unitid, unitname FROM unit WHERE unitname = '$unitname'";

And you should use prepared statements if you want to prevent it from SQL injection attacks.

If you want all the units to be shown on the combo change the select to:

$sql = "SELECT unitid, unitname FROM unit";

So, the code should be now:

 <?php
        $db = mysqli_connect('localhost', 'root', '', 'registration');
        $sql = "Select unitid, unitname from unit";
        $result = mysqli_query($db, $sql);

        echo "<select name='unitid'>";
        while ($row = mysqli_fetch_array($result)) {
           echo "<option value='" .$row['unitid']."'> ".$row['unitname'] . "</option>";
        }
        echo "</select>";
 ?>


问:
fastest way to match fingerprints?
I am trying to check whether a fingerprint exists/matches in a huge collection of fingerprints (100,000 fingerprints). It will take more time to search for matches sequentially. is there any better way to search for match? is it possible to organize the fingerprints in a binary tree structure so that the number of comparisons can be reduced? if yes how can we do it? it would be helpful if the answers are in Java perspective.

edit:

I have all the fingerprints as .gif images. how can i convert the finger print images into data?

Thanks.

答:
This is not my field of expertise (I'm a web developer), but I think you should look into neural networks. I downloaded some demo code once and did some experimenting with character recognition. It was amazing to see how the neural network that I had setup could recognize characters that I drew on the screen. But before it could do this, it first had to learn (backpropagation learning).

Here's a slideshow that provides an outline:
http://www.slideshare.net/alessandrobaffa/fingerprints-recognition-using-neural-networks

The last slide contains further references.

Good luck!

/Thomas Kahn

Title: fastest way to match fingerprints?


问:
Searching for a string of text in a specific worksheet
Im trying to make excel search for a text string in a specific column in a specific worksheet that is not the active worksheet. VBA gives me an error that says i cannot use this method of selection. so my question is, do you have a suggestion to do it in another way?</p>

```<code>Worksheets("Parts for renovation").Columns("Q:Q").Select
Set cell = Selection.Find(What:="Total transfer price", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If cell Is Nothing Then

    Exit Sub

Else

    Worksheets("Internal").Cells(29, 4) = Worksheets("Parts for Renovation").ActiveCell.Offset(0, 4)

End If
</code>```

答:
There is no need to select anything there:</p>

```<code>With Worksheets("Parts for renovation").Columns("Q:Q")
    Set cell = .Find(What:="Total transfer price", After:=.Cells(1), LookIn:=xlFormulas, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)
    If cell Is Nothing Then
        Exit Sub
    Else
        Worksheets("Internal").Cells(29, 4) = Cell.Offset(0, 4)
    End If
End With
</code>```

Body:
Im trying to make excel search for a text string in a specific column in a specific worksheet that is not the active worksheet. VBA gives me an error that says i cannot use this method of selection. so my question is, do you have a suggestion to do it in another way?

Worksheets("Parts for renovation").Columns("Q:Q").Select
Set cell = Selection.Find(What:="Total transfer price", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If cell Is Nothing Then

    Exit Sub

Else

    Worksheets("Internal").Cells(29, 4) = Worksheets("Parts for Renovation").ActiveCell.Offset(0, 4)

End If

Body:
There is no need to select anything there:

With Worksheets("Parts for renovation").Columns("Q:Q")
    Set cell = .Find(What:="Total transfer price", After:=.Cells(1), LookIn:=xlFormulas, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)
    If cell Is Nothing Then
        Exit Sub
    Else
        Worksheets("Internal").Cells(29, 4) = Cell.Offset(0, 4)
    End If
End With


问:
Multiple {n} quantifiers regex
Is it possible to have multiple quantifiers in a regex?
Say I have the following regex:

[A-Z0-9]{44}|[A-Z0-9]{36}|[A-Z0-9]{30}

I want to match any string which is either 30, 36 or 44 chars long. Is it possible to write this shorter in any way? Something like the following:

[A-Z0-9<]{30|36|44}?

Edit: Seeing the answers I assume there is not really a way in which you can write the above shorter. The best solution would be to solve it programmatically I guess. Thanks for the input.

答:
Looks like you want

```<code>[A-Z0-9]{30}([A-Z0-9]{6}([A-Z0-9]{8})?)?
</code>```

This isn't actually simpler, mind you.

Title: Multiple {n} quantifiers regex

Body:
Looks like you want

[A-Z0-9]{30}([A-Z0-9]{6}([A-Z0-9]{8})?)?

This isn't actually simpler, mind you.


问:
Overlay on top of tbody
I am trying to create a loading overlay on top of tbody (and only tbody). My current solution is to add tr as the last element of tbody and set it as position: absolute, and setting tbody as position: relative.

table {
  width: 100%;
}

tbody {
  position: relative;
}

.overlay {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(200, 200, 200, 0.7);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>Label</tr>
  </thead>
  <tbody>
    <tr><td>Data</td></tr>
    <tr><td>Data</td></tr>
    <tr class="overlay">
      <td>My overlay</td>
    </tr>
  </tbody>
</table></code>```

Expected behavior is that an overlay covers tbody, but not thead. Also this overlay is supposed to contain some content (f.e. refresh button) so covering every td is not an option.

My solution works perfectly in Firefox, but not webkit. Webkit somehow ignores position: relative on tbody tag and thus the overlay covers the whole table and more.

RESOLVED
I have managed to make this approach work by adding display: table on tbody

答:
Using CSS calc should help with this. Support is fairly good for the property too.

You just need to balance the calc with the top property.

So your CSS would become:

```<code>table {
  width: 100%;
  position: relative;
}

.overlay {
  position: absolute;
  top: 25px;
  width: 100%;
  height: -webkit-calc(100% - 25px);
  height: calc(100% - 25px);
  background-color: rgba(200, 200, 200, 0.7);
}
</code>```

Here's a working example:

table {
  width: 100%;
  position: relative;
}

.overlay {
  position: absolute;
  top: 25px;
  width: 100%;
  height: -webkit-calc(100% - 25px);
  height: calc(100% - 25px);
  background-color: rgba(200, 200, 200, 0.7);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr><td>Label</td></tr>
  </thead>
  <tbody>
    <tr><td>Data</td></tr>
    <tr><td>Data</td></tr>
    <tr class="overlay">
      <td>My overlay</td>
    </tr>
  </tbody>
</table></code>```

Updated answer using CSS Calc.

Title: Overlay on top of tbody

Body:
I am trying to create a loading overlay on top of tbody (and only tbody). My current solution is to add tr as the last element of tbody and set it as position: absolute, and setting tbody as position: relative.

table {
  width: 100%;
}

tbody {
  position: relative;
}

.overlay {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(200, 200, 200, 0.7);
}

Label

Data

Data

      My overlay

Expected behavior is that an overlay covers tbody, but not thead. Also this overlay is supposed to contain some content (f.e. refresh button) so covering every td is not an option.

My solution works perfectly in Firefox, but not webkit. Webkit somehow ignores position: relative on tbody tag and thus the overlay covers the whole table and more.

RESOLVED
I have managed to make this approach work by adding display: table on tbody

Body:
Using CSS calc should help with this. Support is fairly good for the property too.

You just need to balance the calc with the top property.

So your CSS would become:

table {
  width: 100%;
  position: relative;
}

.overlay {
  position: absolute;
  top: 25px;
  width: 100%;
  height: -webkit-calc(100% - 25px);
  height: calc(100% - 25px);
  background-color: rgba(200, 200, 200, 0.7);
}

Here's a working example:

table {
  width: 100%;
  position: relative;
}

.overlay {
  position: absolute;
  top: 25px;
  width: 100%;
  height: -webkit-calc(100% - 25px);
  height: calc(100% - 25px);
  background-color: rgba(200, 200, 200, 0.7);
}

<table>
  <thead>
    <tr><td>Label</td></tr>
  </thead>
  <tbody>
    <tr><td>Data</td></tr>
    <tr><td>Data</td></tr>
    <tr class="overlay">
      <td>My overlay</td>
    </tr>
  </tbody>
</table>

Updated answer using CSS Calc.


问:
CoinDaemon fails to bind address
When I run my coin daemon on my computer, I get this error:

20: 56: 42.149854 ERROR Exception: TcpListener :: TcpListener, bind failed, result = 98, Address already in use

although when running the same on the Amazon server it works fine. I do not even know what to do to help someone is not difficult.

答:
If this is a Linux like OS, try something like:

netstat -tulpn

It will show you what application is using what port. Identify the app that's using the port you want and stop it.

Title: CoinDaemon fails to bind address


问:
Spring Boot programmatically restart app
I'm developing a Spring Boot app, in which I need to write Java code to shut down the app itself (including its threads), and then restart it. I've tried the following two methods, the first one is to issue a Linux command in Java like the following:

```<code>Process p = Runtime.getRuntime().exec("kill -SIGINT " + pid);
</code>```

where pid is that of the app itself. This has the same effect as pressing "ctrl + c". But having shut down the app successfully this way, I don't know how I can restart it. I tried to issue another command (like "mvn spring-boot:run", which is how I start the app) using the same method but since the app is shut down already, this doesn't work.

Secondly, I've also tried calling the refresh() method of AbstractApplicationContext as follows:

```<code>AbstractApplicationContext appContext = new AnnotationConfigApplicationContext();
appContext.registerShutdownHook();
appContext.refresh();
</code>```

But I don't think this kind of context refreshing is the same as restarting?

So what is the proper way to restart a Spring Boot app with Java code? Any help is appreciated, thanks!

答:
Addition to Darshan Mehta answer:

In  my case I did this:

1.added dependecies:

```<code>compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.cloud:spring-cloud-starter:1.2.4.RELEASE")
</code>```

2.autowired restartEndpoint:

```<code>import org.springframework.cloud.context.restart.RestartEndpoint;
....
@Autowired
private RestartEndpoint restartEndpoint;
</code>```

3. and invoke:

```<code>Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        restartEndpoint.invoke();
    }
});
thread.setDaemon(false);
thread.start();
</code>```

I need new Thread because spring mvc creates daemon threads for each request

Body:
I'm developing a Spring Boot app, in which I need to write Java code to shut down the app itself (including its threads), and then restart it. I've tried the following two methods, the first one is to issue a Linux command in Java like the following:

Process p = Runtime.getRuntime().exec("kill -SIGINT " + pid);

where pid is that of the app itself. This has the same effect as pressing "ctrl + c". But having shut down the app successfully this way, I don't know how I can restart it. I tried to issue another command (like "mvn spring-boot:run", which is how I start the app) using the same method but since the app is shut down already, this doesn't work.

Secondly, I've also tried calling the refresh() method of AbstractApplicationContext as follows:

AbstractApplicationContext appContext = new AnnotationConfigApplicationContext();
appContext.registerShutdownHook();
appContext.refresh();

But I don't think this kind of context refreshing is the same as restarting?

So what is the proper way to restart a Spring Boot app with Java code? Any help is appreciated, thanks!

Body:
Addition to Darshan Mehta answer:

In  my case I did this:

1.added dependecies:

compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.cloud:spring-cloud-starter:1.2.4.RELEASE")

2.autowired restartEndpoint:

import org.springframework.cloud.context.restart.RestartEndpoint;
....
@Autowired
private RestartEndpoint restartEndpoint;

3. and invoke:

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        restartEndpoint.invoke();
    }
});
thread.setDaemon(false);
thread.start();

I need new Thread because spring mvc creates daemon threads for each request


问:
Adding a variable into the path of an image

I am trying to make my client program show an image with a name corresponding to the message received from a server.

So if the client receives b'red' it should display the image on the path: "/home/pi/Desktop/gifs/red.gif"

Here is the code for the client program:

```<code>import socket
import tkinter as tk
HOST = 'localhost'    # The remote host
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

message = s.recv(1024)
print(message) # Message is a bytes-like-object e.g. b'red'

root = tk.Tk()
image1 = tk.PhotoImage(file="/home/pi/Desktop/gifs/x.gif")
#x should change accordingly to the received message
Thelabel = tk.Label(image=image1)
Thelabel.pack()
root.update()
</code>```

How do I make a variable in the path to my image which takes the information in message? So I guess the bytes-like-object has to be decoded into a string?

答:
Based on @CommonSense comment to the question.        </p>

```<code>    byte_string = s.recv(1024)
    path = '/home/pi/Desktop/gifs/%s.gif' % byte_string.decode()

    root = tk.Tk()
    image1 = tk.PhotoImage(file=path)
    Thelabel = tk.Label(image=image1)
    Thelabel.pack()
    root.update()
</code>```

Body:
I am trying to make my client program show an image with a name corresponding to the message received from a server.

So if the client receives b'red' it should display the image on the path: "/home/pi/Desktop/gifs/red.gif"

Here is the code for the client program:

import socket
import tkinter as tk
HOST = 'localhost'    # The remote host
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

message = s.recv(1024)
print(message) # Message is a bytes-like-object e.g. b'red'

root = tk.Tk()
image1 = tk.PhotoImage(file="/home/pi/Desktop/gifs/x.gif")
#x should change accordingly to the received message
Thelabel = tk.Label(image=image1)
Thelabel.pack()
root.update()

How do I make a variable in the path to my image which takes the information in message? So I guess the bytes-like-object has to be decoded into a string?

Body:
Based on @CommonSense comment to the question.

    byte_string = s.recv(1024)
    path = '/home/pi/Desktop/gifs/%s.gif' % byte_string.decode()

    root = tk.Tk()
    image1 = tk.PhotoImage(file=path)
    Thelabel = tk.Label(image=image1)
    Thelabel.pack()
    root.update()


问:
How to display user input variables in single quotes in Python
I am trying to display user input data in single quotes, but something seems to be going wrong. Can you please help.

For eg:

```<code>name1 = raw_input()
print "[{0}]". format ("'"+ "','".join (str(i) for i in [name1] + "'")
</code>```

However it's working as below:

```
Input-
Jan, Feb
Actual output- ['Jan,Feb']
Expected output- ['Jan','Feb']
```

Can anyone please help

答:
Would the unholy use of print and repr help here?</p>

```<code>>>> name1 = input()
[1, 2, '3', 'four']
>>> print(repr(name1))
"[1, 2, '3', 'four']"
</code>```

Body:
I am trying to display user input data in single quotes, but something seems to be going wrong. Can you please help.

For eg:

name1 = raw_input()
print "[{0}]". format ("'"+ "','".join (str(i) for i in [name1] + "'")

However it's working as below:

Input-
Jan, Feb
Actual output- ['Jan,Feb']
Expected output- ['Jan','Feb']

Can anyone please help

Body:
Would the unholy use of print and repr help here?

>>> name1 = input()
[1, 2, '3', 'four']
>>> print(repr(name1))
"[1, 2, '3', 'four']"


问:
Get another row's data from same table
I have a categories table:

```<code>| cat_id | cat_name | cat_desc | child_cat
</code>```

What I want to accomplish is to get the cat name of child_cat if it exists.

sample data:

```<code>| cat_id | cat_name | cat_desc | child_cat
    1        test      testd       0
    2        test2     testd2      1
</code>```

When I get the info of cat_id = 2, I also want to get the cat_name of child_cat.

Expected output:

```<code>| cat_id | cat_name | cat_desc | child_cat_name
    1        test2     testd2        test
</code>```

Which method should I use?

答:
As in the comments, join the table with itself using a left join to not strip the categories that do not have a child.

```<code>SELECT t1.cat_id, t1.cat_name, t1.cat_desc, t2.cat_name as child_cat_name
FROM categories t1
LEFT JOIN categories t2 on t1.child_cat = t2.cat_id;
</code>```

As Juan correctly points out, the aliases t1 and t2 need to be set since we are joining the same table twice and need to tell the SQL engine somehow to distinguish between the tables.

Title: Get another row's data from same table

Body:
I have a categories table:

| cat_id | cat_name | cat_desc | child_cat

What I want to accomplish is to get the cat name of child_cat if it exists.

sample data:

| cat_id | cat_name | cat_desc | child_cat
    1        test      testd       0
    2        test2     testd2      1

When I get the info of cat_id = 2, I also want to get the cat_name of child_cat.

Expected output:

| cat_id | cat_name | cat_desc | child_cat_name
    1        test2     testd2        test

Which method should I use?

Body:
As in the comments, join the table with itself using a left join to not strip the categories that do not have a child.

SELECT t1.cat_id, t1.cat_name, t1.cat_desc, t2.cat_name as child_cat_name
FROM categories t1
LEFT JOIN categories t2 on t1.child_cat = t2.cat_id;

As Juan correctly points out, the aliases t1 and t2 need to be set since we are joining the same table twice and need to tell the SQL engine somehow to distinguish between the tables.