问:
Out of memory when refactoring a method
I had some out of memory issue in my code, right after I refactored a method, to something more generic, that I can call it with my parameters.
The method prior to the change, responded immediately, even though it is reading thousands of rows, while the refactored method, ran out of memory and seemed heavy.

```<code>private Dictionary<string, string> MapFile(string[] fileRows)
    {
        var dic = new Dictionary<string, string>();
        foreach (var row in fileRows)
        {
            var key = row.Substring(3, 10) + row.Substring(45, 11);
            dic[key] = row;
        }
        return dic;
    }
</code>```

The rafactored method:

```<code>        private Dictionary<string, string> MapFile(string[] fileRows, params KeyValuePair<int, int>[] keyIndexes)
    {
        var dic = new Dictionary<string, string>();
        StringBuilder keyPair = new StringBuilder();
        foreach (var row in fileRows)
        {
            foreach (var keyIndex in keyIndexes)
            {
                keyPair.Append(row.Substring(keyIndex.Key, keyIndex.Value));
            }
            dic[keyPair.ToString()] = row;
        }
        return dic;
    }
</code>```

Calling it like:

```<code> MapFile(file, new KeyValuePair<int,int>(3,10), new KeyValuePair<int,int>(45,11))
</code>```

I understand the code need to do some more work, but still don't understand the huge difference between reading those two methods. one is smooth and response in less than a second, the other take all of the system's memory, and crash.

Upate:

Wanted to know, if this implementation, using Tuple as the type to store a pair of int, used with the Substring inside the method (index, length) is smarter and a better practice ?

```<code>private Dictionary<string, string> MapFile(string[] fileRows, params Tuple<int, int>[] keyIndexes)
    {
        var dic = new Dictionary<string, string>();
        foreach (var row in fileRows)
        {
            string key = "";
            foreach (var pair in keyIndexes)
            {
                key += row.Substring(pair.Item1, pair.Item2);
            }
            dic[key] = row;
        }
        return dic;
    }
</code>```

答:
Basically, the problem is that you are appending 2 values to the StringBuilder on every single row, so in each loop you are making the StringBuilder store larger values, up until you run out of memory

What you should do, instead, so that the logic doesn't change from the previous version, is this:

```<code>foreach (var row in fileRows)
{
     StringBuilder keyPair = new StringBuilder(); // Create a new instance each time
     foreach (var keyIndex in keyIndexes)
     {
         keyPair.Append(row.Substring(keyIndex.Key, keyIndex.Value));
     }
     dic[keyPair.ToString()] = row;
 }
</code>```

If you want to use only one instance of the StringBuilder though, you can do this:

```<code>StringBuilder keyPair = new StringBuilder();
foreach (var row in fileRows)
{
     foreach (var keyIndex in keyIndexes)
     {
         keyPair.Append(row.Substring(keyIndex.Key, keyIndex.Value));
     }
     dic[keyPair.ToString()] = row;
     keyPair.Clear(); // ensure it is cleared for the next row
 }
</code>```

Yet another thing you could be doing is this, so that you don't have to deal with StringBuilder's:

```<code>foreach (var row in fileRows)
{
     string key = string.Empty;
     foreach (var keyIndex in keyIndexes)
     {
         key += row.Substring(keyIndex.Key, keyIndex.Value);
     }
     dic[key] = row;
 }
</code>```

Title: Out of memory when refactoring a method

Body:
I had some out of memory issue in my code, right after I refactored a method, to something more generic, that I can call it with my parameters.
The method prior to the change, responded immediately, even though it is reading thousands of rows, while the refactored method, ran out of memory and seemed heavy.

private Dictionary<string, string> MapFile(string[] fileRows)
    {
        var dic = new Dictionary<string, string>();
        foreach (var row in fileRows)
        {
            var key = row.Substring(3, 10) + row.Substring(45, 11);
            dic[key] = row;
        }
        return dic;
    }

The rafactored method:

        private Dictionary<string, string> MapFile(string[] fileRows, params KeyValuePair<int, int>[] keyIndexes)
    {
        var dic = new Dictionary<string, string>();
        StringBuilder keyPair = new StringBuilder();
        foreach (var row in fileRows)
        {
            foreach (var keyIndex in keyIndexes)
            {
                keyPair.Append(row.Substring(keyIndex.Key, keyIndex.Value));
            }
            dic[keyPair.ToString()] = row;
        }
        return dic;
    }

Calling it like:

 MapFile(file, new KeyValuePair<int,int>(3,10), new KeyValuePair<int,int>(45,11))

I understand the code need to do some more work, but still don't understand the huge difference between reading those two methods. one is smooth and response in less than a second, the other take all of the system's memory, and crash.

Upate:

Wanted to know, if this implementation, using Tuple as the type to store a pair of int, used with the Substring inside the method (index, length) is smarter and a better practice ?

private Dictionary<string, string> MapFile(string[] fileRows, params Tuple<int, int>[] keyIndexes)
    {
        var dic = new Dictionary<string, string>();
        foreach (var row in fileRows)
        {
            string key = "";
            foreach (var pair in keyIndexes)
            {
                key += row.Substring(pair.Item1, pair.Item2);
            }
            dic[key] = row;
        }
        return dic;
    }

Body:
Basically, the problem is that you are appending 2 values to the StringBuilder on every single row, so in each loop you are making the StringBuilder store larger values, up until you run out of memory

What you should do, instead, so that the logic doesn't change from the previous version, is this:

foreach (var row in fileRows)
{
     StringBuilder keyPair = new StringBuilder(); // Create a new instance each time
     foreach (var keyIndex in keyIndexes)
     {
         keyPair.Append(row.Substring(keyIndex.Key, keyIndex.Value));
     }
     dic[keyPair.ToString()] = row;
 }

If you want to use only one instance of the StringBuilder though, you can do this:

StringBuilder keyPair = new StringBuilder();
foreach (var row in fileRows)
{
     foreach (var keyIndex in keyIndexes)
     {
         keyPair.Append(row.Substring(keyIndex.Key, keyIndex.Value));
     }
     dic[keyPair.ToString()] = row;
     keyPair.Clear(); // ensure it is cleared for the next row
 }

Yet another thing you could be doing is this, so that you don't have to deal with StringBuilder's:

foreach (var row in fileRows)
{
     string key = string.Empty;
     foreach (var keyIndex in keyIndexes)
     {
         key += row.Substring(keyIndex.Key, keyIndex.Value);
     }
     dic[key] = row;
 }


来源: stackexchange

问:
MySQL (Percona 5.7) Slow ALTER table with InnoDB engine ...?
I have a table that is in InnoDB engine, quite a simple one with 25000 rows. When I do a simple ALTER, it runs for almost 10 minutes:

```<code>mysql> ALTER TABLE `quote_followups_istvan`
       ADD `customer_ip2` VARCHAR(20) NOT NULL DEFAULT '' AFTER `comment`;
</code>```

Query OK, 0 rows affected (10 min 52.82 sec)
Records: 0  Duplicates: 0  Warnings: 0

But when I change it's engine to MyISAM, I get this:

```<code>mysql> alter table quote_followups_istvan engine="MyISAM";
</code>```

Query OK, 25053 rows affected (0.56 sec)
Records: 25053  Duplicates: 0  Warnings: 0

```<code>mysql> ALTER TABLE `quote_followups_istvan`
       ADD `customer_ip3` VARCHAR(20) NOT NULL DEFAULT '' AFTER `comment`;
</code>```

Query OK, 25053 rows affected (0.37 sec)
Records: 25053  Duplicates: 0  Warnings: 0

So 10minutes vs 0.37s....

What amd I missing here?

答:
Let me answer my own question. Reading on, articles like this one

optimize mySql for faster alter table add column

and many more, actually say that this is the "issue" with InnoDb tables, and suggest some alternative approaches.

So I can only conclude that this is a normal behavior.

ContentLicense: CC BY-SA 3.0

Body:
I have a table that is in InnoDB engine, quite a simple one with 25000 rows. When I do a simple ALTER, it runs for almost 10 minutes:

mysql> ALTER TABLE `quote_followups_istvan`
       ADD `customer_ip2` VARCHAR(20) NOT NULL DEFAULT '' AFTER `comment`;

Query OK, 0 rows affected (10 min 52.82 sec)
Records: 0  Duplicates: 0  Warnings: 0

But when I change it's engine to MyISAM, I get this:

mysql> alter table quote_followups_istvan engine="MyISAM";

Query OK, 25053 rows affected (0.56 sec)
Records: 25053  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE `quote_followups_istvan`
       ADD `customer_ip3` VARCHAR(20) NOT NULL DEFAULT '' AFTER `comment`;

Query OK, 25053 rows affected (0.37 sec)
Records: 25053  Duplicates: 0  Warnings: 0

So 10minutes vs 0.37s....

What amd I missing here?


问:
convert a string to json in java
I want to convert the stdout of the following python into a json object in Java code.

```<code>Process p = Runtime.getRuntime().exec(python one.py);

BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));

while ((s = stdInput.readLine()) != null) {
    System.out.println(s); }
</code>```

python output sample:  cat-red-fish dog-brown-meat

desired JSON : "animal":{"type":"cat", "color":"red", "food":"fish"}...

How can I split while passing the output in JSON?

答:
Use JacksonJSON library or GSON which may be easiest one.
http://www.studytrails.com/java/json/java-google-json-parse-json-to-java-tree/

See this answer how to create JSON object from Map<String,String> object. You just need to split an input string accordingly.
https://stackoverflow.com/a/18444414/185565

```<code>Map<String,String> myMap = new HashMap<String,String>();
//..populate mymap..
Gson gson = new Gson();
String json = gson.toJson(myMap);
</code>```

Here is a copypaste example from the gson documentation in case the previous link stopped working. This one reads a json string to json object so is not a direct answer to your question but may come handy.

```<code>import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class ParseTreeExample6 {
    public static void main(String[] args) throws MalformedURLException, IOException {
        String url = "http://freemusicarchive.org/api/get/albums.json?api_key=60BLHNQCAOUFPIBZ&limit=5";
        String json = IOUtils.toString(new URL(url));
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(json);
        if (element.isJsonObject()) {
            JsonObject albums = element.getAsJsonObject();
            System.out.println(albums.get("title").getAsString());
            JsonArray datasets = albums.getAsJsonArray("dataset");
            for (int i = 0; i < datasets.size(); i++) {
                JsonObject dataset = datasets.get(i).getAsJsonObject();
                System.out.println(dataset.get("album_title").getAsString());
            }
        }

    }
}
</code>```

Title: convert a string to json in java

Body:
I want to convert the stdout of the following python into a json object in Java code.

Process p = Runtime.getRuntime().exec(python one.py);

BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));

while ((s = stdInput.readLine()) != null) {
    System.out.println(s); }

python output sample:  cat-red-fish dog-brown-meat

desired JSON : "animal":{"type":"cat", "color":"red", "food":"fish"}...

How can I split while passing the output in JSON?

Body:
Use JacksonJSON library or GSON which may be easiest one.
http://www.studytrails.com/java/json/java-google-json-parse-json-to-java-tree/

See this answer how to create JSON object from Map<String,String> object. You just need to split an input string accordingly.
https://stackoverflow.com/a/18444414/185565

Map<String,String> myMap = new HashMap<String,String>();
//..populate mymap..
Gson gson = new Gson();
String json = gson.toJson(myMap);

Here is a copypaste example from the gson documentation in case the previous link stopped working. This one reads a json string to json object so is not a direct answer to your question but may come handy.

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class ParseTreeExample6 {
    public static void main(String[] args) throws MalformedURLException, IOException {
        String url = "http://freemusicarchive.org/api/get/albums.json?api_key=60BLHNQCAOUFPIBZ&limit=5";
        String json = IOUtils.toString(new URL(url));
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(json);
        if (element.isJsonObject()) {
            JsonObject albums = element.getAsJsonObject();
            System.out.println(albums.get("title").getAsString());
            JsonArray datasets = albums.getAsJsonArray("dataset");
            for (int i = 0; i < datasets.size(); i++) {
                JsonObject dataset = datasets.get(i).getAsJsonObject();
                System.out.println(dataset.get("album_title").getAsString());
            }
        }

    }
}


问:
Create a list that either prints dictionary's value or 0
I have a list

lis = [9,4,10,8,2,4]

I create a dictionary

dicto = Counter(lis)

So my dictionary is

Counter({4: 2, 8: 1, 9: 1, 10: 1, 2: 1})

Now I have created another list from 2 (minimum value of the list) to 10 (maximum value of the list)

lis2 = [2,3,4,5,6,7,8,9,10]

So I would like to loop through lis2 and check with the dictionary keys and if the dictionary key and lis2 element matches,I store the dictionary key's value else zero.Something like

[1, 0, 2, 0, 0, 0, 1, 1, 1]

So I did something like this

count = [dicto[i] for i in range(2,11) for j in dicto.keys() if i==j]

But I am able to get only the values of the dictionary keys which matches with the elements of the lis2 and not the corresponding 0's in case of no match.

How do I get 0's in case of no match?I want to do it in list comprehension style.

答:
Use list comprehension with get:</p>

```<code>count = [dicto.get(num, 0) for num in list2]
# [1, 0, 2, 0, 0, 0, 1, 1, 1]
</code>```

Body:
Use list comprehension with get:

count = [dicto.get(num, 0) for num in list2]
# [1, 0, 2, 0, 0, 0, 1, 1, 1]


问:
How does blur event gets fired when tabbing between siblings
I am having a div which contains an input element and span element as children. The input and span are siblings(having common parent div). So i am having a blur event on div and i am having tabindex 0 on span element. So when my focus is on input element and when i tab the focus shifts to span but the blur event is fired.
Is this event firing expected when tabbing between sliblings?

React Code:

```<code><div className="box-v2"
          tabIndex={-1}
          onBlur={this._onBlur}>
           <input ref="inputBox"
            className="input-box"
            spellCheck={false}
            value={this.state.text}
            onChange={this._onChange} />

            <span className="icon"
                       tabIndex={0}/>
</div>
</code>```

答:
In the world of React JS, we can assume that it indeed is expected. If it makes sense, is another story.

Reason:

Native focus and native blur events don't bubble. Corresponding React event handlers onFocus and onBlur do bubble - dun dun dun.

(Source: https://github.com/facebook/react/issues/6410#issuecomment-207064994)

I created a WebpackBin where you can test and compare the behaviour:
https://www.webpackbin.com/bins/-KoJBHpK9s_OA76FnLkv

Open your browser's dev console, webpackbin cannot show the console.log of the iframe, I wanted to show both examples "side by side".

As you can see, the React behaviour is the one you described. You focus the input field and if you tab to the sibling span, it will fire the onBlur event.

But in the native code, this is not what happens. If you focus the input there and then tab, nothing happens (except moving the focus to the sibling span, of course.

If you focus the div and then leave the focus again, then it will fire the onBlur event too.

Body:
I am having a div which contains an input element and span element as children. The input and span are siblings(having common parent div). So i am having a blur event on div and i am having tabindex 0 on span element. So when my focus is on input element and when i tab the focus shifts to span but the blur event is fired.
Is this event firing expected when tabbing between sliblings?

React Code:

           <input ref="inputBox"
            className="input-box"
            spellCheck={false}
            value={this.state.text}
            onChange={this._onChange} />


问:
Mousemove event blocked by occluding SVG elements
I have an SVG element with a mousemove event, showing the coordinate of the pointer. When the the mouse moves over an occluding element, the mousemove event is blocked. I need to make the event propagate to the original element.

I have tried changing the pointer-events attribute, but this effects all mouse events, and I need the occluding elements to respond other events. Any suggestions.

答:
To summarize the key ideas of Brian Peacock's excellent and detailed suggestion:
It seems the problems is that the graphical order of svg elements (what goes behind what) does not follow the DOM hierarchy, so the normal bubbling of events cannot be used directly. Thus, one must capture the event at a common high point and pragmatically search for the elements under the point.

As a general point of discussion (excuse me for this here), it should be noted that this not an optimal solution in many cases. For example, when rapidly occurring events are captured, such as mousemove, when there are many element in the SVG, and when fast response is needed for smooth GUI, the strategy may be too computationally expensive. It will be great if better event handling system is included in the SVG specs and included in the browsers, where everything can be done by the engine. This will significantly improve the ability to have pure-SVG GUIs.


问:
Java/Spring-Boot Webapp not Serving Assets from Public Resources Directory
I'm working on an AngularJS application that's being served by Spring-Boot. I'm in the process of upgrading our build pipeline to include Webpack. Webpack is bundling all of the source code into a /src/main/resources/static directory, which I'm told SHOULD be served automatically by Spring-Boot. However, when I try to test this out by navigating to http://localhost:8080, the index.html page is being served, but the various JS bundles are not. Below are some of the relevant files to configure this:

webpack.config.js

```<code>/*global process, module, __dirname*/

const path = require('path');
const proxyMiddleware = require('proxy-middleware');
const url = require('url');
const webpack = require('webpack');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');

const PATHS = {
    app: path.join(__dirname, './src/main/webapp'),
    dist: path.join(__dirname, './src/main/resources/static'),
    test: path.join(__dirname, './src/test/webapp')
};

const isDevelopment = process.env.NODE_ENV === 'develop';
const isE2E = process.env.NODE_ENV === 'e2e';
const isTest = process.env.NODE_ENV === 'test';
const isProd = process.env.NODE_ENV === 'production';

// Webpack Loaders
const fontRule = {
    test: /\.(eot|svg|ttf|woff|woff2)$/,
    loader: 'file-loader',
    options: {
        name: '[name].[sha1:hash:base64:32].[ext]'
    }
};

const htmlRule = {
    test: /\.html$/,
    loader: 'html-loader',
    query: {
        minimize: isProd
    }
};

const imageRule = {
    test: /\.png$/i,
    loader: 'url-loader',
    options: {
        limit: 8192,
        mimetype: 'image/png'
    }
};

const javasscriptPreRule = {
    test: /\.js$/,
    exclude: /node_modules/,
    enforce: 'pre',
    loader: 'eslint-loader'
};

const javascriptRule = {
    test: /\.js$/,
    exclude: /node_modules/,
    loader: 'babel-loader'
};

const sassRule = {
    test : /\.scss$/,
    use: ExtractTextPlugin.extract({
        use: [ 'css-loader', 'resolve-url-loader', 'sass-loader?sourceMap' ]
    })
};

const entry = {
    app: (() => {
        let app = [ path.join(PATHS.app, 'app.js') ];

        if (isProd || isE2E) {
            app.push(path.join(PATHS.app, 'app.prod.js'));
        } else {
            app.push(path.join(PATHS.app, 'app.mock.js'));
        }

        return app;
    })()
};

const output = {
    path: PATHS.dist,
    filename: isProd ? '[name].[chunkhash].js' : '[name].js'
};

const plugins = (() => {
    let plugins = [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks(module) {
                return module.context
                    && module.context.indexOf('node_modules') !== -1;
            }
        }),

        new webpack.optimize.CommonsChunkPlugin({ name: 'manifest' }),

        new ExtractTextPlugin(isProd ? 'styles.[contenthash].css' : 'styles.css'),

        new HtmlWebpackPlugin({ template: path.join(PATHS.app, 'index.html') }),

        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
        })
    ];

    if (isProd) {
        plugins = plugins.concat([
            new webpack.optimize.UglifyJsPlugin({
                beautify: false,
                comments: false,
                compress: {
                    warnings: false
                }
            }),

            new webpack.optimize.OccurrenceOrderPlugin(),

            new OptimizeCssAssetsWebpackPlugin({
                cssProcessorOptions: {
                    discardComments: { removeAll: true }
                }
            })
        ]);
    } else {
        const server = (() => {
            let server = {
                baseDir: PATHS.dist
            };

            // Internal testing server configurations...

            return server;
        })();

        plugins.push(
            new BrowserSyncPlugin({
                host: 'localhost',
                port: 3000,
                server
            })
        )
    }

    return plugins;
})();

function proxy(target) {
    let options = url.parse(target);
    options.route = '/api';

    return proxyMiddleware(options);
}

module.exports = {
    entry,
    output,
    plugins,
    module: {
        rules: [ fontRule, htmlRule, imageRule, javasscriptPreRule, javascriptRule, sassRule ]
    }
};
</code>```

WebSecurityConfig.java

```<code>@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements InitializingBean {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // Internal security configurations
                .and()
                .authorizeRequests()
                    .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                    .anyRequest().permitAll();
    }

}
</code>```

Here are the static files stored in /src/target/classes/static:

And here is proof that the JS files aren't showing up when opening the browser:

Body:
I'm working on an AngularJS application that's being served by Spring-Boot. I'm in the process of upgrading our build pipeline to include Webpack. Webpack is bundling all of the source code into a /src/main/resources/static directory, which I'm told SHOULD be served automatically by Spring-Boot. However, when I try to test this out by navigating to http://localhost:8080, the index.html page is being served, but the various JS bundles are not. Below are some of the relevant files to configure this:

webpack.config.js

/*global process, module, __dirname*/

const path = require('path');
const proxyMiddleware = require('proxy-middleware');
const url = require('url');
const webpack = require('webpack');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');

const PATHS = {
    app: path.join(__dirname, './src/main/webapp'),
    dist: path.join(__dirname, './src/main/resources/static'),
    test: path.join(__dirname, './src/test/webapp')
};

const isDevelopment = process.env.NODE_ENV === 'develop';
const isE2E = process.env.NODE_ENV === 'e2e';
const isTest = process.env.NODE_ENV === 'test';
const isProd = process.env.NODE_ENV === 'production';

// Webpack Loaders
const fontRule = {
    test: /\.(eot|svg|ttf|woff|woff2)$/,
    loader: 'file-loader',
    options: {
        name: '[name].[sha1:hash:base64:32].[ext]'
    }
};

const htmlRule = {
    test: /\.html$/,
    loader: 'html-loader',
    query: {
        minimize: isProd
    }
};

const imageRule = {
    test: /\.png$/i,
    loader: 'url-loader',
    options: {
        limit: 8192,
        mimetype: 'image/png'
    }
};

const javasscriptPreRule = {
    test: /\.js$/,
    exclude: /node_modules/,
    enforce: 'pre',
    loader: 'eslint-loader'
};

const javascriptRule = {
    test: /\.js$/,
    exclude: /node_modules/,
    loader: 'babel-loader'
};

const sassRule = {
    test : /\.scss$/,
    use: ExtractTextPlugin.extract({
        use: [ 'css-loader', 'resolve-url-loader', 'sass-loader?sourceMap' ]
    })
};

const entry = {
    app: (() => {
        let app = [ path.join(PATHS.app, 'app.js') ];

        if (isProd || isE2E) {
            app.push(path.join(PATHS.app, 'app.prod.js'));
        } else {
            app.push(path.join(PATHS.app, 'app.mock.js'));
        }

        return app;
    })()
};

const output = {
    path: PATHS.dist,
    filename: isProd ? '[name].[chunkhash].js' : '[name].js'
};

const plugins = (() => {
    let plugins = [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks(module) {
                return module.context
                    && module.context.indexOf('node_modules') !== -1;
            }
        }),

        new webpack.optimize.CommonsChunkPlugin({ name: 'manifest' }),

        new ExtractTextPlugin(isProd ? 'styles.[contenthash].css' : 'styles.css'),

        new HtmlWebpackPlugin({ template: path.join(PATHS.app, 'index.html') }),

        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
        })
    ];

    if (isProd) {
        plugins = plugins.concat([
            new webpack.optimize.UglifyJsPlugin({
                beautify: false,
                comments: false,
                compress: {
                    warnings: false
                }
            }),

            new webpack.optimize.OccurrenceOrderPlugin(),

            new OptimizeCssAssetsWebpackPlugin({
                cssProcessorOptions: {
                    discardComments: { removeAll: true }
                }
            })
        ]);
    } else {
        const server = (() => {
            let server = {
                baseDir: PATHS.dist
            };

            // Internal testing server configurations...

            return server;
        })();

        plugins.push(
            new BrowserSyncPlugin({
                host: 'localhost',
                port: 3000,
                server
            })
        )
    }

    return plugins;
})();

function proxy(target) {
    let options = url.parse(target);
    options.route = '/api';

    return proxyMiddleware(options);
}

module.exports = {
    entry,
    output,
    plugins,
    module: {
        rules: [ fontRule, htmlRule, imageRule, javasscriptPreRule, javascriptRule, sassRule ]
    }
};

WebSecurityConfig.java

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements InitializingBean {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // Internal security configurations
                .and()
                .authorizeRequests()
                    .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                    .anyRequest().permitAll();
    }

}

Here are the static files stored in /src/target/classes/static:

And here is proof that the JS files aren't showing up when opening the browser:

Body:
I figured out the problem that I was running into. Spring-Boot was still defaulting to src/main/webapp to serve the front-end code. While there is an index.html file within that directory, it doesn't contain <script> tags for the JavaScript bundles generated by Webpack; Webpack takes care of automatically adding those tags. I had to change the directory where the bundle files were being loaded from.

To do this, I edited the src/main/resources/application.properties file, and added the following line:

spring.resources.static-locations=classpath:/static/


问:
Bell frequently sounds when editing vimrc
The terminal bell frequently sounds in my .vimrc when it should not, including when I'm typing comments. What sorts of issues can typically cause this problem?

I have no idea where to start, and so am unsure what code to include, but here is a link to my .vimrc: https://github.com/adc17/.adc17/blob/master/vimrc. If there's any particular info you need about my configuration, feel free to ask and I'll post the relevant snippet.

答: It was a plugin called vim-mucomplete, and I found an option to stop the ringing (set belloff+=ctrlg). Thanks to the commenters for their help—for some reason it didn't occur to me that the problem was a plugin.


问:
Template not displaying using 'sub module'
So I have my main module,

```<code>var panther = angular.module('panther', ['panther.sign_in']).config(function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    })
});
</code>```

Which has a dependency of panther.sign_in,

```<code>angular.module('panther.sign_in', ['ngRoute']).config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/sign_in', {
        controller: 'controller_sign_in',
        templateUrl: 'assets/js/modules/core/sign_in/template.html'
    });
}]);
</code>```

The controller looks like this,

```<code>angular.module('panther.sign_in').controller('controller_sign_in', ['$scope', '$http', function ($scope, $http) {
    alert('test');
}]);
</code>```

The template looks like this,

```<code><h1>Test</h1>
</code>```

When I go to /sign_in it shows,

My index.html file looks like this,

```<code><!DOCTYPE html>
<html ng-app="panther">
<head>
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport"
    content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">

<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"
    integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ"
    crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/base.css">

<title>Panther</title>
</head>
<body>
    <script type="text/javascript" src="cordova.js"></script>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"
        integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
        crossorigin="anonymous"></script>

    <script type="text/javascript"
        src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>

    <script type="text/javascript"
        src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular-route.min.js"></script>

    <!-- CORE PANTHER FILES! -->
    <script type="text/javascript" src="assets/js/panther.js"></script>

    <!-- MODULE(S) INITIALISED HERE! -->
    <script type="text/javascript" src="assets/js/modules/core/sign_in/module.js"></script>

    <!-- MODULE(S) CONTROLLER(S) INITIALISED HERE! -->
    <script type="text/javascript" src="assets/js/modules/core/sign_in/controller.js"></script>
</body>
</html>
</code>```

Why does it not show the template file when I go to the URL /sign_in?

Secondly, is this the correct way to split a large application using Angular (using sub modules)?

Edit #1

In simple terms, I want it so that the user can type http://www.mysite.online/sign_in and the template/controller should show for that sub module. I've updated the main panther module as can be seen below:

```<code>var panther = angular.module('panther', ['panther.sign_in']).config(function ($routeProvider, $locationProvider) {
    /** Remove anything that has been appended to URL (#!). **/
    $locationProvider.hashPrefix('');
});
</code>```

I've changed my code to this, but it still didn't work.

答:
You have to do server side url rewriting, see the docs on html5mode:

https://docs.angularjs.org/guide/$location#server-side

Body:
So I have my main module,

var panther = angular.module('panther', ['panther.sign_in']).config(function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    })
});

Which has a dependency of panther.sign_in,

angular.module('panther.sign_in', ['ngRoute']).config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/sign_in', {
        controller: 'controller_sign_in',
        templateUrl: 'assets/js/modules/core/sign_in/template.html'
    });
}]);

The controller looks like this,

angular.module('panther.sign_in').controller('controller_sign_in', ['$scope', '$http', function ($scope, $http) {
    alert('test');
}]);

The template looks like this,

Test

When I go to /sign_in it shows,

My index.html file looks like this,

<!DOCTYPE html>

<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport"
    content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">

<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"
    integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ"
    crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/base.css">

<title>Panther</title>

Why does it not show the template file when I go to the URL /sign_in?

Secondly, is this the correct way to split a large application using Angular (using sub modules)?

Edit #1

In simple terms, I want it so that the user can type http://www.mysite.online/sign_in and the template/controller should show for that sub module. I've updated the main panther module as can be seen below:

var panther = angular.module('panther', ['panther.sign_in']).config(function ($routeProvider, $locationProvider) {
    /** Remove anything that has been appended to URL (#!). **/
    $locationProvider.hashPrefix('');
});

I've changed my code to this, but it still didn't work.


问:
Intel Vs. AT&T syntax when addressing xmm and floating instruction
Hello everyone
I am working on writing an assembly program and I would like to acquire some knowledge before I start on the looks of AT&T and Intel syntax when addressing xmm and fp. I know that in regular instructions a push when function on a byte is "pushb" in AT&T while "push byte" in Intel. Can anyone provide a similar comparison to when using xmm or fp? In sum I want to know how xmm operands are addressed
Thanks in advance</p>

答: I'm not an AT&T fan/user, but the first place to start for intel would be the intel developer manuals(volumes 2a and 2b contain the instruction references), these list the sizes they operate on, which almost all intel syntax assemblers will try deduce (push will try narrow the variable or align it, depending on settings) if not specified, else you'll generally be using qword/dword for fp (for the likes of fld) and dword/qword/dqword for mmx/sse ops.</p>

ContentLicense: CC BY-SA 2.5


问:
How to Match a Regular Expression to Any Word in a String
I need to be able to search for the first name OR possible middle name and last name of a user and have it pop up in the search results. If my user in a test case is "Alicia Henderson", currently with the following code, I can grab anything from the letter A onward (i.e. Alic, Alicia Hen). However, I would like to be able to type in "H" and get Alicia Henderson (and all other cases in any other word in that may be in the users name. Similar to how Facebook, Twitter, and many other fantastic search engines have. Thanks in advance!</p>

```<code>    $("input[name='search_users']").keyup(function(){

        // Retrieve the input field text and reset the count to zero
        var filter = "^" + $(this).val(), itemsFound = 0;

        // Loop through each user
        $(".send_to .messages .message_username").each(function(){

            // If the list item does not contain the text phrase fade it out
            if ($(this).text().search(new RegExp(filter, "i")) < 0) {
                $(this).parent().css("display","none");

            // Show the list user if the phrase matches and increase the count by 1
            } else {
                $(this).parent().show();
                itemsFound++;
            }

        });

    });
</code>```

答:
First, try using this function to test the match:

const str = "Alicia Henderson";

console.log(testMatch(str, 'Alicia'));
console.log(testMatch(str, 'H'));
console.log(testMatch(str, 'NOPE!'));

function testMatch(str, inputToTest){
 return (new RegExp(inputToTest, 'gi')).test(str);
}```

Body:
I need to be able to search for the first name OR possible middle name and last name of a user and have it pop up in the search results. If my user in a test case is "Alicia Henderson", currently with the following code, I can grab anything from the letter A onward (i.e. Alic, Alicia Hen). However, I would like to be able to type in "H" and get Alicia Henderson (and all other cases in any other word in that may be in the users name. Similar to how Facebook, Twitter, and many other fantastic search engines have. Thanks in advance!

    $("input[name='search_users']").keyup(function(){

        // Retrieve the input field text and reset the count to zero
        var filter = "^" + $(this).val(), itemsFound = 0;

        // Loop through each user
        $(".send_to .messages .message_username").each(function(){

            // If the list item does not contain the text phrase fade it out
            if ($(this).text().search(new RegExp(filter, "i")) < 0) {
                $(this).parent().css("display","none");

            // Show the list user if the phrase matches and increase the count by 1
            } else {
                $(this).parent().show();
                itemsFound++;
            }

        });

    });


问:
How to count vowels
How can I count the vowels in a string ?

for example:

```<code>data: str type string  value 'steave'.
</code>```

and I want the output be:

```<code>2 --> e.
1 --> a.
</code>```

答:
I  seriously thought you were making up words at random. <s> I hope 'vogals' are characters</s>. Vogals I've been told, are vowels. Thank @jmoerdyk. Anyway, since you got me interested I think this may work:

```<code>vowels = 'aeiouy'
length = STRLEN(vowels).
WHILE index < length.
  char = vowels+index(1).
  FIND ALL OCCURENCES OF char IN yourString
  MATCH COUNT  occurrences
  WRITE: / char,'appears', / occurrences,'times'
  ADD 1 TO index.
ENDWHILE.
</code>```

Seems difficult working for SAP. The language seems to work well with tables/databases, not these kind of string operations.

ContentLicense: CC BY-SA 4.0

Title: How to count vowels

Body:
How can I count the vowels in a string ?

for example:

data: str type string  value 'steave'.

and I want the output be:

2 --> e.
1 --> a.

Body:
I  seriously thought you were making up words at random. <s> I hope 'vogals' are characters</s>. Vogals I've been told, are vowels. Thank @jmoerdyk. Anyway, since you got me interested I think this may work:

vowels = 'aeiouy'
length = STRLEN(vowels).
WHILE index < length.
  char = vowels+index(1).
  FIND ALL OCCURENCES OF char IN yourString
  MATCH COUNT  occurrences
  WRITE: / char,'appears', / occurrences,'times'
  ADD 1 TO index.
ENDWHILE.

Seems difficult working for SAP. The language seems to work well with tables/databases, not these kind of string operations.


问:
How to run chrome driver in headless mode or in background
I've been using chrome driver (with selenium webdriver), so far it never caused any issue, now for some requirement i want to run test cases in background. How can I do this?</p>

答:
Currently Chrome 59 supports headless mode.
You just need to use those chromeOptions to use headless chrome in selenium.

```<code>chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--disable-gpu");
</code>```

You can refer below link for more details:

https://www.automation99.com/2017/07/how-to-use-chrome-headless-using.html

Body:
Currently Chrome 59 supports headless mode.
You just need to use those chromeOptions to use headless chrome in selenium.

chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--disable-gpu");

You can refer below link for more details:

https://www.automation99.com/2017/07/how-to-use-chrome-headless-using.html


问:
NYT article search API not returning results for certain queries
I have a set of queries and I am trying to get web_urls using the NYT article search API. But I am seeing that it works for q2 below but not for q1.

q1: Seattle+Jacob Vigdor+the University of Washington

q2: Seattle+Jacob Vigdor+University of Washington

If you paste the url below with your API key in the web browser, you get an empty result.

Search request for q1

api.nytimes.com/svc/search/v2/articlesearch.json?q=Seattle+Jacob%20Vigdor+the%20University%20of%20Washington&begin_date=20170626&api-key=XXXX

Empty results for q1

{"response":{"meta":{"hits":0,"time":27,"offset":0},"docs":[]},"status":"OK","copyright":"Copyright (c) 2013 The New York Times Company.  All Rights Reserved."}

Instead if you paste the following in your web browser (without the article 'the' in the query) you get non-empty results

Search request for q2

api.nytimes.com/svc/search/v2/articlesearch.json?q=Seattle+Jacob%20Vigdor+University%20of%20Washington&begin_date=20170626&api-key=XXXX

Non-empty results for q2

{"response":{"meta":{"hits":1,"time":22,"offset":0},"docs":[{"web_url":"https://www.nytimes.com/aponline/2017/06/26/us/ap-us-seattle-minimum-wage.html","snippet":"Seattle's $15-an-hour minimum wage law has cost the city jobs, according to a study released Monday that contradicted another new study published last week....","lead_paragraph":"Seattle's $15-an-hour minimum wage law has cost the city jobs, according to a study released Monday that contradicted another new study published last week.","abstract":null,"print_page":null,"blog":[],"source":"AP","multimedia":[],"headline":{"main":"New Study of Seattle's $15 Minimum Wage Says It Costs Jobs","print_headline":"New Study of Seattle's $15 Minimum Wage Says It Costs Jobs"},"keywords":[],"pub_date":"2017-06-26T15:16:28+0000","document_type":"article","news_desk":"None","section_name":"U.S.","subsection_name":null,"byline":{"person":[],"original":"By THE ASSOCIATED PRESS","organization":"THE ASSOCIATED PRESS"},"type_of_material":"News","_id":"5951255195d0e02550996fb3","word_count":643,"slideshow_credits":null}]},"status":"OK","copyright":"Copyright (c) 2013 The New York Times Company.  All Rights Reserved."}

Interestingly, both queries work fine on the api test page
http://developer.nytimes.com/article_search_v2.json#/Console/

Also, if you look at the article below returned by q2, you see that the query term in q1, 'the University of Washington' does occur in it and it should have returned this article.
https://www.nytimes.com//aponline//2017//06//26//us//ap-us-seattle-minimum-wage.html

I am confused about this behaviour of the API. Any ideas what's going on? Am I missing something?

答:
Thank you for all the answers. Below I am pasting the answer I received from NYT developers.

NYT's Article Search API uses Elasticsearch. There are lots of docs online about the query syntax of Elasticsearch (it is based on Lucene).

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#query-string-syntax

If you want articles that contain "Seattle", "Jacob Vigdor" and "University of Washington", do

"Seattle" AND "Jacob Vigdor" AND "University of Washington"

or

+"Seattle" +"Jacob Vigdor" +"University of Washington"


答:
```<code>    StringBuilder keyPair = new StringBuilder();
    foreach (var row in fileRows)
    {
        foreach (var keyIndex in keyIndexes)
        {
            keyPair.Append(row.Substring(keyIndex.Key, keyIndex.Value));
        }
        dic[keyPair.ToString()] = row;
    }
</code>```

Here's a question for you...  what is keyPair.ToString() going to evaluate to here?

Answer: A concatenation of everything you've appended.  It will grow for every time through the loop.  Eventually, keyPair will be a huge string that you are using as a key to your dictionary.

Your code doesn't make a lot of sense to me, but try moving the StringBuilder creation INSIDE the first foreach loop.

Title: Out of memory when refactoring a method

Body:
    StringBuilder keyPair = new StringBuilder();
    foreach (var row in fileRows)
    {
        foreach (var keyIndex in keyIndexes)
        {
            keyPair.Append(row.Substring(keyIndex.Key, keyIndex.Value));
        }
        dic[keyPair.ToString()] = row;
    }

Here's a question for you...  what is keyPair.ToString() going to evaluate to here?

Answer: A concatenation of everything you've appended.  It will grow for every time through the loop.  Eventually, keyPair will be a huge string that you are using as a key to your dictionary.

Your code doesn't make a lot of sense to me, but try moving the StringBuilder creation INSIDE the first foreach loop.


问:
Logical Operator always stays true?
What I want is to compare current url with my cookie array which would contain all the URL's a user has visited so it would compare that whether the array contains the current link or not so if not it would push that new link to the array and would again recreate the cookie with the new array which would contain the new pushed link so what I am facing right now is that everytime the if function which checks for the unique link always comes true I am not sure that what's the problem?

Can you people please have a look over it :

```<code><script type="text/javascript">

function createCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

var url = window.location.href;
var pathname = new URL(url).pathname;
var jsonObj = [];

//jsonObj.push("test");

var x = readCookie('vid_cookies');
if (x) {
var res = x.split(",");
console.log(res);
for (var i = 0; i < res.length; i++) {
    if (pathname != res[i]) {
        alert("IS NOT EQUAL");
    //res.push(pathname);
    //var joinedArray = res.join(",");
    //console.log(joinedArray);
    //createCookie('vid_cookies',joinedArray,7);
    //var z = readCookie('vid_cookies');
    //console.log(z)
    }
}
} else {
    jsonObj.push(pathname);
createCookie('vid_cookies',jsonObj,7);
}

//alert(jsonObj);

</script>
</code>```

Here is the Array as :

```<code>["/evercookie-master/yahoo.html", "/evercookie-master/facebook.html", "/evercookie-master/facebook.html", "/evercookie-master/facebook.html"]
</code>```

答:
The logic is not correct. If you want to add a value to an array only if it doesn't exist yet, you have to check all elements before you add it.

In your code you are adding the value as soon as any of the element doesn't match. That will always be the case of course because out n elements, n - 1 will not match.

One way to do it would be to use Array#every:

```<code>if (res.every(x => x !== pathname)) {
 // add to array and set cookie
}
</code>```

Alternatively you could convert the array to a Set, always add the value and set the cookie. The Set will automatically dedupe the values:

```<code>var res = new Set(x.split(","));
res.add(pathname);
res = Array.from(res);
</code>```

Title: Logical Operator always stays true?

Body:
What I want is to compare current url with my cookie array which would contain all the URL's a user has visited so it would compare that whether the array contains the current link or not so if not it would push that new link to the array and would again recreate the cookie with the new array which would contain the new pushed link so what I am facing right now is that everytime the if function which checks for the unique link always comes true I am not sure that what's the problem?

Can you people please have a look over it :

Here is the Array as :

["/evercookie-master/yahoo.html", "/evercookie-master/facebook.html", "/evercookie-master/facebook.html", "/evercookie-master/facebook.html"]

Body:
The logic is not correct. If you want to add a value to an array only if it doesn't exist yet, you have to check all elements before you add it.

In your code you are adding the value as soon as any of the element doesn't match. That will always be the case of course because out n elements, n - 1 will not match.

One way to do it would be to use Array#every:

if (res.every(x => x !== pathname)) {
 // add to array and set cookie
}

Alternatively you could convert the array to a Set, always add the value and set the cookie. The Set will automatically dedupe the values:

var res = new Set(x.split(","));
res.add(pathname);
res = Array.from(res);


问:
Dependency Injection vs Factory Pattern
Most of the examples quoted for usage of Dependency Injection, we can solve using the factory pattern as well. Looks like when it comes to usage/design the difference between dependency injection and factory is blurred or thin.

Once someone told me that its how you use it that makes a difference!

I once used StructureMap a DI container to solve a problem, later on I redesigned it to work with a simple factory and removed references to StructureMap.

Can anyone tell me what is the difference between them and where to use what, whats the best practice here?

答:
Life cycle management is one of the responsibilities dependency containers assume in addition to instantiation and injection. The fact that the container sometimes keep a reference to the components after instantiation is the reason it is called a "container", and not a factory. Dependency injection containers usually only keep a reference to objects it needs to manage life cycles for, or that are reused for future injections, like singletons or flyweights. When configured to create new instances of some components for each call to the container, the container usually just forgets about the created object.

From: http://tutorials.jenkov.com/dependency-injection/dependency-injection-containers.html

OwnerDisplayName: Binoj Antony

Title: Dependency Injection vs Factory Pattern

LastEditorDisplayName: Binoj Antony


问:
How can the User Interface know which commands is allowed to perform against an Aggregate Root?
The UI is decoupled from the domain, but the UI should try its best to never allow the user to issue commands that are sure to fail.
Consider the following example (pseudo-code):

```<code>DiscussionController
    @Security(is_logged)
    @Method('POST')
    @Route('addPost')
    addPostToDiscussionAction(request)
        discussionService.postToDiscussion(
            new PostToDiscussionCommand(request.discussionId, session.myUserId, request.bodyText)
        )

    @Method('GET')
    @Route('showDiscussion/{discussionId}')
    showDiscussionAction(request)
        discussionWithAllThePosts = discussionFinder.findById(request.discussionId)

        canAddPostToThisDiscussion = ???

        // render the discussion to the user, and use `canAddPostToThisDiscussion` to show/hide the form
        // from which the user can send a request to `addPostToDiscussionAction`.
        renderDiscussion(discussionWithAllThePosts, canAddPostToThisDiscussion)

PostToDiscussionCommand
    constructor(discussionId, authorId, bodyText)

DiscussionApplicationService
    postToDiscussion(command)
        discussion = discussionRepository.get(command.discussionId)
        author = collaboratorService.authorFrom(discussion.Id, command.authorId)
        post = discussion.createPost(postRepository.nextIdentity(), author, command.bodyText)
        postRepository.add(post)

DiscussionAggregate
    // originalPoster is the Author that started the discussion
    constructor(discussionId, originalPoster)

    // if the discussion is closed, you can't create a post.
    // *unless* if you're the author (OP) that started the discussion
    createPost(postId, author, bodyText)
        if (this.close && !this.originalPoster.equals(author))
            throw "Discussion is closed."

        return new Post(this.discussionId, postId, author, bodyText)

    close()
        if (this.close)
            throw "Discussion already closed."

        this.close = true

    isClosed()
        return this.close
</code>```

The user goes to /showDiscussion/123 and he see the discussion with the <form> from which he can submit a new post, but only if the discussion is not closed or the current user is who started that discussion.

Or, the user goes to /showDiscussion/123 where it's presented as a REST-as-in-HATEOAS API. A hypermedia link to /addPost will be provided, only if the discussion is not closed or the authenticated user is who started that discussion.

How can I provide that knowledge into the UI?

I could code that into the read model,

```<code>canAddPostToThisDiscussion = !discussionWithAllThePosts.discussion.isClosed
    && discussionWithAllThePosts.discussion.originalPoster.id == session.currentUserId
</code>```

but then I need to maintain that logic and keep it in sync with the write model. This is a fairly simple example, but as the states transitions of an aggregate become more complex, it may become really hard to do. I'd like to image my aggregates as state machines, with their workflows (like the RESTBucks example). But I don't like the idea to move that business logic outside my domain model, and put it in a service that both the read side and write side can use.

Maybe this isn't the best example, but as an aggregate root is basically a consistency boundary, we know that we need to prevent invalid state transitions in its life cycle, and in each transitions to a new state some operations may become illegal and vice versa. So, how can the user interface know what is allowed or not? What are my alternative? How should I approach to this problem? Do you have any example to provide?

答: The response you are looking for is HATEOAS, look no further. You must implement your rest api as really restful (level 3) adhering to hypertext to model the state transitions and return links to the clients (being the UI one of those). These links represent the actions the user can execute in its context according to the model state. It´s simple. If you return a link from the server then you bind it to a button in the UI, if you don´t return the link because of business invariants then you do not show the button on the UI. There is a lot more of concepts behind it such as designing a good API supporting a well designed domain model behind but this is the general idea around it and fits exactly what you want.</p>

Body:
The UI is decoupled from the domain, but the UI should try its best to never allow the user to issue commands that are sure to fail.
Consider the following example (pseudo-code):

DiscussionController
    @Security(is_logged)
    @Method('POST')
    @Route('addPost')
    addPostToDiscussionAction(request)
        discussionService.postToDiscussion(
            new PostToDiscussionCommand(request.discussionId, session.myUserId, request.bodyText)
        )

    @Method('GET')
    @Route('showDiscussion/{discussionId}')
    showDiscussionAction(request)
        discussionWithAllThePosts = discussionFinder.findById(request.discussionId)

        canAddPostToThisDiscussion = ???

        // render the discussion to the user, and use `canAddPostToThisDiscussion` to show/hide the form
        // from which the user can send a request to `addPostToDiscussionAction`.
        renderDiscussion(discussionWithAllThePosts, canAddPostToThisDiscussion)

PostToDiscussionCommand
    constructor(discussionId, authorId, bodyText)

DiscussionApplicationService
    postToDiscussion(command)
        discussion = discussionRepository.get(command.discussionId)
        author = collaboratorService.authorFrom(discussion.Id, command.authorId)
        post = discussion.createPost(postRepository.nextIdentity(), author, command.bodyText)
        postRepository.add(post)

DiscussionAggregate
    // originalPoster is the Author that started the discussion
    constructor(discussionId, originalPoster)

    // if the discussion is closed, you can't create a post.
    // *unless* if you're the author (OP) that started the discussion
    createPost(postId, author, bodyText)
        if (this.close && !this.originalPoster.equals(author))
            throw "Discussion is closed."

        return new Post(this.discussionId, postId, author, bodyText)

    close()
        if (this.close)
            throw "Discussion already closed."

        this.close = true

    isClosed()
        return this.close

The user goes to /showDiscussion/123 and he see the discussion with the <form> from which he can submit a new post, but only if the discussion is not closed or the current user is who started that discussion.

Or, the user goes to /showDiscussion/123 where it's presented as a REST-as-in-HATEOAS API. A hypermedia link to /addPost will be provided, only if the discussion is not closed or the authenticated user is who started that discussion.

How can I provide that knowledge into the UI?

I could code that into the read model,

canAddPostToThisDiscussion = !discussionWithAllThePosts.discussion.isClosed
    && discussionWithAllThePosts.discussion.originalPoster.id == session.currentUserId

but then I need to maintain that logic and keep it in sync with the write model. This is a fairly simple example, but as the states transitions of an aggregate become more complex, it may become really hard to do. I'd like to image my aggregates as state machines, with their workflows (like the RESTBucks example). But I don't like the idea to move that business logic outside my domain model, and put it in a service that both the read side and write side can use.

Maybe this isn't the best example, but as an aggregate root is basically a consistency boundary, we know that we need to prevent invalid state transitions in its life cycle, and in each transitions to a new state some operations may become illegal and vice versa. So, how can the user interface know what is allowed or not? What are my alternative? How should I approach to this problem? Do you have any example to provide?


问:
JOIN, ORDER BY and GROUP BY in same statement
I have two tables - results and contestants. Result table cointains

result_id (PK)

resul_contestant (who scored this)

value (how much did he scored)

result_discipline(where he scored this)

contestants table cointains

contestant_id (PK)

contestant_name

contestant_category

What I want to do is to select results for all contestants, but I only want to show one result per contestant - the highest (lowest) one.
So far I managed to do this:

```<code>SELECT * FROM contenstants
JOIN results ON result_contestant = contenstant_id
WHERE result_discipline = 1 AND contestant_category = 1
ORDER BY value DESC
GROUP BY contenstant_id;
</code>```

However, this gives me syntax error. If I delete the GROUP BY line, I got results ordered from highest, but if any of the contestants scored in this discipline more than once, I got all of his scores.

If I delete the ORDER BY line, I got only one result per contestant, but it returns the first record in db, not the highest one.

How to fix this command to be valid? Also, there are some less_is_better disciplines, where I want the lowest score, but as far as I could use the ORDER BY on final query, it should be achieved by replacing DESC with ASC.
Thanks.

答:
Don't use group by.  Using select * with group by just doesn't make sense.  Instead, use a filter to get the row you want:

```<code>SELECT *
FROM contenstants c JOIN
     results r
     ON r.result_contestant = c.contestant_id
WHERE r.result_discipline = 1 AND c.contestant_category = 1 AND
      r.value = (select min(r2.value)
                 from results r2
                 where r2.result_contestant = r.result_contestant and
                       r2.result_discipline = r.result_discipline
                )
ORDER BY value DESC;
</code>```

Note: I'm not sure if you want min() or max() in the subquery.

Body:
I have two tables - results and contestants. Result table cointains

result_id (PK)

resul_contestant (who scored this)

value (how much did he scored)

result_discipline(where he scored this)

contestants table cointains

contestant_id (PK)

contestant_name

contestant_category

What I want to do is to select results for all contestants, but I only want to show one result per contestant - the highest (lowest) one.
So far I managed to do this:

SELECT * FROM contenstants
JOIN results ON result_contestant = contenstant_id
WHERE result_discipline = 1 AND contestant_category = 1
ORDER BY value DESC
GROUP BY contenstant_id;

However, this gives me syntax error. If I delete the GROUP BY line, I got results ordered from highest, but if any of the contestants scored in this discipline more than once, I got all of his scores.

If I delete the ORDER BY line, I got only one result per contestant, but it returns the first record in db, not the highest one.

How to fix this command to be valid? Also, there are some less_is_better disciplines, where I want the lowest score, but as far as I could use the ORDER BY on final query, it should be achieved by replacing DESC with ASC.
Thanks.

Body:
Don't use group by.  Using select * with group by just doesn't make sense.  Instead, use a filter to get the row you want:

SELECT *
FROM contenstants c JOIN
     results r
     ON r.result_contestant = c.contestant_id
WHERE r.result_discipline = 1 AND c.contestant_category = 1 AND
      r.value = (select min(r2.value)
                 from results r2
                 where r2.result_contestant = r.result_contestant and
                       r2.result_discipline = r.result_discipline
                )
ORDER BY value DESC;

Note: I'm not sure if you want min() or max() in the subquery.


问:
H1 tag pushes div down
Hello I have a problem and I cant find a good explained answer on the web.

I have two div's when I type some text with a h1 tag in the second div it pushes the div down. Even when I make the margin-top greater.

My code:

```<code><!DOCTYPE html>
<html lang="nl">
  <head>
    <meta charset="UTF-8" />
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link href="css/normalize" rel="stylesheet" />
    <style>

      #one {
        width: 100%;
        height: 50px;
        background-color: red
      }

      #two {
        width: 100%;
        height: 150px;
        background-color: blue
      }

      h1 {
        margin: 50px 0;
      }

    </style>
  </head>
  <body>
    <div id="one">

    </div>
    <div id="two">
      <h1>Hoi</h1>
    </div>
  </body>
</html>
</code>```

Example Picture

答:
The adjoining margins of two or more (or parent and child) box can combine to form a single margin, this combination is called collapsed margin.

W3C Reference: https://www.w3.org/TR/CSS2/box.html#collapsing-margins

Any value of overflow different from its default (visible) applied to the parent will prevent collapse.

Use overflow: hidden in the div #two will solve it.

Title: H1 tag pushes div down

Body:
Hello I have a problem and I cant find a good explained answer on the web.

I have two div's when I type some text with a h1 tag in the second div it pushes the div down. Even when I make the margin-top greater.

My code:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link href="css/normalize" rel="stylesheet" />

Hoi

Example Picture


问:
Faster alternative to push_back(size is known)
I have a float vector. As I process certain data, I push it back.I always know what the size will be while declaring the vector.

For the largest case, it is 172,490,752 floats. This takes about eleven seconds just to push_back everything.

Is there a faster alternative, like a different data structure or something?

答:
I have two answers for you:

As previous answers have pointed out, using reserve to allocate the storage beforehand can be quite helpful, but:

push_back (or emplace_back) themselves have a performance penalty because during every call, they have to check whether the vector has to be reallocated. If you know the number of elements you will insert already, you can avoid this penalty by directly setting the elements using the access operator []

So the most efficient way I would recommend is:

Initialize the vector with the 'fill'-constructor:

```<code>std::vector<float> values(172490752, 0.0f);
</code>```

Set the entries directly using the access operator:

```<code>values[i] = some_float;
++i;
</code>```

Body:
I have two answers for you:

As previous answers have pointed out, using reserve to allocate the storage beforehand can be quite helpful, but:

push_back (or emplace_back) themselves have a performance penalty because during every call, they have to check whether the vector has to be reallocated. If you know the number of elements you will insert already, you can avoid this penalty by directly setting the elements using the access operator []

So the most efficient way I would recommend is:

Initialize the vector with the 'fill'-constructor:

std::vector<float> values(172490752, 0.0f);

Set the entries directly using the access operator:

values[i] = some_float;
++i;


问:
Different Truncation Results When Casting
I'm having some some difficulty predicting how my C code will truncate results. Refer to the following:

```<code>float fa,fb,fc;
short ia,ib;

fa=160
fb=0.9;
fc=fa*fb;
ia=(short)fc;
ib=(short)(fa*fb);
</code>```

The results are ia=144, ib=143.

I can understand the reasoning for either result, but I don't understand why the two calculations are treated differently. Can anyone refer me to where this behaviour is defined or explain the difference?

Edit: the results are compiled with MS Visual C++ Express 2010 on Intel core i3-330m. I get the same results on gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5) under Virtual Box on the same machine.

答: The compiler is allowed to use more precision for a subexpression like fa*fb than it uses when assigning to a float variable like fc.  So it's the fc= part which is very slightly changing the result (and happening to then make a difference in the integer truncation).

Body:
I'm having some some difficulty predicting how my C code will truncate results. Refer to the following:

float fa,fb,fc;
short ia,ib;

fa=160
fb=0.9;
fc=fa*fb;
ia=(short)fc;
ib=(short)(fa*fb);

The results are ia=144, ib=143.

I can understand the reasoning for either result, but I don't understand why the two calculations are treated differently. Can anyone refer me to where this behaviour is defined or explain the difference?

Edit: the results are compiled with MS Visual C++ Express 2010 on Intel core i3-330m. I get the same results on gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5) under Virtual Box on the same machine.


问:
iOS https / Host dont't has SSL certificate
I ran into a problem and needs help. I send a request to the server via HTTPS but server don't has SSL certificate. How I can bypass check SSL certificate in iOS?

My Code:

```<code>let loginString = String(format: "Login:Pass")
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()

let headers = [
    "content-type": "application/xml",
    "authorization": "Basic \(base64LoginString)"
]

let postData = NSData(data: "BODY".data(using: String.Encoding.utf8)!)

let request = NSMutableURLRequest(url: URL(string: "IP")!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)

request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

var session = URLSession.shared
session = URLSession(configuration: URLSessionConfiguration.default, delegate: self as? URLSessionDelegate, delegateQueue: nil)
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in

    if (error != nil) {
        print(error.debugDescription)
    } else {
        let responseData = String(data: data!, encoding: String.Encoding.utf8)!
        print(responseData)
    }
})

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

My Error:

The certificate for this server is invalid. You might be connecting to a server that is pretending to be “IP” which could put your confidential information at risk.

Help me pls.

答: You need to allow Allow Arbitrary Loads. In your info.plist file, add this following entry

Body:
I ran into a problem and needs help. I send a request to the server via HTTPS but server don't has SSL certificate. How I can bypass check SSL certificate in iOS?

My Code:

let loginString = String(format: "Login:Pass")
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()

let headers = [
    "content-type": "application/xml",
    "authorization": "Basic \(base64LoginString)"
]

let postData = NSData(data: "BODY".data(using: String.Encoding.utf8)!)

let request = NSMutableURLRequest(url: URL(string: "IP")!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)

request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

var session = URLSession.shared
session = URLSession(configuration: URLSessionConfiguration.default, delegate: self as? URLSessionDelegate, delegateQueue: nil)
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in

    if (error != nil) {
        print(error.debugDescription)
    } else {
        let responseData = String(data: data!, encoding: String.Encoding.utf8)!
        print(responseData)
    }
})

dataTask.resume()

My Error:

The certificate for this server is invalid. You might be connecting to a server that is pretending to be “IP” which could put your confidential information at risk.

Help me pls.


问:
ticket machine in netbeans
I need some help in making this ticket machine code work. I can do it using if, else if and else, and I have seen it done with a while loop. However whenever I am trying to run it as an object I either get and error because of the print ticket at the bottom of the code, or build successful and no ticket. Here is my code</p>

```<code>package ticketmachine;

import javax.swing.JOptionPane;

public class TicketMachine {
    private int price;
    private int change;
    private int balance;

public int getPrice(){
    return price;
}

public int getBalance(){
    return balance;
}

public TicketMachine (int ticketCost) {
    price = ticketCost;
    change = 0;
    balance = 0;
}

public void insertMoney (int amount){
    balance = balance + amount;
}

public static void main(String[] args){

    String input1= JOptionPane.showInputDialog(null, " Insert a coin ");
    int ticketCost=Integer.parseInt(input1);

public void printTicket(){

    //Simulate the printing of a ticket
    System.out.println("##################");
    System.out.println("# Ticket");
    System.out.println("# " + price + " pence.");
    System.out.println("##################");
    System.out.println();
}
}
}
</code>```

答:
Here now it prints it </p>

```<code>import javax.swing.JOptionPane;
import java.sql.PreparedStatement;

public class TicketMachine {
    private int price;
    private int change;
    private int balance;

    public int getPrice(){
        return price;
    }

    public int getBalance(){
        return balance;
    }

    public TicketMachine (int ticketCost) {
        price = ticketCost;
        change = 0;
        balance = 0;
    }

    public void insertMoney (int amount){
        balance = balance + amount;
    }

    public static void main(String[] args) {

        String input1 = JOptionPane.showInputDialog(null, " Insert a coin ");
        int ticketCost = Integer.parseInt(input1);
        TicketMachine ticketMachine = new TicketMachine(ticketCost);
        ticketMachine.printTicket();
    }

    public void printTicket(){

        //Simulate the printing of a ticket
        System.out.println("##################");
        System.out.println("# Ticket");
        System.out.println("# " + this.price + " pence.");
        System.out.println("##################");
        System.out.println();
    }
}
</code>```

<p>You should really try to learn how OOP works. People say they don't understand what you need due to the fact that you aren't even calling that method that prints the thicket. </p>

Title: ticket machine in netbeans

Body:
I need some help in making this ticket machine code work. I can do it using if, else if and else, and I have seen it done with a while loop. However whenever I am trying to run it as an object I either get and error because of the print ticket at the bottom of the code, or build successful and no ticket. Here is my code

package ticketmachine;

import javax.swing.JOptionPane;

public class TicketMachine {
    private int price;
    private int change;
    private int balance;

public int getPrice(){
    return price;
}

public int getBalance(){
    return balance;
}

public TicketMachine (int ticketCost) {
    price = ticketCost;
    change = 0;
    balance = 0;
}

public void insertMoney (int amount){
    balance = balance + amount;
}

public static void main(String[] args){

    String input1= JOptionPane.showInputDialog(null, " Insert a coin ");
    int ticketCost=Integer.parseInt(input1);

public void printTicket(){

    //Simulate the printing of a ticket
    System.out.println("##################");
    System.out.println("# Ticket");
    System.out.println("# " + price + " pence.");
    System.out.println("##################");
    System.out.println();
}
}
}

Body:
Here now it prints it

import javax.swing.JOptionPane;
import java.sql.PreparedStatement;

public class TicketMachine {
    private int price;
    private int change;
    private int balance;

    public int getPrice(){
        return price;
    }

    public int getBalance(){
        return balance;
    }

    public TicketMachine (int ticketCost) {
        price = ticketCost;
        change = 0;
        balance = 0;
    }

    public void insertMoney (int amount){
        balance = balance + amount;
    }

    public static void main(String[] args) {

        String input1 = JOptionPane.showInputDialog(null, " Insert a coin ");
        int ticketCost = Integer.parseInt(input1);
        TicketMachine ticketMachine = new TicketMachine(ticketCost);
        ticketMachine.printTicket();
    }

    public void printTicket(){

        //Simulate the printing of a ticket
        System.out.println("##################");
        System.out.println("# Ticket");
        System.out.println("# " + this.price + " pence.");
        System.out.println("##################");
        System.out.println();
    }
}

You should really try to learn how OOP works. People say they don't understand what you need due to the fact that you aren't even calling that method that prints the thicket.


问:
Atom randomly opening files in the same (or different) tab
I have a project opened in Atom and, when I click on a file to open it, instead of always opening it in a different tab (as it was doing until now), now it randomly opens it in a new tab or in an existing one. Due to this behavior, it's closing files that I still want to have open.

Does anybody have a solution for this problem?

I'm using Atom 1.6.0. under Mac OS X 10.11.3

答:
This feature has been introduced in Atom 1.6.0.

Basically if you open the file with a single click, you take a peek at the contents of a file without opening it in a dedicated tab. When another item is opened in a pane, it replaces the pending tab.

When you simply double-click the file or the tab, the tab is automagically made permanent for you.

See: Major Changes in 1.6.0 Stable - Pending Pane Items

Pending Pane Items

When you single-click a file from the tree view or the find-and-replace search results, the file in question opens as a pending pane item. When another item is opened in a pane, it replaces the pending tab in that pane instead of being appended to the list of tabs. This allows you to quickly click through several files quickly without opening each of them in a dedicated tab. In the default UI configuration, the tab’s title is italicized if the pane item is pending. If you want the tab to stick around permanently, simply double-click the file or the tab; in addition, when you edit text within a text editor that lives in a pending tab, the tab is automagically made permanent for you. You can disable this functionality by unchecking Allow Pending Pane Items in the Core Settings section of the editor settings.


问:
parsing date and time in java
I have Time format in (yyyy-mm-ddTHH:mm+0:0000)..i need to convert this format to mm-dd-yyyy hh:mm am/pm using java program...any one help me to do this..thanx in advance...</p>

答:
Here’s the modern answer. SimpleDateFormat was the right answer in 2011 when the question was asked, but it isn’t any longer. The old classes turned out to be troublesome, so at long last their replacements came out early in 2014.

I was a bit puzzled about a couple of details in your formats.

yyyy-mm-ddTHH:mm+0:0000 looks a bit like an ISO 8601 offset date-time, but then +0:0000 should be the offset from UTC. I am speculating that it may have been intended as an offset in h:mmss format, but it is non-standard and nothing I have ever seen elsewhere.

You seem to be asking for am/pm in lowercase. This is non-standard too and not built-in with the standard classes.

I suggest:

```<code>    DateTimeFormatter sourceFormat
            = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm'+0:0000'");
    DateTimeFormatter targetFormat
            = DateTimeFormatter.ofPattern("MM-dd-uuuu hh:mm a", Locale.ENGLISH);

    String sourceTime = "2017-07-05T20:31+0:0000";
    String convertedTime = LocalDateTime.parse(sourceTime, sourceFormat)
            .format(targetFormat)
            .toLowerCase(Locale.ENGLISH);

    System.out.println(convertedTime);
</code>```

This prints

```<code>07-05-2017 08:31 pm
</code>```

I found it safest just to require literal +0:0000 in the input, not trying to interpret it. For producing pm in lowercase, I converted the whole string to lowercase after formatting. There is a different trick in this answer.

An attempt to be more flexible with hours, minutes and seconds in the offset and make sense of them could be:

```<code>    sourceTime = sourceTime.replaceFirst("(\\d:\\d{2})(\\d{2})$", "0$1:$2");
    String convertedTime = OffsetDateTime.parse(sourceTime)
            .format(targetFormat)
            .toLowerCase(Locale.ENGLISH);
</code>```

The replaceFirst converts 0:0000 to 00:00:00, which when preceeded by + or - conforms with an ISO 8601 offset. This will work with other offsets too (as long as hour is one digit; you may want to try both one and two digits in turn). In the concrete code we are still ignoring the offset when formatting, but it could be used for other purposes if desired.

DateTimeFormatter, LocalDateTime and OffsetDateTime are part of JSR-310. They are built in in Java 8 and later. You may use them in Java 6 and 7 too through the ThreeTen Backport. There is also a specific edition of the backport for Android, ThreeTenABP.

Title: parsing date and time in java

Body:
Here’s the modern answer. SimpleDateFormat was the right answer in 2011 when the question was asked, but it isn’t any longer. The old classes turned out to be troublesome, so at long last their replacements came out early in 2014.

I was a bit puzzled about a couple of details in your formats.

yyyy-mm-ddTHH:mm+0:0000 looks a bit like an ISO 8601 offset date-time, but then +0:0000 should be the offset from UTC. I am speculating that it may have been intended as an offset in h:mmss format, but it is non-standard and nothing I have ever seen elsewhere.

You seem to be asking for am/pm in lowercase. This is non-standard too and not built-in with the standard classes.

I suggest:

    DateTimeFormatter sourceFormat
            = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm'+0:0000'");
    DateTimeFormatter targetFormat
            = DateTimeFormatter.ofPattern("MM-dd-uuuu hh:mm a", Locale.ENGLISH);

    String sourceTime = "2017-07-05T20:31+0:0000";
    String convertedTime = LocalDateTime.parse(sourceTime, sourceFormat)
            .format(targetFormat)
            .toLowerCase(Locale.ENGLISH);

    System.out.println(convertedTime);

This prints

07-05-2017 08:31 pm

I found it safest just to require literal +0:0000 in the input, not trying to interpret it. For producing pm in lowercase, I converted the whole string to lowercase after formatting. There is a different trick in this answer.

An attempt to be more flexible with hours, minutes and seconds in the offset and make sense of them could be:

    sourceTime = sourceTime.replaceFirst("(\\d:\\d{2})(\\d{2})$", "0$1:$2");
    String convertedTime = OffsetDateTime.parse(sourceTime)
            .format(targetFormat)
            .toLowerCase(Locale.ENGLISH);

The replaceFirst converts 0:0000 to 00:00:00, which when preceeded by + or - conforms with an ISO 8601 offset. This will work with other offsets too (as long as hour is one digit; you may want to try both one and two digits in turn). In the concrete code we are still ignoring the offset when formatting, but it could be used for other purposes if desired.

DateTimeFormatter, LocalDateTime and OffsetDateTime are part of JSR-310. They are built in in Java 8 and later. You may use them in Java 6 and 7 too through the ThreeTen Backport. There is also a specific edition of the backport for Android, ThreeTenABP.


问:
VueJS + VUEX + VueRouter: Making A Component Unloadable?
I want to secure a certain route / component.

It should not be loadable.

How do I secure a route / component in VueJS?

答:
You can either use aliasing and redirecting: https://router.vuejs.org/en/essentials/redirect-and-alias.html

Or use Navigation Guards so you can display things if someone tries to get there: https://router.vuejs.org/en/advanced/navigation-guards.html


问:
How to delete an element from an array in C#
Lets say I have this array,

```<code>int[] numbers = {1, 3, 4, 9, 2};
</code>```

How can I delete an element by "name"? , lets say number 4?

Even ArrayList didn't help to delete?

```<code>string strNumbers = " 1, 3, 4, 9, 2";
ArrayList numbers = new ArrayList(strNumbers.Split(new char[] { ',' }));
numbers.RemoveAt(numbers.IndexOf(4));
foreach (var n in numbers)
{
    Response.Write(n);
}
</code>```

答:
You can also convert your array to a list and call remove on the list. You can then convert back to your array.</p>

```<code>int[] numbers = {1, 3, 4, 9, 2};
var numbersList = numbers.ToList();
numbersList.Remove(4);
</code>```

OwnerDisplayName: ahmed

Body:
Lets say I have this array,

int[] numbers = {1, 3, 4, 9, 2};

How can I delete an element by "name"? , lets say number 4?

Even ArrayList didn't help to delete?

string strNumbers = " 1, 3, 4, 9, 2";
ArrayList numbers = new ArrayList(strNumbers.Split(new char[] { ',' }));
numbers.RemoveAt(numbers.IndexOf(4));
foreach (var n in numbers)
{
    Response.Write(n);
}

LastEditorDisplayName: ahmed

Body:
You can also convert your array to a list and call remove on the list. You can then convert back to your array.

int[] numbers = {1, 3, 4, 9, 2};
var numbersList = numbers.ToList();
numbersList.Remove(4);


问:
Why do 7zip and gzip add 0x0A at the end of gzip compressed data
Wikipedia states(wrongly apparently at least for real world status) that gzip format demands that last 4 bytes are uncompressed size (mod 4GB).
I have fond the credible answer on SO that explains that sometimes there is junk at the end of the gzip data so you can not reply on last 4 bytes being size.

Unfortunately this matches my experiments(both terminal gzip and 7zip archiver add 0x0A byte for my small test example).

My question is what is the reason for this gzip and 7zip doing this?
Obviously they do it like that because they are written to do that, but I wonder about the motivation to break the format specification.
I know that some formats have padding requirements, but I found nothing for gzip.

edit:process:

echo "Testing rocks:) Debugging sucks :(" >> test_data

rm test_data.gz

gzip -6 test_data

vim -c "noautocmd edit test_data.gz"

in vim: :%!xxd -c 4

and last 5 bytes are size(35) and 0x0a (23 hex=35, then 00 00 00 0a)

7zip process is just using GUI to make a archive.

答:
Your testing process is wrong. Vim is what adds 0x0A to the end of the file. Here is a simpler test, using xxd directly (why did you even use Vim?):

```<code>echo "Testing rocks:) Debugging sucks :(" >> test_data
gzip -6 test_data
xxd -c 4 test_data.gz
</code>```

Output:

```<code>0000000: 1f8b 0808  ....
0000004: 453c 5d59  E<]Y
0000008: 0003 7465  ..te
000000c: 7374 5f64  st_d
0000010: 6174 6100  ata.
0000014: 0b49 2d2e  .I-.
0000018: c9cc 4b57  ..KW
000001c: 28ca 4fce  (.O.
0000020: 2eb6 d254  ...T
0000024: 7049 4d2a  pIM*
0000028: 4d4f 0789  MO..
000002c: 1497 0245  ...E
0000030: 14ac 34b8  ..4.
0000034: 00f4 a724  ...$
0000038: 5623 0000  V#..
000003c: 00         .
</code>```

As you can see, there is no 0x0A at the end. I think Vim adds newlines to the end of files by default, if they are not present.

Body:
Your testing process is wrong. Vim is what adds 0x0A to the end of the file. Here is a simpler test, using xxd directly (why did you even use Vim?):

echo "Testing rocks:) Debugging sucks :(" >> test_data
gzip -6 test_data
xxd -c 4 test_data.gz

Output:

0000000: 1f8b 0808  ....
0000004: 453c 5d59  E<]Y
0000008: 0003 7465  ..te
000000c: 7374 5f64  st_d
0000010: 6174 6100  ata.
0000014: 0b49 2d2e  .I-.
0000018: c9cc 4b57  ..KW
000001c: 28ca 4fce  (.O.
0000020: 2eb6 d254  ...T
0000024: 7049 4d2a  pIM*
0000028: 4d4f 0789  MO..
000002c: 1497 0245  ...E
0000030: 14ac 34b8  ..4.
0000034: 00f4 a724  ...$
0000038: 5623 0000  V#..
000003c: 00         .

As you can see, there is no 0x0A at the end. I think Vim adds newlines to the end of files by default, if they are not present.


问:
Previewing ARKit in the simulator with your phone
In this tutorial the person preview's ARKit on their phone.

https://www.youtube.com/watch?v=R8U8rGdMop4

Whenever I run the app it doesn't load the camera. Also, he somehow gets to preview the camera on the simulator. I can't seem to find the documentation on how to do this. It would be really helpful if I could view the camera through the simulator.

答:
You need a real device (with an A9 processor or better) with iOS 11 installed to preview ARKit.

In the video, he is using a physical device and the app Reflector 2 in order to show a preview on the screen. It's possible to stream live footage from an attached device with the QuickTime app as well.


问:
Extracting data from series of excel files
I have a series of Excel data with multiple cities and sensors in a single worksheet. What would be the fastest and most accurate way to extract data from a city X and a Y sensor?

In my case, I need only the data from the sensor "umidade_solo_nivel1".

I could do with pivot table, but it would take a lot of time, since there are 66 cities and a different Excel worksheet for each month of the year.

Following is an image of the worksheet that helps you understand how the data is organized.

Thank you in advance for any help you can provide.

答:
One solution is to set up your file to include "indicators" and the =INDIRECT() function.  Using this, you can set up a series of indicators (in separate rows) which include the sheet name, row, and column of data you are looking for.  This can be somewhat time-intensive to set up at first, but can definitely pay off in the long run, especially if your data are periodically updated or if more data is entered.  All it takes is a little creativity.

If you are not familiar with the function, you could check out this website:
http://www.contextures.com/xlFunctions05.html

As David Lee mentioned in your comments, VBA or other languages like Python or C# could also be of use.  As we can not fully understand what you need specifically or what all of your data look like from your description, I would recommend learning the function I mentioned and evaluating if it would be helpful in this context before learning another language like VBA (though I highly recommend learning VBA if you anticipate spending lots of time in Excel).


问:
Cannot access phoenix webserver hosted in debian azure VM
I'm trying to host a website in Azure using Phoenix. When I use a browser in the VM to go to the website it works and nmap is also showing that the ports are open.

However, when I go to the website from my own PC I cannot reach it. I suspected this to be caused by the network security group settings so I opened the ports:

However, it still doesn't work. What else can be causing this?

EDIT: nvm I must have been asleep when configuring the security group settings. Thanks to Justin Wood for pointing out the wrong port number.

答: You already have port 443 (HTTPS) open. You will probably want to open port 80 (HTTP) as well.</p>


问:
Authentication is required. You need to sign into your Google Account in phonegap
i am integrated in app purchase  i am getting these error

This is my config file

```<code><gap:plugin name="com.smartmobilesoftware.inappbilling">
<param name="BILLING_KEY" value="MIIBIjANBgkqhkiG9w0BAQE****/></gap:plugin>
</code>```

and my index.html file

```<code>    <!DOCTYPE HTML>
<html>
    <head>
        <title>In App Billing</title>
        <script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
        <script type="text/javascript" charset="utf-8" src="inappbilling.js"></script>
        <script type="text/javascript" charset="utf-8">
            function successHandler (result) {
                var strResult = "";
                if(typeof result === 'object') {
                    strResult = JSON.stringify(result);
                } else {
                    strResult = result;
                }
                alert("SUCCESS: \r\n"+strResult );
            }

            function errorHandler (error) {
                alert("ERROR: \r\n"+error );
            }

            // Click on init button
            function init(){
                // Initialize the billing plugin
                inappbilling.init(successHandler, errorHandler, {showLog:true};
            }

            // Click on purchase button
            function buy(){
                // make the purchase
                inappbilling.buy(successHandler, errorHandler,"gas");

            }

            // Click on ownedProducts button
            function ownedProducts(){
                // Initialize the billing plugin
                inappbilling.getPurchases(successHandler, errorHandler);

            }

            // Click on Consume purchase button
            function consumePurchase(){

                inappbilling.consumePurchase(successHandler, errorHandler, "gas");
            }

            // Click on subscribe button
            function subscribe(){
                // make the purchase
                inappbilling.subscribe(successHandler, errorHandler,"infinite_gas");

            }

            // Click on Query Details button
            function getDetails(){
                // Query the store for the product details
                inappbilling.getProductDetails(successHandler, errorHandler, ["gas","infinite_gas"]);

            }

            // Click on Get Available Products button
            function getAvailable(){
                // Get the products available for purchase.
                inappbilling.getAvailableProducts(successHandler, errorHandler);

            }

        </script>

    </head>
    <body>
        <h1>Hello World</h1>
        <button onclick="init();">Initalize the billing plugin</button>
        <button onclick="buy();">Purchase</button>
        <button onclick="ownedProducts();">Owned products</button>
        <button onclick="consumePurchase();">Consume purchase</button>
        <button onclick="subscribe();">Subscribe</button>
        <button onclick="getDetails();">Query Details</button>
        <button onclick="getAvailable();">Get Available Products</button>
    </body>
</html>
</code>```

above index.html shows all integration plugin.
i am integrating these app in build.phonegap.com.

and my product id is

Please help me where i am did mistack and how to solve these.For testing app in beta Still faceing these issues.

答:
In my case, I did not publish app on play it was in draft then I publish it in alpha testing and created test user with my tester Gmail account (separate account than developer account) and add it in some google group then click on the ‘BECOME A TESTER’ button to opt-in through that tester link by following the instruction on this blog. After 2, 3 hours of publishing, it was working fine.

Follow the instructions on this blog:

http://help.gamesalad.com/gamesalad-cookbook/7-using-pro-features/7-03-adding-in-app-purchases-iap/7-03-2-setting-up-iap-for-google-play/

Body:
i am integrated in app purchase  i am getting these error

This is my config file

<gap:plugin name="com.smartmobilesoftware.inappbilling">
<param name="BILLING_KEY" value="MIIBIjANBgkqhkiG9w0BAQE****/></gap:plugin>

and my index.html file

    <!DOCTYPE HTML>

        <title>In App Billing</title>

Hello World

        <button onclick="init();">Initalize the billing plugin</button>
        <button onclick="buy();">Purchase</button>
        <button onclick="ownedProducts();">Owned products</button>
        <button onclick="consumePurchase();">Consume purchase</button>
        <button onclick="subscribe();">Subscribe</button>
        <button onclick="getDetails();">Query Details</button>
        <button onclick="getAvailable();">Get Available Products</button>

above index.html shows all integration plugin.
i am integrating these app in build.phonegap.com.

and my product id is

Please help me where i am did mistack and how to solve these.For testing app in beta Still faceing these issues.


问:
How to generate tuples with some constant values with comprehension?
Is it possible to generate tuples with some constant values with comprehension?

I would like to have something like

```<code>[
(0, 'A', 'B'),
(1, 'A', 'B'),
(2, 'A', 'B'),
(3, 'A', 'B'),
...
]
</code>```

so I would take 0, 1, 2, 3, ... from range. But how to get As and Bs, which are not change?

答:
it's not because tuples are immutable that you cannot generate a list of tuples with a variable item only:

```<code>result = [(i,'A','B') for i in range(1,5)]

print(result)
</code>```

yields:

```<code>[(1, 'A', 'B'), (2, 'A', 'B'), (3, 'A', 'B'), (4, 'A', 'B')]
</code>```

Body:
Is it possible to generate tuples with some constant values with comprehension?

I would like to have something like

[
(0, 'A', 'B'),
(1, 'A', 'B'),
(2, 'A', 'B'),
(3, 'A', 'B'),
...
]

so I would take 0, 1, 2, 3, ... from range. But how to get As and Bs, which are not change?

Body:
it's not because tuples are immutable that you cannot generate a list of tuples with a variable item only:

result = [(i,'A','B') for i in range(1,5)]

print(result)

yields:

[(1, 'A', 'B'), (2, 'A', 'B'), (3, 'A', 'B'), (4, 'A', 'B')]