问:
cannot draw multiple shapes on canvas when using clearRect
when i use ctx.clearRect before drawing all objects only the last object is drawn (with updated chrome and firefox).
Everything is drawn without clearRect.</p>

```<code>//in interval
for(var i = 0;i<objects.length;i++){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    objects[i].draw();
}

function drawRect(x,y,w,h,fill){
    if(fill)
        ctx.fillRect(x-camera.x,y-camera.y,w,h);
    else
        ctx.strokeRect(x-camera.x,y-camera.y,w,h);
}

function square(pos,size){
    object.call(this);
    this.pos = pos;
    this.size = size;
    this.draw = function(){
        drawRect(this.pos.x,this.pos.y,this.size.x,this.size.y);
    }
}
</code>```

答:
You need to move the clearRect method call out of the loop body:

```<code>ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < objects.length; i++) {
    objects[i].draw();
}
</code>```

Otherwise, you will clear the canvas with the start of each loop iteration - which causes all objects apart from the last to be cleared.

Body:
when i use ctx.clearRect before drawing all objects only the last object is drawn (with updated chrome and firefox).
Everything is drawn without clearRect.

//in interval
for(var i = 0;i<objects.length;i++){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    objects[i].draw();
}

function drawRect(x,y,w,h,fill){
    if(fill)
        ctx.fillRect(x-camera.x,y-camera.y,w,h);
    else
        ctx.strokeRect(x-camera.x,y-camera.y,w,h);
}

function square(pos,size){
    object.call(this);
    this.pos = pos;
    this.size = size;
    this.draw = function(){
        drawRect(this.pos.x,this.pos.y,this.size.x,this.size.y);
    }
}

Body:
You need to move the clearRect method call out of the loop body:

ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < objects.length; i++) {
    objects[i].draw();
}

Otherwise, you will clear the canvas with the start of each loop iteration - which causes all objects apart from the last to be cleared.


来源: stackexchange

问:
Workaround on FileReference.save() dialog box
Im still new in Flex and currently working on capturing a flash game into a flv video file. Im using FileReference.save() to write the captured file in the user's system. It is working as of now but not the way I want it to be.

Is there a way to bypass or automate the save dialog box when invoking the save() api of fileReference?

答: AFAIK, no. This would be violation of Flash security model. Flash application cannot write to disk unless user allows it.</p>

ContentLicense: CC BY-SA 2.5


问:
Deploying to Heroku with Webpack
Hy guys. So, until now I have been doing it like this. Using webpack to make a bundle file, pushing code to github and deploying to Heroku. For this to work I had to push the bundle file to github.

Now, I would like to run webpack on Heroku. The thing is I have dependencies and devDependencies inside my package.json and if I want to run webpack on Heroku I need to install both. To do this I have to move a lot of devDependencies to dependencie so Heroku can install it and run webpack.

What is the best way to do this?

1) If I move all devDepend to dependencies and let Heroku make build file can I somehow clean and remove all unnecessary devDependencies afterwards?

2) Is there a way to do it without changing my package.json or setting set NPM_CONFIG_PRODUCTION=false and disabling production environment?

3) How would npm script look like to do this?

4) All in all what would be a best performance optimized way to push to Heroku ?

This is my package.json file

```<code>"scripts": {
    "clean-client": "rm -rf ./src/dist",
    "clean-server": "rm -rf ./src/build",
    "build-server": "babel src/server -d src/build -s --copy-files",
    "build-client": "webpack -p --config webpack.config.prod.babel.js",
    "start": "set \"NODE_ENV=production\" && npm run build-server && npm run build-client && node ./src/build/index.js",
    "start-dev": "set \"NODE_ENV=development\" && nodemon ./start-dev.js",
    "webpack": "webpack -w --config webpack.config.babel.js",
    "flow": "./node_modules/.bin/flow check",
    "test": "set \"NODE_ENV=test\" && babel-tape-runner -r \"test/setup.js\" \"test/**/*.test.jsx\" | node_modules/.bin/tap-spec",
    "coverage": "babel-node node_modules/babel-istanbul/lib/cli.js cover node_modules/babel-tape-runner/bin/babel-tape-runner -- \"test/setup.js\" -- \"test/**/*.test.jsx\""
  },
  "dependencies": {
    "babel-plugin-react-css-modules": "2.7.0",
    "babel-runtime": "^6.23.0",
    "ejs": "^2.5.6",
    "express": "^4.15.2",
    "prop-types": "^15.5.8",
    "react": "15.5.4",
    "react-dom": "15.5.4",
    "react-router": "3.0.4"
  },
  "devDependencies": {
    "babel-cli": "^6.24.1",
    "babel-core": "^6.24.1",
    "babel-eslint": "^7.2.3",
    "babel-istanbul": "^0.12.2",
    "babel-loader": "^7.0.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-plugin-webpack-alias": "^2.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "babel-register": "^6.24.1",
    "babel-tape-runner": "^2.0.1",
    "bootstrap": "v4.0.0-alpha.6",
    "browser-sync": "^2.18.8",
    "browser-sync-webpack-plugin": "^1.1.4",
    "css-loader": "0.28.0",
    "enzyme": "^2.8.2",
    "eslint": "^3.18.0",
    "eslint-config-standard": "^10.2.1",
    "eslint-plugin-flowtype": "^2.32.1",
    "eslint-plugin-react": "^6.10.3",
    "extract-text-webpack-plugin": "^2.1.0",
    "flow-bin": "^0.45.0",
    "ignore-styles": "^5.0.1",
    "jquery": "^3.2.1",
    "jsdom": "^10.1.0",
    "jsdom-global": "^3.0.2",
    "node-sass": "^4.5.2",
    "nodemon": "^1.11.0",
    "postcss": "^6.0.1",
    "postcss-cssnext": "2.10.0",
    "postcss-loader": "^2.0.5",
    "postcss-scss": "^1.0.0",
    "react-test-renderer": "^15.5.4",
    "sass-loader": "^6.0.3",
    "sass-resources-loader": "^1.2.1",
    "script-loader": "^0.7.0",
    "sinon": "^2.2.0",
    "sinon-test": "^1.0.2",
    "snazzy": "^7.0.0",
    "standard": "^10.0.2",
    "style-loader": "^0.17.0",
    "tap-spec": "^4.1.1",
    "tape": "^4.6.3",
    "tether": "^1.4.0",
    "webpack": "^2.4.1"
</code>```

答:
Per this guide you must set NPM_CONFIG_PRODUCTION to "false" and NODE_ENV to "development" in order for the devDependencies to be installed using npm install. If you are not using Heroku's Review Apps as the guide is, I believe you can set these environment variables via your apps dashboard.

Disclosure: I wrote the guide.

ContentLicense: CC BY-SA 3.0

Title: Deploying to Heroku with Webpack

Body:
Hy guys. So, until now I have been doing it like this. Using webpack to make a bundle file, pushing code to github and deploying to Heroku. For this to work I had to push the bundle file to github.

Now, I would like to run webpack on Heroku. The thing is I have dependencies and devDependencies inside my package.json and if I want to run webpack on Heroku I need to install both. To do this I have to move a lot of devDependencies to dependencie so Heroku can install it and run webpack.

What is the best way to do this?

1) If I move all devDepend to dependencies and let Heroku make build file can I somehow clean and remove all unnecessary devDependencies afterwards?

2) Is there a way to do it without changing my package.json or setting set NPM_CONFIG_PRODUCTION=false and disabling production environment?

3) How would npm script look like to do this?

4) All in all what would be a best performance optimized way to push to Heroku ?

This is my package.json file

"scripts": {
    "clean-client": "rm -rf ./src/dist",
    "clean-server": "rm -rf ./src/build",
    "build-server": "babel src/server -d src/build -s --copy-files",
    "build-client": "webpack -p --config webpack.config.prod.babel.js",
    "start": "set \"NODE_ENV=production\" && npm run build-server && npm run build-client && node ./src/build/index.js",
    "start-dev": "set \"NODE_ENV=development\" && nodemon ./start-dev.js",
    "webpack": "webpack -w --config webpack.config.babel.js",
    "flow": "./node_modules/.bin/flow check",
    "test": "set \"NODE_ENV=test\" && babel-tape-runner -r \"test/setup.js\" \"test/**/*.test.jsx\" | node_modules/.bin/tap-spec",
    "coverage": "babel-node node_modules/babel-istanbul/lib/cli.js cover node_modules/babel-tape-runner/bin/babel-tape-runner -- \"test/setup.js\" -- \"test/**/*.test.jsx\""
  },
  "dependencies": {
    "babel-plugin-react-css-modules": "2.7.0",
    "babel-runtime": "^6.23.0",
    "ejs": "^2.5.6",
    "express": "^4.15.2",
    "prop-types": "^15.5.8",
    "react": "15.5.4",
    "react-dom": "15.5.4",
    "react-router": "3.0.4"
  },
  "devDependencies": {
    "babel-cli": "^6.24.1",
    "babel-core": "^6.24.1",
    "babel-eslint": "^7.2.3",
    "babel-istanbul": "^0.12.2",
    "babel-loader": "^7.0.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-plugin-webpack-alias": "^2.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "babel-register": "^6.24.1",
    "babel-tape-runner": "^2.0.1",
    "bootstrap": "v4.0.0-alpha.6",
    "browser-sync": "^2.18.8",
    "browser-sync-webpack-plugin": "^1.1.4",
    "css-loader": "0.28.0",
    "enzyme": "^2.8.2",
    "eslint": "^3.18.0",
    "eslint-config-standard": "^10.2.1",
    "eslint-plugin-flowtype": "^2.32.1",
    "eslint-plugin-react": "^6.10.3",
    "extract-text-webpack-plugin": "^2.1.0",
    "flow-bin": "^0.45.0",
    "ignore-styles": "^5.0.1",
    "jquery": "^3.2.1",
    "jsdom": "^10.1.0",
    "jsdom-global": "^3.0.2",
    "node-sass": "^4.5.2",
    "nodemon": "^1.11.0",
    "postcss": "^6.0.1",
    "postcss-cssnext": "2.10.0",
    "postcss-loader": "^2.0.5",
    "postcss-scss": "^1.0.0",
    "react-test-renderer": "^15.5.4",
    "sass-loader": "^6.0.3",
    "sass-resources-loader": "^1.2.1",
    "script-loader": "^0.7.0",
    "sinon": "^2.2.0",
    "sinon-test": "^1.0.2",
    "snazzy": "^7.0.0",
    "standard": "^10.0.2",
    "style-loader": "^0.17.0",
    "tap-spec": "^4.1.1",
    "tape": "^4.6.3",
    "tether": "^1.4.0",
    "webpack": "^2.4.1"


问:
Why to use LinesOfCodeAvoidedAttribute class?
Reading the sample from PostSharp, I noticed something odd:

```<code>[LinesOfCodeAvoided(6)]
    public sealed class LogMethodAttribute : OnMethodBoundaryAspect
    {
</code>```

According to the documentation, it says that LineOfCodeAvoided it's just a number specifying the quantity of lines of code avoided instead of writing those manually.

Is this attribute really necessary? Why exists?

I don't see any benefits and I suppose that "if I avoid to code N lines of code" that's something I know, no something I need to tell to my program, right?

答:
One of the PostSharp code metrics is LOC Saved (Line of Code Saved). This attribute helps this metric to calculate how many lines you saved moving common code to aspects.

Ready-made aspects are just a part of the story. Your custom aspects also participate in avoiding boilerplate code. To benefit from accurate code saving information, you will need to tell PostSharp how much lines are avoided every time your aspect is used.

The easiest way is to add the [LinesOfCodeAvoided] attribute to your aspect class.

More information on this blog entry

Body:
Reading the sample from PostSharp, I noticed something odd:

[LinesOfCodeAvoided(6)]
    public sealed class LogMethodAttribute : OnMethodBoundaryAspect
    {

According to the documentation, it says that LineOfCodeAvoided it's just a number specifying the quantity of lines of code avoided instead of writing those manually.

Is this attribute really necessary? Why exists?

I don't see any benefits and I suppose that "if I avoid to code N lines of code" that's something I know, no something I need to tell to my program, right?


问:
React-Native Unable to resolve module
I'm getting the following error:

Dec 16 20:03:26 NathanHyland Bunny[21876]: Unable to resolve module socket.io-client/socket.io from /Users/nhyland/Documents/react-native/Bunny/index.ios.js: Invalid directory /Users/node_modules/socket.io-client/socket.io
  Dec 16 20:03:26 NathanHyland syslogd[21710]: ASL Sender Statistics

My index.io.js:

```<code>var React = require('react-native');
var {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    TouchableHighlight
    } = React;

import './UserAgent';
window.navigator.userAgent = "react-native";
var _ = require('lodash');
var io = require('socket.io-client/socket.io');

class Bunny extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.welcome}>
                    Welcome to React Native!
                </Text>
                <Text style={styles.instructions}>
                    To get started, edit index.ios.js
                </Text>
                <Text style={styles.instructions}>
                    Press Cmd+R to reload,{'\n'}
                    Cmd+D or shake for dev menu
                </Text>
                <TouchableHighlight onPress={() => {

      }}><Text>Test</Text></TouchableHighlight>
            </View>
        );
    }
}

var styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
});

AppRegistry.registerComponent('Bunny', () => Bunny);
</code>```

I've tried to link directly to the folder/file in node_modules and that doesn't work, I've tried different ways of importing and no bueno.

It installs just fine via npm install socket.io-client, I can see it in node-modules.

Any idea why it won't let me import?

答:
For people who land on this issue in future try include the "dist" folder in your require path like this:

```<code>var io = require('socket.io-client/dist/socket.io');
</code>```

See the github issue discussing this here.

Title: React-Native Unable to resolve module

Body:
I'm getting the following error:

Dec 16 20:03:26 NathanHyland Bunny[21876]: Unable to resolve module socket.io-client/socket.io from /Users/nhyland/Documents/react-native/Bunny/index.ios.js: Invalid directory /Users/node_modules/socket.io-client/socket.io
  Dec 16 20:03:26 NathanHyland syslogd[21710]: ASL Sender Statistics

My index.io.js:

var React = require('react-native');
var {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    TouchableHighlight
    } = React;

import './UserAgent';
window.navigator.userAgent = "react-native";
var _ = require('lodash');
var io = require('socket.io-client/socket.io');

class Bunny extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.welcome}>
                    Welcome to React Native!
                </Text>
                <Text style={styles.instructions}>
                    To get started, edit index.ios.js
                </Text>
                <Text style={styles.instructions}>
                    Press Cmd+R to reload,{'\n'}
                    Cmd+D or shake for dev menu
                </Text>
                <TouchableHighlight onPress={() => {

      }}><Text>Test</Text></TouchableHighlight>
            </View>
        );
    }
}

var styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
});

AppRegistry.registerComponent('Bunny', () => Bunny);

I've tried to link directly to the folder/file in node_modules and that doesn't work, I've tried different ways of importing and no bueno.

It installs just fine via npm install socket.io-client, I can see it in node-modules.

Any idea why it won't let me import?

Body:
For people who land on this issue in future try include the "dist" folder in your require path like this:

var io = require('socket.io-client/dist/socket.io');

See the github issue discussing this here.


问:
color skin icons but monochrome toolbar because plugin icons are black and white in CKEditor
For CKEditor, I have a color skin but am getting a monochrome toolbar.  There seems to be a conflict between the color icons under "skin" and the black-and-white icons under the individual plugins.

The skin is "moonocolor" and the color icons are under:

```<code>{CKEDITOR}/skins/moonocolor/icons/
</code>```

But there are black-and-white icons under the respective:

```<code>{CKEDITOR}/plugins/{plugin_name}/icons/
</code>```

I want color.  What do I need to do?  I thought that core/resourcemanager.js handled this type of stuff.

I should add that I am using the full source version of the product; lots of little files.

答:
Answering my own question.

Problem was that wrong icons appear in the toolbar.  I selected a skin, and the files are present, but are icons are not being used in the toolbar.  Config file "config.js" was built with the correct specification:

```<code>config.skin = 'moonocolor';
</code>```

But just now, I succeeded in getting the CKEditor toolbar to use the icons.  First I went into the skins directory, in my case, this was "moonocolor".

```<code>$  cd moonocolor
</code>```

In that directory, there is a program file called "skin.js".  I edited that. (My editor is "gvim".)

```<code>$  gvim skin.js
</code>```

At the bottom of the script, there is an anonymous function with immediate execution, except that it is all commented out.  To help you identify this function, note that it includes the following:

```<code>(function() {
    var icons = ('...long string listing plugin names...').split( ',' );

    var iconsFolder = CKEDITOR.getUrl( CKEDITOR.skin.path() + 'icons/' + ( CKEDITOR.env.hidpi ? 'hidpi/' : '' ) );

    for ( var i = 0; i < icons.length; i++ ) {
    CKEDITOR.skin.addIcon( icons[ i ], iconsFolder + icons[ i ] + '.png' );
    }
})();
</code>```

Uncomment the entire function.   When CKEditor starts up, it will find this file and run it, and at that time, this function will immediately execute.  (For readers not familiar with JavaScript, here's why it executes: The parenthesis surrounding the function definition, and the other parenthesis following that, together work to cause immediate execution.)  The reason that CKEditor finds this file in this subdirectory is because you told CKEditor about the subdirectory in the config file; see "config.skin = '...'" above.

The "for()" loop calls "addIcon()" for every plugin mentioned in the list.  The call to "addIcon()" specifies the desired subdirectory, via "CKEDITOR.skin.path()".  For each of the listed plugins, the desired "skins" subdirectory (in my case ".../skins/moonocolor") gets registered as the preferred source for an icon.

In that script, near that function, there are some comments that should be read.  The comments explain that in the production version, versus development version, the icons would have displayed automatically.  (I assume this is a reference to "minified" versus full source files.)

Body:
For CKEditor, I have a color skin but am getting a monochrome toolbar.  There seems to be a conflict between the color icons under "skin" and the black-and-white icons under the individual plugins.

The skin is "moonocolor" and the color icons are under:

{CKEDITOR}/skins/moonocolor/icons/

But there are black-and-white icons under the respective:

{CKEDITOR}/plugins/{plugin_name}/icons/

I want color.  What do I need to do?  I thought that core/resourcemanager.js handled this type of stuff.

I should add that I am using the full source version of the product; lots of little files.

Body:
Answering my own question.

Problem was that wrong icons appear in the toolbar.  I selected a skin, and the files are present, but are icons are not being used in the toolbar.  Config file "config.js" was built with the correct specification:

config.skin = 'moonocolor';

But just now, I succeeded in getting the CKEditor toolbar to use the icons.  First I went into the skins directory, in my case, this was "moonocolor".

$  cd moonocolor

In that directory, there is a program file called "skin.js".  I edited that. (My editor is "gvim".)

$  gvim skin.js

At the bottom of the script, there is an anonymous function with immediate execution, except that it is all commented out.  To help you identify this function, note that it includes the following:

(function() {
    var icons = ('...long string listing plugin names...').split( ',' );

    var iconsFolder = CKEDITOR.getUrl( CKEDITOR.skin.path() + 'icons/' + ( CKEDITOR.env.hidpi ? 'hidpi/' : '' ) );

    for ( var i = 0; i < icons.length; i++ ) {
    CKEDITOR.skin.addIcon( icons[ i ], iconsFolder + icons[ i ] + '.png' );
    }
})();

Uncomment the entire function.   When CKEditor starts up, it will find this file and run it, and at that time, this function will immediately execute.  (For readers not familiar with JavaScript, here's why it executes: The parenthesis surrounding the function definition, and the other parenthesis following that, together work to cause immediate execution.)  The reason that CKEditor finds this file in this subdirectory is because you told CKEditor about the subdirectory in the config file; see "config.skin = '...'" above.

The "for()" loop calls "addIcon()" for every plugin mentioned in the list.  The call to "addIcon()" specifies the desired subdirectory, via "CKEDITOR.skin.path()".  For each of the listed plugins, the desired "skins" subdirectory (in my case ".../skins/moonocolor") gets registered as the preferred source for an icon.

In that script, near that function, there are some comments that should be read.  The comments explain that in the production version, versus development version, the icons would have displayed automatically.  (I assume this is a reference to "minified" versus full source files.)


问:
What is the order of precedence when there are multiple Spring's environment profiles as set by spring.profiles.active
I am just wondering what the order of precedence is when multiple Spring active profiles have been specified.

Say I want the default profile to be active but the dev profile to override it when there are several identical elements (beans for instance) to choose from but with different profiles...

Say for instance I have two PropertySourcesPlaceholderConfigurer beans configured with "default" and "dev" values a environment profiles.

If I use the following profile activation: -Dspring.profiles.active="default,dev"

Will the dev profile override the default one?

If not how can the above behavior be achieved?

答: superEB is right the order of the profiles doesn't matter for beans, the declaration order is more important there, but keep in mind that the order is important if you use profile based configuration files!</p>


问:
Regex: replace all numbers and "number-like" strings except for years in range
I have the following string:

```<code>s = '2014 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'
</code>```

I want to replace with '' every part of this string which contains a number, except for those parts of the string that are in the year range 1950 to 2025. The resultant string would look like this (don't worry about the extraneous whitespace):

```<code>'2014          keep this text      2015 2025 '
</code>```

So, effectively I want the brute-force removal of anything and everything remotely "numerical," except for something standalone (i.e. not part of another string, and of length 4 excluding whitespace) that resembles a year.

I know I can use this to remove everything containing digits:

```<code>re.sub('\w*[0-9]\w*', '', s)
</code>```

But that doesn't return what I want:

```<code>'           keep this text        '
</code>```

Here's my attempt at replacing anything that doesn't match the patterns listed below:

```<code>re.sub(r'^([A-Za-z]+|19[5-9]\d|20[0-1]\d|202[0-5])', '*', s)
</code>```

Which returns:

```<code>'* 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'
</code>```

I've been here and here, but wasn't able to find what I was looking for.

答:
I would do it like this because it's readable and easy to fix of to improve:</p>

```<code>' '.join(
    filter(
        lambda word: (word.isdigit() and \
                      int(word) >= 1950 and \
                      int(word) <= 2025) or \
                     re.match(r'^[a-zA-Z]+$', word),
        s.split()
    )
)
# '2014 keep this text 2015 2025'
</code>```

Body:
I have the following string:

s = '2014 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'

I want to replace with '' every part of this string which contains a number, except for those parts of the string that are in the year range 1950 to 2025. The resultant string would look like this (don't worry about the extraneous whitespace):

'2014          keep this text      2015 2025 '

So, effectively I want the brute-force removal of anything and everything remotely "numerical," except for something standalone (i.e. not part of another string, and of length 4 excluding whitespace) that resembles a year.

I know I can use this to remove everything containing digits:

re.sub('\w*[0-9]\w*', '', s)

But that doesn't return what I want:

'           keep this text        '

Here's my attempt at replacing anything that doesn't match the patterns listed below:

re.sub(r'^([A-Za-z]+|19[5-9]\d|20[0-1]\d|202[0-5])', '*', s)

Which returns:

'* 2026 202 20 1000 1949 194 195092 20111a a2011a a2011 keep this text n0t th1s th0ugh 1 0 2015 2025 2026'

I've been here and here, but wasn't able to find what I was looking for.

Body:
I would do it like this because it's readable and easy to fix of to improve:

' '.join(
    filter(
        lambda word: (word.isdigit() and \
                      int(word) >= 1950 and \
                      int(word) <= 2025) or \
                     re.match(r'^[a-zA-Z]+$', word),
        s.split()
    )
)
# '2014 keep this text 2015 2025'


问:
StreamWriter: Starting and ending on a specific line number
I would like to ask some tips and help on a reading/writing part of my C#.

Situation:

I have to read a CSV file; - OK

If the CSV file name starts with "Load_", I want to write on another CSV the data from line 2 to the last one;

If the CSV file name starts with "RO_", I want to write on 2 different CSVs, 1 with the line 1 to 4 and the other 4 to the last one;

What I have so far is:

```<code>    public static void ProcessFile(string[] ProcessFile)
    {

        // Keeps track of your current position within a record
        int wCurrLine = 0;

        // Number of rows in the file that constitute a record
        const int LINES_PER_ROW = 1;
        int ctr = 0;
        foreach (string filename in ProcessFile)
        {

            var sbText = new System.Text.StringBuilder(100000);
            int stop_line = 0;
            int start_line = 0;

            // Used for the output name of the file
            var dir = Path.GetDirectoryName(filename);
            var fileName = Path.GetFileNameWithoutExtension(filename);
            var ext = Path.GetExtension(filename);
            var folderbefore = Path.GetFullPath(Path.Combine(dir, @"..\"));

            var lineCount = File.ReadAllLines(@filename).Length;

            string outputname = folderbefore + "output\\" + fileName;

            using (StreamReader Reader = new StreamReader(@filename))
            {

                if (filename.Contains("RO_"))
                {
                    start_line = 1;
                    stop_line = 5;
                }
                else
                {
                    start_line = 2;
                    stop_line = lineCount;
                }

                ctr = 0;
                while (!Reader.EndOfStream && ctr < stop_line)
                {
                    // Add the text
                    sbText.Append(Reader.ReadLine());

                    // Increment our current record row counter
                    wCurrLine++;

                    // If we have read all of the rows for this record
                    if (wCurrLine == LINES_PER_ROW)
                    {
                        // Add a line to our buffer
                        sbText.AppendLine();
                        // And reset our record row count
                        wCurrLine = 0;
                    }
                    ctr++;

                } // end of the while
            }

            int total_lenght = sbText.Length
            // When all of the data has been loaded, write it to the text box in one fell swoop
            using (StreamWriter Writer = new StreamWriter(dir + "\\" + "output\\" + fileName + "_out" + ext))
            {
                Writer.Write.(sbText.);
            }

        } // end of the foreach

    } // end of ProcessFile
</code>```

I was thinking about using the IF/ELSE: "using (StreamWriter Writer = new StreamWriter(dir + "\" + "output\" + fileName + "_out" + ext))" part. However, I am not sure how to pass, to StreamWriter, to only write from/to a specific line number.

Any Help is welcome! If I am missing some information, please, let me know (I am pretty new on stackoverflow).

Thank you.

答:
You can use LINQ to Take and Skip lines.

```<code>public abstract class CsvProcessor
{
    private readonly IEnumerable<string> processFiles;

    public CsvProcessor(IEnumerable<string> processFiles)
    {
        this.processFiles = processFiles;
    }

    protected virtual IEnumerable<string> GetAllLinesFromFile(string fileName)
    {
        using(var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
        using(var reader = new StreamReader(stream))
        {
            var line = String.Empty;
            while((line = reader.ReadLine()) != null)
            {
                yield return line;
            }
        }
    }

    protected virtual void ProcessFiles()
    {
        var sb1 = new StringBuilder();
        var sb2 = new StringBuilder();

        foreach(var file in this.processFiles)
        {
            var fileName = Path.GetFileNameWithoutExtension(file);
            var lines = GetAllLinesFromFile(file);

            if(fileName.StartsWith("RO_", StringComparison.InvariantCultureIgnoreCase))
            {
                sb1.AppendLine(lines.Take(4)); //take only the first four lines
                sb2.AppendLine(lines.Skip(4).TakeWhile(s => !String.IsNullOrEmpty(s))); //skip the first four lines, take everything else
            }
            else if(fileName.StartsWith("Load_", StringComparison.InvariantCultureIgnoreCase)
            {
                sb2.AppendLine(lines.Skip(1).TakeWhile(s => !String.IsNullOrEmpty(s)));
            }
        }

        // now write your StringBuilder objects to file...
    }

    protected virtual void WriteFile(StringBuilder sb1, StringBuilder sb2)
    {
        // ... etc..
    }
}
</code>```

Body:
I would like to ask some tips and help on a reading/writing part of my C#.

Situation:

I have to read a CSV file; - OK

If the CSV file name starts with "Load_", I want to write on another CSV the data from line 2 to the last one;

If the CSV file name starts with "RO_", I want to write on 2 different CSVs, 1 with the line 1 to 4 and the other 4 to the last one;

What I have so far is:

    public static void ProcessFile(string[] ProcessFile)
    {

        // Keeps track of your current position within a record
        int wCurrLine = 0;

        // Number of rows in the file that constitute a record
        const int LINES_PER_ROW = 1;
        int ctr = 0;
        foreach (string filename in ProcessFile)
        {

            var sbText = new System.Text.StringBuilder(100000);
            int stop_line = 0;
            int start_line = 0;

            // Used for the output name of the file
            var dir = Path.GetDirectoryName(filename);
            var fileName = Path.GetFileNameWithoutExtension(filename);
            var ext = Path.GetExtension(filename);
            var folderbefore = Path.GetFullPath(Path.Combine(dir, @"..\"));

            var lineCount = File.ReadAllLines(@filename).Length;

            string outputname = folderbefore + "output\\" + fileName;

            using (StreamReader Reader = new StreamReader(@filename))
            {

                if (filename.Contains("RO_"))
                {
                    start_line = 1;
                    stop_line = 5;
                }
                else
                {
                    start_line = 2;
                    stop_line = lineCount;
                }

                ctr = 0;
                while (!Reader.EndOfStream && ctr < stop_line)
                {
                    // Add the text
                    sbText.Append(Reader.ReadLine());

                    // Increment our current record row counter
                    wCurrLine++;

                    // If we have read all of the rows for this record
                    if (wCurrLine == LINES_PER_ROW)
                    {
                        // Add a line to our buffer
                        sbText.AppendLine();
                        // And reset our record row count
                        wCurrLine = 0;
                    }
                    ctr++;

                } // end of the while
            }

            int total_lenght = sbText.Length
            // When all of the data has been loaded, write it to the text box in one fell swoop
            using (StreamWriter Writer = new StreamWriter(dir + "\\" + "output\\" + fileName + "_out" + ext))
            {
                Writer.Write.(sbText.);
            }

        } // end of the foreach

    } // end of ProcessFile

I was thinking about using the IF/ELSE: "using (StreamWriter Writer = new StreamWriter(dir + "\" + "output\" + fileName + "_out" + ext))" part. However, I am not sure how to pass, to StreamWriter, to only write from/to a specific line number.

Any Help is welcome! If I am missing some information, please, let me know (I am pretty new on stackoverflow).

Thank you.

Body:
You can use LINQ to Take and Skip lines.

public abstract class CsvProcessor
{
    private readonly IEnumerable<string> processFiles;

    public CsvProcessor(IEnumerable<string> processFiles)
    {
        this.processFiles = processFiles;
    }

    protected virtual IEnumerable<string> GetAllLinesFromFile(string fileName)
    {
        using(var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
        using(var reader = new StreamReader(stream))
        {
            var line = String.Empty;
            while((line = reader.ReadLine()) != null)
            {
                yield return line;
            }
        }
    }

    protected virtual void ProcessFiles()
    {
        var sb1 = new StringBuilder();
        var sb2 = new StringBuilder();

        foreach(var file in this.processFiles)
        {
            var fileName = Path.GetFileNameWithoutExtension(file);
            var lines = GetAllLinesFromFile(file);

            if(fileName.StartsWith("RO_", StringComparison.InvariantCultureIgnoreCase))
            {
                sb1.AppendLine(lines.Take(4)); //take only the first four lines
                sb2.AppendLine(lines.Skip(4).TakeWhile(s => !String.IsNullOrEmpty(s))); //skip the first four lines, take everything else
            }
            else if(fileName.StartsWith("Load_", StringComparison.InvariantCultureIgnoreCase)
            {
                sb2.AppendLine(lines.Skip(1).TakeWhile(s => !String.IsNullOrEmpty(s)));
            }
        }

        // now write your StringBuilder objects to file...
    }

    protected virtual void WriteFile(StringBuilder sb1, StringBuilder sb2)
    {
        // ... etc..
    }
}

ContentLicense: CC BY-SA 4.0


问:
how to properly get a blob(MAX) image from SQL db
When i try to get a image as blob i get this response:
The Response content must be a string or object implementing __toString(), "boolean" given.

my code is as following,
The GET query

```<code>function GET_shopimages($shopid){
    $currentUserName = Auth::user()->name;
    $query = "SELECT * FROM srms_dam.dbo.pictures WHERE srms_dam.dbo.pictures.shopid = (?) ";
    $parameters = array((int) $shopid);
    return executeImageObjectQuery($query, $parameters);
}
</code>```

the executeImageObjectQuery:

```<code> function executeImageObjectQuery($inputQuery, $stagingParameters){
        $conn = buildConnection();
        if( $conn ) {
            $query = $inputQuery;
            $result = sqlsrv_query($conn, $query, $stagingParameters);
            $detailresult  = sqlsrv_fetch_array($result); echo '<img
            src="data:image/jpeg;base64,'.base64_encode( $result['picture'] ).'"/>';
            sqlsrv_close ($conn);
            return $detailresult;
      } else {
         return response('Cannot build database connection', 503);
    }
}
</code>```

I already looked at the different questions surrounding blob but could not find an answer, any help would be greatly appreciated.
the Query worked in the database itself.
$detailresult = $result here.

(if i need to insert my routing code please let me know)

Since this took to long to figure out i decided to just upload the picture path in the db and go from there. Question still remains though because i'm sure i am not the only one having this issue

答:
There is probably a typo error:

```<code>$result['picture']
</code>```

You fetch results into $detailresult and you should use it:

```<code>$detailresult['picture']
</code>```

Still, you may get some errors from your sql query, therefore I would use sqlsrv_errors.

Body:
When i try to get a image as blob i get this response:
The Response content must be a string or object implementing __toString(), "boolean" given.

my code is as following,
The GET query

function GET_shopimages($shopid){
    $currentUserName = Auth::user()->name;
    $query = "SELECT * FROM srms_dam.dbo.pictures WHERE srms_dam.dbo.pictures.shopid = (?) ";
    $parameters = array((int) $shopid);
    return executeImageObjectQuery($query, $parameters);
}

the executeImageObjectQuery:

 function executeImageObjectQuery($inputQuery, $stagingParameters){
        $conn = buildConnection();
        if( $conn ) {
            $query = $inputQuery;
            $result = sqlsrv_query($conn, $query, $stagingParameters);
            $detailresult  = sqlsrv_fetch_array($result); echo '';
            sqlsrv_close ($conn);
            return $detailresult;
      } else {
         return response('Cannot build database connection', 503);
    }
}

I already looked at the different questions surrounding blob but could not find an answer, any help would be greatly appreciated.
the Query worked in the database itself.
$detailresult = $result here.

(if i need to insert my routing code please let me know)

Since this took to long to figure out i decided to just upload the picture path in the db and go from there. Question still remains though because i'm sure i am not the only one having this issue

Body:
There is probably a typo error:

$result['picture']

You fetch results into $detailresult and you should use it:

$detailresult['picture']

Still, you may get some errors from your sql query, therefore I would use sqlsrv_errors.


问:
Java jSch Exec with progress bar and real time output to a JTextArea
I'm developing a program in java to download files directly to my server, for that I'm using jSch to connect via ssh and do a wget command, but i would like to stream the output to a JTextArea, and I've already done that, but it will only print it when the download is finished, and i would like to print it as the output of wget command in real time.

CustomOutputStream code:

```<code>public class CustomOutputStream extends OutputStream{
private JTextArea textArea;

    public CustomOutputStream(JTextArea textArea) {
        this.textArea = textArea;
    }

    @Override
    public void write(int b) throws IOException {
        // redirects data to the text area
        textArea.append(String.valueOf((char) b));
        // scrolls the text area to the end of data
        textArea.setCaretPosition(textArea.getText().length());
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        String s = new String(b,off,len);
        textArea.append(s);
        textArea.setCaretPosition(textArea.getText().length());
    }

    @Override
    public void write(byte[] b) throws IOException {
        this.write(b, 0, b.length);
    }
</code>```

}

here is the Exec code:

```<code>Properties props = new Properties();
    props.put("StrictHostKeyChecking", "no");
    int port = 22;

    JSch jsch=new JSch();

    Session session=jsch.getSession(username, host, 22);
    session.setConfig(props);
    session.setPassword(password);
    session.connect();
    String command =  "cd " + info.downPath + " && printf \"" + downLinks + "\" l> d.txt && wget -i d.txt";
    Channel channel=session.openChannel("exec");
    InputStream in=channel.getInputStream();
    OutputStream out = channel.getOutputStream();
    ((ChannelExec)channel).setCommand(command);
    //((ChannelExec)channel).setErrStream(System.err);
    //((ChannelExec)channel).setOutputStream(System.out);
    ((ChannelExec)channel).setErrStream(new CustomOutputStream(taOutput));
    //((ChannelExec)channel).setOutputStream(new CustomOutputStream(taOutput));
    channel.connect();
    byte[] tmp=new byte[1024];
    while(true){
      while(in.available()>0){
        int i=in.read(tmp, 0, 1024);
        if(i<0)break;
        System.out.print(new String(tmp, 0, i));
      }
      if(channel.isClosed()){
        if(in.available()>0) continue;
        System.out.println("exit-status: "+channel.getExitStatus());
        break;
      }
      try{Thread.sleep(1000);}catch(Exception ee){}
    }
    channel.disconnect();
    session.disconnect();
    bar.setValue(100);
</code>```

答:
try{Thread.sleep(1000);}catch(Exception ee){}

Your code is probably executing on the Event Dispatch Thread (EDT) and the Thread.sleep(...) is preventing the GUI from repainting itself until the task is finished executing.

So the solution is to start a separate Thread for the long running task so the EDT is able to respond to events.

An easy way do to this is to use a SwingWorker. Read the section from the Swing tutorial on Concurrency in Swing. The tutorial explains more about the EDT and SwingWorker.

Body:
I'm developing a program in java to download files directly to my server, for that I'm using jSch to connect via ssh and do a wget command, but i would like to stream the output to a JTextArea, and I've already done that, but it will only print it when the download is finished, and i would like to print it as the output of wget command in real time.

CustomOutputStream code:

public class CustomOutputStream extends OutputStream{
private JTextArea textArea;

    public CustomOutputStream(JTextArea textArea) {
        this.textArea = textArea;
    }

    @Override
    public void write(int b) throws IOException {
        // redirects data to the text area
        textArea.append(String.valueOf((char) b));
        // scrolls the text area to the end of data
        textArea.setCaretPosition(textArea.getText().length());
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        String s = new String(b,off,len);
        textArea.append(s);
        textArea.setCaretPosition(textArea.getText().length());
    }

    @Override
    public void write(byte[] b) throws IOException {
        this.write(b, 0, b.length);
    }

}

here is the Exec code:

Properties props = new Properties();
    props.put("StrictHostKeyChecking", "no");
    int port = 22;

    JSch jsch=new JSch();

    Session session=jsch.getSession(username, host, 22);
    session.setConfig(props);
    session.setPassword(password);
    session.connect();
    String command =  "cd " + info.downPath + " && printf \"" + downLinks + "\" l> d.txt && wget -i d.txt";
    Channel channel=session.openChannel("exec");
    InputStream in=channel.getInputStream();
    OutputStream out = channel.getOutputStream();
    ((ChannelExec)channel).setCommand(command);
    //((ChannelExec)channel).setErrStream(System.err);
    //((ChannelExec)channel).setOutputStream(System.out);
    ((ChannelExec)channel).setErrStream(new CustomOutputStream(taOutput));
    //((ChannelExec)channel).setOutputStream(new CustomOutputStream(taOutput));
    channel.connect();
    byte[] tmp=new byte[1024];
    while(true){
      while(in.available()>0){
        int i=in.read(tmp, 0, 1024);
        if(i<0)break;
        System.out.print(new String(tmp, 0, i));
      }
      if(channel.isClosed()){
        if(in.available()>0) continue;
        System.out.println("exit-status: "+channel.getExitStatus());
        break;
      }
      try{Thread.sleep(1000);}catch(Exception ee){}
    }
    channel.disconnect();
    session.disconnect();
    bar.setValue(100);


问:
CSS3 Spin Animation
I have reviewed quite a few demos and have no idea why I can't get the CSS3 spin to function. I am using the latest stable release of Chrome.

The fiddle:
http://jsfiddle.net/9Ryvs/1/

div {
  margin: 20px;
  width: 100px;
  height: 100px;
  background: #f00;
  -webkit-animation-name: spin;
  -webkit-animation-duration: 40000ms;
  -webkit-animation-iteration-count: infinite;
  -webkit-animation-timing-function: linear;
  -moz-animation-name: spin;
  -moz-animation-duration: 40000ms;
  -moz-animation-iteration-count: infinite;
  -moz-animation-timing-function: linear;
  -ms-animation-name: spin;
  -ms-animation-duration: 40000ms;
  -ms-animation-iteration-count: infinite;
  -ms-animation-timing-function: linear;
  -o-transition: rotate(3600deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

答:
HTML with font-awesome glyphicon.

```<code><span class="fa fa-spinner spin"></span>
</code>```

CSS

```<code>@-moz-keyframes spin {
    to { -moz-transform: rotate(360deg); }
}
@-webkit-keyframes spin {
    to { -webkit-transform: rotate(360deg); }
}
@keyframes spin {
    to {transform:rotate(360deg);}
}

.spin {
    animation: spin 1000ms linear infinite;
}
</code>```

Title: CSS3 Spin Animation

Body:
HTML with font-awesome glyphicon.

<span class="fa fa-spinner spin"></span>

CSS

@-moz-keyframes spin {
    to { -moz-transform: rotate(360deg); }
}
@-webkit-keyframes spin {
    to { -webkit-transform: rotate(360deg); }
}
@keyframes spin {
    to {transform:rotate(360deg);}
}

.spin {
    animation: spin 1000ms linear infinite;
}


问:
How to add 3rd party JQuery 'js' file to aurelia typescript navigation skeleton
I have simple Aurelia app based on aurelia navigation skeleton-typescript template (https://github.com/aurelia/skeleton-navigation/tree/master/skeleton-typescript) and I am trying to make it accept materia-dashboard.js file from Creative Tim Material Dashboard (https://github.com/creativetimofficial/material-dashboard) with no luck.

If I reference this in index.html, lib will not be accepted as when loaded, I get an error:

```<code>Uncaught ReferenceError: $ is not defined
    at material-dashboard.js:38
    at material-dashboard.js:46
</code>```

which I guess means that this file has dependency on JQuery which is not loaded in time.

I have also tried adding this to my config.js

```<code>"material-dashboard:src/material-dashboard": {
  "jquery": "npm:jquery@2.2.4"
},
</code>```

just pointing it directly to its source as well as to bundles.js

```<code>"dist/aurelia": {
    "includes" : [ ..., "material-dashboard", ...]
}
</code>```

and referencing is it main.js like bootstrap

```<code>import 'material-bootstrap';
</code>```

but this just kicks another error

```<code>system.src.js:1041
GET http://localhost:9000/dist/material-dashboard.js 404 (Not Found)
    W @ system.src.js:1041
    (anonymous) @ system.src.js:1777
    e._execute @ bluebird.min.js:31
    i._resolveFromExecutor @ bluebird.min.js:32
    i @ bluebird.min.js:32
    (anonymous) @ system.src.js:1776
    (anonymous) @ system.src.js:2801
    (anonymous) @ system.src.js:3379
    (anonymous) @ system.src.js:3711
    (anonymous) @ system.src.js:4103
    (anonymous) @ system.src.js:4568
    (anonymous) @ system.src.js:4837
    (anonymous) @ system.src.js:408
    r @ bluebird.min.js:33
    i._settlePromiseFromHandler @ bluebird.min.js:32
    i._settlePromise @ bluebird.min.js:32
    i._settlePromise0 @ bluebird.min.js:32
    i._settlePromises @ bluebird.min.js:32
    r._drainQueue @ bluebird.min.js:31
    r._drainQueues @ bluebird.min.js:31
    drainQueues @ bluebird.min.js:31

bluebird.min.js:33
Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:9000/dist/material-dashboard.js
    Error: XHR error (404 Not Found) loading http://localhost:9000/dist/material-dashboard.js
    Error loading http://localhost:9000/dist/material-dashboard.js as "material-dashboard" from http://localhost:9000/dist/main.js
</code>```

Any idea how to solve/understand this?

答:
this is how I get it to work:

config.js

```<code>"material": "/assets/js/material.min.js",
"material-dashboard": "/assets/js/material-dashboard.js"
</code>```

bundles.js

```<code>"dist/aurelia": {
    "includes" : [ ...,"material", "material-dashboard", ...]
}
</code>```

main.js

```<code>import 'material';
import 'material-bootstrap';
</code>```

which finally worked  gulp watch

Body:
I have simple Aurelia app based on aurelia navigation skeleton-typescript template (https://github.com/aurelia/skeleton-navigation/tree/master/skeleton-typescript) and I am trying to make it accept materia-dashboard.js file from Creative Tim Material Dashboard (https://github.com/creativetimofficial/material-dashboard) with no luck.

If I reference this in index.html, lib will not be accepted as when loaded, I get an error:

Uncaught ReferenceError: $ is not defined
    at material-dashboard.js:38
    at material-dashboard.js:46

which I guess means that this file has dependency on JQuery which is not loaded in time.

I have also tried adding this to my config.js

"material-dashboard:src/material-dashboard": {
  "jquery": "npm:jquery@2.2.4"
},

just pointing it directly to its source as well as to bundles.js

"dist/aurelia": {
    "includes" : [ ..., "material-dashboard", ...]
}

and referencing is it main.js like bootstrap

import 'material-bootstrap';

but this just kicks another error

system.src.js:1041
GET http://localhost:9000/dist/material-dashboard.js 404 (Not Found)
    W @ system.src.js:1041
    (anonymous) @ system.src.js:1777
    e._execute @ bluebird.min.js:31
    i._resolveFromExecutor @ bluebird.min.js:32
    i @ bluebird.min.js:32
    (anonymous) @ system.src.js:1776
    (anonymous) @ system.src.js:2801
    (anonymous) @ system.src.js:3379
    (anonymous) @ system.src.js:3711
    (anonymous) @ system.src.js:4103
    (anonymous) @ system.src.js:4568
    (anonymous) @ system.src.js:4837
    (anonymous) @ system.src.js:408
    r @ bluebird.min.js:33
    i._settlePromiseFromHandler @ bluebird.min.js:32
    i._settlePromise @ bluebird.min.js:32
    i._settlePromise0 @ bluebird.min.js:32
    i._settlePromises @ bluebird.min.js:32
    r._drainQueue @ bluebird.min.js:31
    r._drainQueues @ bluebird.min.js:31
    drainQueues @ bluebird.min.js:31

bluebird.min.js:33
Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:9000/dist/material-dashboard.js
    Error: XHR error (404 Not Found) loading http://localhost:9000/dist/material-dashboard.js
    Error loading http://localhost:9000/dist/material-dashboard.js as "material-dashboard" from http://localhost:9000/dist/main.js

Any idea how to solve/understand this?

Body:
this is how I get it to work:

config.js

"material": "/assets/js/material.min.js",
"material-dashboard": "/assets/js/material-dashboard.js"

bundles.js

"dist/aurelia": {
    "includes" : [ ...,"material", "material-dashboard", ...]
}

main.js

import 'material';
import 'material-bootstrap';

which finally worked  gulp watch


问:
Executing an async method after every n minutes
I have implemented an http module which will be fired on application start of my ASP.NET application

```<code>using System.Web;
using System.Threading.Tasks;
using System;
using System.Net.Http;

namespace BL.HttpModules
{
    public class MyCustomAsyncModule : IHttpModule
    {
        #region Static Privates

        private static bool applicationStarted = false;
        private readonly static object applicationStartLock = new object();

        #endregion

        public void Dispose()
        {

        }

        /// <summary>
        /// Initializes the specified module.
        /// </summary>
        /// <param name="httpApplication">The application context that instantiated and will be running this module.</param>
        public void Init(HttpApplication httpApplication)
        {
            if (!applicationStarted)
            {
                lock (applicationStartLock)
                {
                    if (!applicationStarted)
                    {
                        // this will run only once per application start
                         this.OnStart(httpApplication);
                    }
                }
            }
            // this will run on every HttpApplication initialization in the application pool
            this.OnInit(httpApplication);
        }

        public virtual void OnStart(HttpApplication httpApplication)
        {
            httpApplication.AddOnBeginRequestAsync(OnBegin, OnEnd);
        }

        private IAsyncResult OnBegin(object sender, EventArgs e, AsyncCallback cb, object extraData)
        {
            applicationStarted = true;
            var tcs = new TaskCompletionSource<object>(extraData);
            DoAsyncWork(HttpContext.Current).ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    tcs.SetException(t.Exception.InnerExceptions);
                }
                else
                {
                    tcs.SetResult(null);
                }
                if (cb != null) cb(tcs.Task);
            });
            return tcs.Task;
        }

        async Task DoAsyncWork(HttpContext ctx)
        {
            var client = new HttpClient();
            var result = await client.GetStringAsync("http://google.com");
            // USE RESULT
        }

        private void OnEnd(IAsyncResult ar)
        {
            Task t = (Task)ar;
            t.Wait();
        }

        /// <summary>Initializes any data/resources on HTTP module start.</summary>
        /// <param name="httpApplication">The application context that instantiated and will be running this module.</param>
        public virtual void OnInit(HttpApplication httpApplication)
        {
            // put your module initialization code here

        }

    }// end class
}// end namespace
</code>```

I want to fire DoAsyncWork after each 5 minutes. Can you help me achieving that goal in that module?

答: There is no built in way in IIS to reliably do this, you need to use a external process or a 3rd party library to scheduled the work to be done. Hangfire is a very popular library that lets you do both in process and out of process scheduled tasks.</p>

Body:
I have implemented an http module which will be fired on application start of my ASP.NET application

using System.Web;
using System.Threading.Tasks;
using System;
using System.Net.Http;

namespace BL.HttpModules
{
    public class MyCustomAsyncModule : IHttpModule
    {
        #region Static Privates

        private static bool applicationStarted = false;
        private readonly static object applicationStartLock = new object();

        #endregion

        public void Dispose()
        {

        }

        ///
        /// Initializes the specified module.
        ///
        /// <param name="httpApplication">The application context that instantiated and will be running this module.</param>
        public void Init(HttpApplication httpApplication)
        {
            if (!applicationStarted)
            {
                lock (applicationStartLock)
                {
                    if (!applicationStarted)
                    {
                        // this will run only once per application start
                         this.OnStart(httpApplication);
                    }
                }
            }
            // this will run on every HttpApplication initialization in the application pool
            this.OnInit(httpApplication);
        }

        public virtual void OnStart(HttpApplication httpApplication)
        {
            httpApplication.AddOnBeginRequestAsync(OnBegin, OnEnd);
        }

        private IAsyncResult OnBegin(object sender, EventArgs e, AsyncCallback cb, object extraData)
        {
            applicationStarted = true;
            var tcs = new TaskCompletionSource<object>(extraData);
            DoAsyncWork(HttpContext.Current).ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    tcs.SetException(t.Exception.InnerExceptions);
                }
                else
                {
                    tcs.SetResult(null);
                }
                if (cb != null) cb(tcs.Task);
            });
            return tcs.Task;
        }

        async Task DoAsyncWork(HttpContext ctx)
        {
            var client = new HttpClient();
            var result = await client.GetStringAsync("http://google.com");
            // USE RESULT
        }

        private void OnEnd(IAsyncResult ar)
        {
            Task t = (Task)ar;
            t.Wait();
        }

        /// Initializes any data/resources on HTTP module start.
        /// <param name="httpApplication">The application context that instantiated and will be running this module.</param>
        public virtual void OnInit(HttpApplication httpApplication)
        {
            // put your module initialization code here

        }

    }// end class
}// end namespace

I want to fire DoAsyncWork after each 5 minutes. Can you help me achieving that goal in that module?


问:
Web scraping with urllib
Im trying to do some simple web scraping and I keep getting this error, im not sure whats wrong as I am fairly new to python

Exception: a bytes-like object is required, not 'str'

```<code>import time
import urllib.request
import urllib.parse

stock = 'a'

def finvizKeyStats(stock):
    try:
        sourceCode = urllib.request.urlopen('http://finviz.com/quote.ashx?t='+stock).read()
        pbr = sourceCode.split('P/B</td><td width="8%" class="snapshot-td2" align="left"><b>')[1].split('</b></td>')[0]
        print(pbr)
    except Exception as e:
        print('Exception:', e)

finvizKeyStats('a')
</code>```

答:
Firstly you'll have to decode the Binary object into a string

```<code>sourceCodeString = sourceCode.decode()
</code>```

I would suggest you use urllib2 and BeautifulSoup there are number of tutorials available on the internet regarding web scraping with BeautifulSoup.

Title: Web scraping with urllib

Body:
Im trying to do some simple web scraping and I keep getting this error, im not sure whats wrong as I am fairly new to python

Exception: a bytes-like object is required, not 'str'

import time
import urllib.request
import urllib.parse

stock = 'a'

def finvizKeyStats(stock):
    try:
        sourceCode = urllib.request.urlopen('http://finviz.com/quote.ashx?t='+stock).read()
        pbr = sourceCode.split('P/B	')[1].split('	')[0]
        print(pbr)
    except Exception as e:
        print('Exception:', e)

finvizKeyStats('a')

Body:
Firstly you'll have to decode the Binary object into a string

sourceCodeString = sourceCode.decode()

I would suggest you use urllib2 and BeautifulSoup there are number of tutorials available on the internet regarding web scraping with BeautifulSoup.


问:
Stackoverflow error while generating a set of 2 non repeated random numbers from a range of numbers
Below are the 2 methods which I am using to generate a random number from a range of numbers.This is part of a small maths quiz. The number of questions can go upto 50 questions. The only clause is the numbers should be non repeated i.e 5x6 if is present in the list I cant have 6x5 in the list.

The problem that I am facing is the below code throws stackoverflow error.I have tried to run it in a separate thread but I am unable to get it working.

The for loop used inside the first method is the one I use to check if the number is already present.

```<code>public QuestionsV1 generateQuestionsArray(int level, int range) {
generateRandomNumbers(level, range);
    for (QuestionsV1 questions : questionsList) {
        if (questionsList != null && ((first_number == questions.getFirst_number() && second_number == questions.getSecond_number())
                || (first_number == questions.getSecond_number() &&
                second_number == questions.getFirst_number()))) {
            generateQuestionsArray(level, range);
            break;
        }
    }
    Log.d("ArrayList---", first_number + " " + second_number);
    QuestionsV1 questions = new QuestionsV1();
    questions.setFirst_number(first_number);
    questions.setSecond_number(second_number);
    questions.setOperator("x");
    questions.setCorrect_answer(first_number * second_number);
    return questions;
}

public void generateRandomNumbers(int level, int range) {
    Random rand1 = new Random();
    Random rand2 = new Random();
    if (range == 0) {
        first_number = rand1.nextInt(3 - 1 + 1) + 1;
    } else if (range == 1) {
        first_number = rand1.nextInt(6 - 4 + 1) + 4;
    } else if (range == 2) {
        first_number = rand1.nextInt(10 - 7 + 1) + 7;
    }
    switch (level) {
        case 1:
            second_number = rand2.nextInt(6 - 2 + 1) + 2;
            break;
        case 2:
            second_number = rand2.nextInt(12 - 7 + 1) + 7;
            break;
        case 3:
            second_number = rand2.nextInt(20 - 13 + 1) + 13;
            break;

    }
</code>```

below is the error which I am getting.

```<code>   Fatal Exception: java.lang.StackOverflowError: stack size 2MB
   at java.util.concurrent.atomic.AtomicLong.<init>(AtomicLong.java:61)
   at java.util.Random.<init>(Random.java:137)
   at java.util.Random.<init>(Random.java:105)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:80)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateQuestionsArray(Multiply.java:39)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbersHard(Multiply.java:74)
   at com.leapscale.scimat.t4e.Builders.Multiply.calculateNoOfQuestionsForLevels(Multiply.java:141)
   at com.leapscale.scimat.t4e.Builders.Multiply.getList(Multiply.java:146)
   at com.leapscale.scimat.t4e.Levels.Levels_Fragment$QuestionBuilder$1.run(Levels_Fragment.java:185)
   at java.lang.Thread.run(Thread.java:761)
</code>```

答:
Instead of using recursive call use a while loop to keep generating until a non-duplicate value is created.  Something similar to this:

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class App {
    private static final int QUESTION_COUNT = 25;
    private static final int RANGE = 10;
    private static final Random RAND = new Random();

    public static void main(String[] args) {
        App app = new App();
        app.generateAndDisplayQuestions();
    }

    private void generateAndDisplayQuestions() {
        List<QuestionV1> questions = new ArrayList<>();
        for (int q = 0; q < QUESTION_COUNT; q++) {
            while(true) {
                QuestionV1 question = getNextRandomQuestion();
                if (!questions.contains(question)) {
                    questions.add(question);
                    break;
                }
                System.out.println("found a duplicate - trying again...");
            }

            System.out.println("Question " + (q + 1) + ": first = " + questions.get(q).getFirst() + " : second = " + questions.get(q).getSecond());
        }
    }

    private QuestionV1 getNextRandomQuestion() {
        return new QuestionV1(RAND.nextInt(RANGE), RAND.nextInt(RANGE));
    }

    private class QuestionV1 {
        private int first;
        private int second;

        public QuestionV1(int first, int second) {
            this.first = first;
            this.second = second;
        }

        @Override
        public boolean equals(Object o) {
            QuestionV1 other = (QuestionV1)o;
            return (this.first == other.first && this.second == other.second) || (this.first == other.second && this.second == other.first);
        }

        @Override
        public int hashCode() {
            return first * 31 + second;
        }

        public int getFirst() {
            return first;
        }

        public int getSecond() {
            return second;
        }

    }

}
</code>```

Not that if RANGE is low and QUESTION_COUNTis high, then this will cause an infinite loop since all possible combinations will be used.

Body:
Below are the 2 methods which I am using to generate a random number from a range of numbers.This is part of a small maths quiz. The number of questions can go upto 50 questions. The only clause is the numbers should be non repeated i.e 5x6 if is present in the list I cant have 6x5 in the list.

The problem that I am facing is the below code throws stackoverflow error.I have tried to run it in a separate thread but I am unable to get it working.

The for loop used inside the first method is the one I use to check if the number is already present.

public QuestionsV1 generateQuestionsArray(int level, int range) {
generateRandomNumbers(level, range);
    for (QuestionsV1 questions : questionsList) {
        if (questionsList != null && ((first_number == questions.getFirst_number() && second_number == questions.getSecond_number())
                || (first_number == questions.getSecond_number() &&
                second_number == questions.getFirst_number()))) {
            generateQuestionsArray(level, range);
            break;
        }
    }
    Log.d("ArrayList---", first_number + " " + second_number);
    QuestionsV1 questions = new QuestionsV1();
    questions.setFirst_number(first_number);
    questions.setSecond_number(second_number);
    questions.setOperator("x");
    questions.setCorrect_answer(first_number * second_number);
    return questions;
}

public void generateRandomNumbers(int level, int range) {
    Random rand1 = new Random();
    Random rand2 = new Random();
    if (range == 0) {
        first_number = rand1.nextInt(3 - 1 + 1) + 1;
    } else if (range == 1) {
        first_number = rand1.nextInt(6 - 4 + 1) + 4;
    } else if (range == 2) {
        first_number = rand1.nextInt(10 - 7 + 1) + 7;
    }
    switch (level) {
        case 1:
            second_number = rand2.nextInt(6 - 2 + 1) + 2;
            break;
        case 2:
            second_number = rand2.nextInt(12 - 7 + 1) + 7;
            break;
        case 3:
            second_number = rand2.nextInt(20 - 13 + 1) + 13;
            break;

    }

below is the error which I am getting.

   Fatal Exception: java.lang.StackOverflowError: stack size 2MB
   at java.util.concurrent.atomic.AtomicLong.<init>(AtomicLong.java:61)
   at java.util.Random.<init>(Random.java:137)
   at java.util.Random.<init>(Random.java:105)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:80)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbers(Multiply.java:106)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateQuestionsArray(Multiply.java:39)
   at com.leapscale.scimat.t4e.Builders.Multiply.generateRandomNumbersHard(Multiply.java:74)
   at com.leapscale.scimat.t4e.Builders.Multiply.calculateNoOfQuestionsForLevels(Multiply.java:141)
   at com.leapscale.scimat.t4e.Builders.Multiply.getList(Multiply.java:146)
   at com.leapscale.scimat.t4e.Levels.Levels_Fragment$QuestionBuilder$1.run(Levels_Fragment.java:185)
   at java.lang.Thread.run(Thread.java:761)

Body:
Instead of using recursive call use a while loop to keep generating until a non-duplicate value is created.  Something similar to this:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class App {
    private static final int QUESTION_COUNT = 25;
    private static final int RANGE = 10;
    private static final Random RAND = new Random();

    public static void main(String[] args) {
        App app = new App();
        app.generateAndDisplayQuestions();
    }

    private void generateAndDisplayQuestions() {
        List<QuestionV1> questions = new ArrayList<>();
        for (int q = 0; q < QUESTION_COUNT; q++) {
            while(true) {
                QuestionV1 question = getNextRandomQuestion();
                if (!questions.contains(question)) {
                    questions.add(question);
                    break;
                }
                System.out.println("found a duplicate - trying again...");
            }

            System.out.println("Question " + (q + 1) + ": first = " + questions.get(q).getFirst() + " : second = " + questions.get(q).getSecond());
        }
    }

    private QuestionV1 getNextRandomQuestion() {
        return new QuestionV1(RAND.nextInt(RANGE), RAND.nextInt(RANGE));
    }

    private class QuestionV1 {
        private int first;
        private int second;

        public QuestionV1(int first, int second) {
            this.first = first;
            this.second = second;
        }

        @Override
        public boolean equals(Object o) {
            QuestionV1 other = (QuestionV1)o;
            return (this.first == other.first && this.second == other.second) || (this.first == other.second && this.second == other.first);
        }

        @Override
        public int hashCode() {
            return first * 31 + second;
        }

        public int getFirst() {
            return first;
        }

        public int getSecond() {
            return second;
        }

    }

}

Not that if RANGE is low and QUESTION_COUNTis high, then this will cause an infinite loop since all possible combinations will be used.


问:
How to remove HTML tags from rendered text
I am needing to remove the opening and closing
 tags from some rendered comment text. I pass the content to a component as a prop and i think that in doing so, it doesn't allow for the v-html directive to work correctly.

I need the content to render without the html tags

Here is where I am trying to render normally with v-html

```<code> <textarea class="form-control comment-inline-edit" v-html="content" name="comment-inline-edit" cols="45" rows="3"></textarea>
</code>```

And here is where I am passing the rendered content from the parent component

```<code><CommentEdit v-show="isEditting" :content="comment.content.rendered" v-on:cancel="cancelEdit" />
</code>```

Is there a VueJS way to do this other than using v-html?

答:
The question of how to remove HTML tags from text in javascript already has an answer.

The Vue way to do this would be to create a computed property that runs code to remove HTML tags from the rendered content and pass that to your CommentEdit component instead:

```<code>computed: {
  strippedContent() {
    let regex = /(<([^>]+)>)/ig;
    return this.comment.content.rendered.replace(regex, "");
  }
}
</code>```

```<code><CommentEdit v-show="isEditting" :content="strippedContent" />
</code>```

Body:
I am needing to remove the opening and closing
 tags from some rendered comment text. I pass the content to a component as a prop and i think that in doing so, it doesn't allow for the v-html directive to work correctly.

I need the content to render without the html tags

Here is where I am trying to render normally with v-html

 <textarea class="form-control comment-inline-edit" v-html="content" name="comment-inline-edit" cols="45" rows="3"></textarea>

And here is where I am passing the rendered content from the parent component

<CommentEdit v-show="isEditting" :content="comment.content.rendered" v-on:cancel="cancelEdit" />

Is there a VueJS way to do this other than using v-html?

Body:
The question of how to remove HTML tags from text in javascript already has an answer.

The Vue way to do this would be to create a computed property that runs code to remove HTML tags from the rendered content and pass that to your CommentEdit component instead:

computed: {
  strippedContent() {
    let regex = /(<([^>]+)>)/ig;
    return this.comment.content.rendered.replace(regex, "");
  }
}

<CommentEdit v-show="isEditting" :content="strippedContent" />


问:
What does "somevar >> 0" mean?

What does the notation somevar >> 0 mean in javascript?

Thanks

答: Bitwise right shift. Although somevar >> 0 looks weird.

Title: What does "somevar >> 0" mean?


问:
Qt Creator won't launch on Ubuntu (VBox)
I just installed Qt Creator on Ubuntu in VirtualBox and it won't launch. Does anyone know what could I do to make it work? </p>

答: It's most likely due to the OpenGL requirement not being met, they have a section on their FAQ regarding it: Creator FAQ.</p>


问:
cjson.decode() of a multi layer JSON
I want to decode a multi layered json object into a table and print the value of "temp".

p=666
d=23.42
payload='{"d":
             {"pres":'..(p)..',"temp":'..(d)..'}
         }'

t = cjson.decode(payload)
```

<p>My first idea was something like this: </p>

<pre class="lang-Lua prettyprint-override"><code>print(t["d"]["temp"])
</code>```

But this did not work. How can I improve this code so that it correctly decodes using Lua-CJson?

答:
Nesting Json directly does not seem to work with cJson ( atleast not on the ESP8266 with NodeMCU ) I found a solution by wrapping an array around the nested values.

```<code>p = 666
d = "23.42"
payload='{"d":[{"pres":'..(p)..',"temp":"'..(d)..'"}]}'
t = cjson.decode(payload)
print(t.d[1].temp) -- prints "23.42"
</code>```

# Note 1 - this means you have to address the array before calling the variable t.d[1] - Arrays in Lua begin with the number 1 and are NOT zero-based like many other scripting languages.

# Note 2 - for some reason I got a 'Malformed number' error with the floating point value ( variable d ). As a string the value is decoded without error. I had to make the variable a string and put "double quotation marks" around the value.
--> ah I found out I was working on a integer version of nodeMCU - which apparently does not support floating point numbers ...

Title: cjson.decode() of a multi layer JSON

Body:
I want to decode a multi layered json object into a table and print the value of "temp".

p=666
d=23.42
payload='{"d":
             {"pres":'..(p)..',"temp":'..(d)..'}
         }'

t = cjson.decode(payload)

My first idea was something like this:

print(t["d"]["temp"])

But this did not work. How can I improve this code so that it correctly decodes using Lua-CJson?

Body:
Nesting Json directly does not seem to work with cJson ( atleast not on the ESP8266 with NodeMCU ) I found a solution by wrapping an array around the nested values.

p = 666
d = "23.42"
payload='{"d":[{"pres":'..(p)..',"temp":"'..(d)..'"}]}'
t = cjson.decode(payload)
print(t.d[1].temp) -- prints "23.42"

# Note 1 - this means you have to address the array before calling the variable t.d[1] - Arrays in Lua begin with the number 1 and are NOT zero-based like many other scripting languages.

# Note 2 - for some reason I got a 'Malformed number' error with the floating point value ( variable d ). As a string the value is decoded without error. I had to make the variable a string and put "double quotation marks" around the value.
--> ah I found out I was working on a integer version of nodeMCU - which apparently does not support floating point numbers ...


问:
Cut JS string present in an array at every occurrance of a particular substring and append to same array
Note:
At this point in time, I'm unable to word the question title better. If someone is able to put it accross better, please go right ahead!

What I have:

```<code>var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]
</code>```

What I need:

```<code>["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]
</code>```

Basically, wherevever I see .$., I need to preserve it, then append everything before the occourrence of .$. along with everything before the occourrence of .$

Example:

difference.$.user.$.otherinformation should be parsed to contain:

```<code>difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation
</code>```

I'm strongly feeling that some sort of recursion is to be involved here, but have not progressed in that direction yet.

Below is my implementation for the same, but unfortunately, my when my substring matches the first occourrence of .$., it stops and does not proceed to further check for other occurrences of .$. in the same string.

How best can I take this to closure?

Current flawed implementation:

```<code>for(var i=0; i<array.length; i++){
    //  next, replace all array field references with $ as that is what autoform's pick() requires
    //  /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
    array[i] = array[i].replace(/\.\d+\./g,".$.");
        if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
            console.log("Substring without .$.  " + array[i].substring(0, array[i].indexOf('.$.')));
            console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')));
            }
        }
    // finally remove any duplicates if any
    array = _.uniq(array);
</code>```

答:
You can use this function inside your array loop.

var test = "difference.$.user.$.otherinformation";

function toArray(testString) {
  var testArr = testString.split(".")

  var tempString = "";
  var finalArray = [];

  for (var i = 0; i < testArr.length; i++) {

    var toTest = testArr[i];

    if (toTest == "$") {
      tempString += ".$"
    } else {
      if (i != 0) {
        tempString += ".";
      }

      tempString += toTest;
    }

    finalArray.push(tempString)

  }
  return finalArray;
}
console.log(toArray(test))```

Body:
Note:
At this point in time, I'm unable to word the question title better. If someone is able to put it accross better, please go right ahead!

What I have:

var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]

What I need:

["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]

Basically, wherevever I see .$., I need to preserve it, then append everything before the occourrence of .$. along with everything before the occourrence of .$

Example:

difference.$.user.$.otherinformation should be parsed to contain:

difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation

I'm strongly feeling that some sort of recursion is to be involved here, but have not progressed in that direction yet.

Below is my implementation for the same, but unfortunately, my when my substring matches the first occourrence of .$., it stops and does not proceed to further check for other occurrences of .$. in the same string.

How best can I take this to closure?

Current flawed implementation:

for(var i=0; i<array.length; i++){
    //  next, replace all array field references with $ as that is what autoform's pick() requires
    //  /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
    array[i] = array[i].replace(/\.\d+\./g,".$.");
        if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
            console.log("Substring without .$.  " + array[i].substring(0, array[i].indexOf('.$.')));
            console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')));
            }
        }
    // finally remove any duplicates if any
    array = _.uniq(array);


问:
Get variable by name from a String
Example code:

```<code>int width = 5;
int area = 8;
int potato = 2;
int stackOverflow = -4;
</code>```

Now, say I want to have the user input a string:

```<code>String input = new Scanner(System.in).nextLine();
</code>```

Then, say the user inputs potato. How would I retrieve the variable named potato and do stuff with it? Something like this:

```<code>System.getVariable(input); //which will be 2
System.getVariable("stackOverflow"); //should be -4
</code>```

I looked up some things and did not find much; I did find a reference to something called "the Reflection API," but that seems too complicated for this one simple task.

Is there a way to do this, and if so, what is it? If "Reflection" does indeed work and if it is the only way, then how would I use it to do this? The tutorial page for it has all sorts of internal stuff that I can't make any sense of.

EDIT: I need to keep the Strings in the variables for what I am doing. (I can't use a Map)

答:
I have another solution without a map : </p>

```<code>class Vars {
    Integer potato, stack;
    public Vars(a,b) {
        potato=a;
        stack=b;
    }
}
Object object=(Object)new Vars(1,2);
Class<?> c = object.getClass();
Integer result=(Integer)c.getField("potato").get(object);
</code>```

Title: Get variable by name from a String

Body:
Example code:

int width = 5;
int area = 8;
int potato = 2;
int stackOverflow = -4;

Now, say I want to have the user input a string:

String input = new Scanner(System.in).nextLine();

Then, say the user inputs potato. How would I retrieve the variable named potato and do stuff with it? Something like this:

System.getVariable(input); //which will be 2
System.getVariable("stackOverflow"); //should be -4

I looked up some things and did not find much; I did find a reference to something called "the Reflection API," but that seems too complicated for this one simple task.

Is there a way to do this, and if so, what is it? If "Reflection" does indeed work and if it is the only way, then how would I use it to do this? The tutorial page for it has all sorts of internal stuff that I can't make any sense of.

EDIT: I need to keep the Strings in the variables for what I am doing. (I can't use a Map)

Body:
I have another solution without a map :

class Vars {
    Integer potato, stack;
    public Vars(a,b) {
        potato=a;
        stack=b;
    }
}
Object object=(Object)new Vars(1,2);
Class<?> c = object.getClass();
Integer result=(Integer)c.getField("potato").get(object);


问:
How does one specify a particular cipher suite for a nginx docker instance?
I am running a newly built discourse docker image on Google Compute Engine.  I converted that to use https using letsencrypt following the walk through and I get an A+ rating from ssllabs.  However the scripting agent I'm using doesn't support either of the two TLS 1.0 cipher suites enabled [TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA] and I'd like to add TLS-DHE-RSA-WITH-AES-256-CBC-SHA which is supported by the open source rebol3 fork ren-c.

I've modified my web.ssl.template.yml file from

```<code>ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:\
ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:\
ECDHE-RSA-AES256-SHA;
</code>```

to

```<code>ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:\
ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:\
ECDHE-RSA-AES256-SHA:TLS-DHE-RSA-WITH-AES-256-CBC-SHA;
</code>```

and rebuilt the app using

```<code>sudo ./launcher rebuild app
</code>```

but this doesn't alter the cipher_suites available.

I'm now wondering if I have to alter the nginx.conf directly, wherever that is, instead of asking the discourse build script to do it ...

答:
mkdir -p containers/templates

cp templates/web.ssl.template.yml containers/templates

fuss with the file

add containers/templates/web.ssl.template.yml to you app.yml file in the templates section

profit

Body:
I am running a newly built discourse docker image on Google Compute Engine.  I converted that to use https using letsencrypt following the walk through and I get an A+ rating from ssllabs.  However the scripting agent I'm using doesn't support either of the two TLS 1.0 cipher suites enabled [TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA] and I'd like to add TLS-DHE-RSA-WITH-AES-256-CBC-SHA which is supported by the open source rebol3 fork ren-c.

I've modified my web.ssl.template.yml file from

ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:\
ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:\
ECDHE-RSA-AES256-SHA;

to

ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:\
ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:\
ECDHE-RSA-AES256-SHA:TLS-DHE-RSA-WITH-AES-256-CBC-SHA;

and rebuilt the app using

sudo ./launcher rebuild app

but this doesn't alter the cipher_suites available.

I'm now wondering if I have to alter the nginx.conf directly, wherever that is, instead of asking the discourse build script to do it ...


问:
Unable to get result from stdout with subprocess
I need to get the result being displayed in the console after issuing a command.

e.g.: H:/path/to/openssl.exe x509 -in H:/path/to/cert.pem -noout -subject

This command produces values of an encrypted certificate when placed in an opened cmd.exe but I am unable to get the same result as a returned variable using the subprocess module.

So far I have attempted (where cmd is the e.g. above):

```<code># checking if output is going to stderr
out = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
# attempt with Popen
out = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()[0]
# attempt with Popen not using communicate()
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
out = p.stdout.read()
</code>```

All the print (out) values are b''.

I have even broken the cmd into multiple args for both check_output() and Popen() such that it would look like: ["H:/path/to/openssl.exe", "x509 -in H:/path/to/cert.pem -noout -subject"].

I do have an alternative method to achieve the result, but that requires running a .bat file that contains the command: start cmd /k "... > H:/path/to/temp.txt" where the ... is the command in question here. This redirects the .exe output to a temp file (for security purposes) which I delete after reading contents into a variable.

Supporting information:

If the first part of the command is run (the .exe) it opens custom console for that program. The remainder of the command is executed in that console and then that console closes. However if the whole command series is used in a cmd.exe console, the output is displayed in that console. Hence why the use of " " in my alternate method of a .bat as it issues it to the open console as a whole command.

Use of subprocess.Popen(["cmd.exe"]) opens a console at C:\Python36> and I can issue the command in question and get the exact result I want. I cannot seem to grab it pythonically though. However, subprocess.Popen(["cmd.exe", "H:/path/to/openssl.exe"]) does not execute the second command; opens a console but does not start the .exe console.

Update:

I was able to get a result, but I don't like how I got there. Is there a shorter way to do the following:

```<code>p = subprocess.Popen("H:/path/to/openssl.exe", stdin=PIPE, stdout=PIPE)
# b for byte-type requirement
p.stdin.write(b"x509 -in H:/path/to/cert.pem -noout -subject")
p.stdin.close()
out = p.stdout.read()
</code>```

I can also produce the result with:

p = os.popen("start cmd /k H:/path/to/openssl.exe -in H:/path/to/cert.pem -noout -subject")

Tried to add .read() to the above, but prints a blank line

答:
Have you tried storing the entire command as raw string and passing it with shell=True

cmd = r'H:/path/to/openssl.exe x509 -in H:/path/to/cert.pem -noout -subject'
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = p.communicate()
print(out[0]) #for std out
print(out[1]) # for std err

Edit: This worked for me with stderr,

print p.communicate()[1]

b'unable to load certificate\r\n3636:error:0D07209B:asn1 encoding routines:ASN1_
get_object:too long:./crypto/asn1/asn1_lib.c:142:\r\n3636:error:0D068066:asn1 en
coding routines:ASN1_CHECK_TLEN:bad object header:./crypto/asn1/tasn_dec.c:1281:
\r\n3636:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 erro
r:./crypto/asn1/tasn_dec.c:380:Type=X509\r\n3636:error:0906700D:PEM routines:PEM
_ASN1_read_bio:ASN1 lib:./crypto/pem/pem_oth.c:83:\r\n'

Body:
I need to get the result being displayed in the console after issuing a command.

e.g.: H:/path/to/openssl.exe x509 -in H:/path/to/cert.pem -noout -subject

This command produces values of an encrypted certificate when placed in an opened cmd.exe but I am unable to get the same result as a returned variable using the subprocess module.

So far I have attempted (where cmd is the e.g. above):

# checking if output is going to stderr
out = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
# attempt with Popen
out = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()[0]
# attempt with Popen not using communicate()
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
out = p.stdout.read()

All the print (out) values are b''.

I have even broken the cmd into multiple args for both check_output() and Popen() such that it would look like: ["H:/path/to/openssl.exe", "x509 -in H:/path/to/cert.pem -noout -subject"].

I do have an alternative method to achieve the result, but that requires running a .bat file that contains the command: start cmd /k "... > H:/path/to/temp.txt" where the ... is the command in question here. This redirects the .exe output to a temp file (for security purposes) which I delete after reading contents into a variable.

Supporting information:

If the first part of the command is run (the .exe) it opens custom console for that program. The remainder of the command is executed in that console and then that console closes. However if the whole command series is used in a cmd.exe console, the output is displayed in that console. Hence why the use of " " in my alternate method of a .bat as it issues it to the open console as a whole command.

Use of subprocess.Popen(["cmd.exe"]) opens a console at C:\Python36> and I can issue the command in question and get the exact result I want. I cannot seem to grab it pythonically though. However, subprocess.Popen(["cmd.exe", "H:/path/to/openssl.exe"]) does not execute the second command; opens a console but does not start the .exe console.

Update:

I was able to get a result, but I don't like how I got there. Is there a shorter way to do the following:

p = subprocess.Popen("H:/path/to/openssl.exe", stdin=PIPE, stdout=PIPE)
# b for byte-type requirement
p.stdin.write(b"x509 -in H:/path/to/cert.pem -noout -subject")
p.stdin.close()
out = p.stdout.read()

I can also produce the result with:

p = os.popen("start cmd /k H:/path/to/openssl.exe -in H:/path/to/cert.pem -noout -subject")

Tried to add .read() to the above, but prints a blank line


问:
How to store .raw or raw bytes of pictures to local disk documents folder without png or jpeg representation
I want to store the raw bytes of a captured picture using AVCaptureSession. But I have only seen examples of pngrepresentation and jpegrepresentation. I want to store the raw data bytes in local disk documents of phone so it can be reopened at other times and converted into a UIImage for post processing. Is there a way to do this?
for example:

```<code>CVPixelBufferLockBaseAddress(pixelBuffer, 0);
GLubyte *rawImageBytes = CVPixelBufferGetBaseAddress(pixelBuffer);
</code>```

Can I store rawImageBytes in documents to open it later?

答:
Sure you can. Create an NSData object containing your bytes and save that using one of the NSData file saving methods (e.g. writeToURL:atomically:.)

You'll need to know the number of bytes in your pixelBuffer though. It looks like you should use CVPixelBufferGetDataSize to get the number of bytes.

Body:
I want to store the raw bytes of a captured picture using AVCaptureSession. But I have only seen examples of pngrepresentation and jpegrepresentation. I want to store the raw data bytes in local disk documents of phone so it can be reopened at other times and converted into a UIImage for post processing. Is there a way to do this?
for example:

CVPixelBufferLockBaseAddress(pixelBuffer, 0);
GLubyte *rawImageBytes = CVPixelBufferGetBaseAddress(pixelBuffer);

Can I store rawImageBytes in documents to open it later?


问:
JComboBox actions
Is there a way to distinguish between a JComboBox's index being changed programatically using setSelectedBoundValue and by clicking on the JComboBox?</p>

答:
This is ugly and truly a hack, but works!

The ActionEvent contains a field modifiers which in this case is the mouse button id. So using that may help you distinguish between setSelectedIndex or setSelectedValue and mouse clicks (by the way setSelectedBoundValue is not a method on JComboBox):

```<code>box.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getModifiers() != 0) {
            // ~ mouse button pressed ;)
        }
    }
});
</code>```

Title: JComboBox actions

Body:
This is ugly and truly a hack, but works!

The ActionEvent contains a field modifiers which in this case is the mouse button id. So using that may help you distinguish between setSelectedIndex or setSelectedValue and mouse clicks (by the way setSelectedBoundValue is not a method on JComboBox):

box.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getModifiers() != 0) {
            // ~ mouse button pressed ;)
        }
    }
});