问:
Submitting Pig job from Google Cloud Dataproc does not add custom jars to Pig classpath
I'm trying to submit a Pig job via Google Cloud Dataproc and include a custom jar that implements a custom load function I use in the Pig script, but I can't find out how to do that.

Adding my custom jar through the UI appears DOES NOT add it to the Pig classpath.

Here's the output of the Pig job, showing it fails to find my class:

```<code>17/03/29 16:12:21 INFO pig.ExecTypeProvider: Trying ExecType : LOCAL
17/03/29 16:12:21 INFO pig.ExecTypeProvider: Trying ExecType : MAPREDUCE
17/03/29 16:12:21 INFO pig.ExecTypeProvider: Picked MAPREDUCE as the ExecType
2017-03-29 16:12:21,961 [main] INFO  org.apache.pig.Main - Apache Pig version 0.16.0 (r: unknown) compiled Nov 27 2016, 23:14:51
2017-03-29 16:12:21,961 [main] INFO  org.apache.pig.Main - Logging error messages to: /tmp/cb3b0696-3f30-4db4-a6a7-bb716d2a8a89/pig_1490803941959.log
2017-03-29 16:12:22,379 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - mapred.job.tracker is deprecated. Instead, use mapreduce.jobtracker.address
2017-03-29 16:12:22,379 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - fs.default.name is deprecated. Instead, use fs.defaultFS
2017-03-29 16:12:22,379 [main] INFO  org.apache.pig.backend.hadoop.executionengine.HExecutionEngine - Connecting to hadoop file system at: hdfs://aspen-dp-central-m
2017-03-29 16:12:22,404 [main] INFO  com.google.cloud.hadoop.fs.gcs.GoogleHadoopFileSystemBase - GHFS version: 1.6.0-hadoop2
2017-03-29 16:12:22,890 [main] INFO  org.apache.pig.PigServer - Pig Script ID for the session: PIG-default-e53a2851-efe5-4e74-bf33-89dfe0733386
2017-03-29 16:12:22,890 [main] WARN  org.apache.pig.PigServer - ATS is disabled since yarn.timeline-service.enabled set to false
2017-03-29 16:12:23,247 [main] ERROR org.apache.pig.PigServer - exception during parsing: Error during parsing. Could not resolve com.turner.pig.load.HBaseMultiScanLoader using imports: [, java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]
Failed to parse: Pig script failed to parse:
<line 8, column 13> pig script failed to validate: org.apache.pig.backend.executionengine.ExecException: ERROR 1070: Could not resolve com.turner.pig.load.HBaseMultiScanLoader using imports: [, java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]
    at org.apache.pig.parser.QueryParserDriver.parse(QueryParserDriver.java:199)
    at org.apache.pig.PigServer$Graph.parseQuery(PigServer.java:1819)
    at org.apache.pig.PigServer$Graph.access$000(PigServer.java:1527)
    at org.apache.pig.PigServer.parseAndBuild(PigServer.java:460)
    at org.apache.pig.PigServer.executeBatch(PigServer.java:485)
    at org.apache.pig.PigServer.executeBatch(PigServer.java:471)
    at org.apache.pig.tools.grunt.GruntParser.executeBatch(GruntParser.java:172)
    at org.apache.pig.tools.grunt.GruntParser.processDump(GruntParser.java:742)
    at org.apache.pig.tools.pigscript.parser.PigScriptParser.parse(PigScriptParser.java:376)
    at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:231)
    at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:206)
    at org.apache.pig.tools.grunt.Grunt.exec(Grunt.java:81)
    at org.apache.pig.Main.run(Main.java:532)
    at org.apache.pig.Main.main(Main.java:176)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
Caused by:
<line 8, column 13> pig script failed to validate: org.apache.pig.backend.executionengine.ExecException: ERROR 1070: Could not resolve com.turner.pig.load.HBaseMultiScanLoader using imports: [, java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]
    at org.apache.pig.parser.LogicalPlanBuilder.validateFuncSpec(LogicalPlanBuilder.java:1339)
    at org.apache.pig.parser.LogicalPlanBuilder.buildFuncSpec(LogicalPlanBuilder.java:1324)
    at org.apache.pig.parser.LogicalPlanGenerator.func_clause(LogicalPlanGenerator.java:5184)
    at org.apache.pig.parser.LogicalPlanGenerator.load_clause(LogicalPlanGenerator.java:3515)
    at org.apache.pig.parser.LogicalPlanGenerator.op_clause(LogicalPlanGenerator.java:1625)
    at org.apache.pig.parser.LogicalPlanGenerator.general_statement(LogicalPlanGenerator.java:1102)
    at org.apache.pig.parser.LogicalPlanGenerator.statement(LogicalPlanGenerator.java:560)
    at org.apache.pig.parser.LogicalPlanGenerator.query(LogicalPlanGenerator.java:421)
    at org.apache.pig.parser.QueryParserDriver.parse(QueryParserDriver.java:191)
    ... 19 more
Caused by: org.apache.pig.backend.executionengine.ExecException: ERROR 1070: Could not resolve com.turner.pig.load.HBaseMultiScanLoader using imports: [, java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]
    at org.apache.pig.impl.PigContext.resolveClassName(PigContext.java:671)
    at org.apache.pig.parser.LogicalPlanBuilder.validateFuncSpec(LogicalPlanBuilder.java:1336)
    ... 27 more
2017-03-29 16:12:23,251 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1070: Could not resolve com.turner.pig.load.HBaseMultiScanLoader using imports: [, java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]
Details at logfile: /tmp/cb3b0696-3f30-4db4-a6a7-bb716d2a8a89/pig_1490803941959.log
2017-03-29 16:12:23,269 [main] INFO  org.apache.pig.Main - Pig script completed in 1 second and 477 milliseconds (1477 ms)
Job output is complete
</code>```

答:
Registering the custom jar inside the Pig script solves the problem.
So, basically:

Added my jar file to Google Storage

Registered the jar inside the script

Submitted Pig job either via UI or command line below:

gcloud dataproc jobs submit pig --cluster eduboom-central --file custom.pig
 --jars=gs://eduboom-dataproc/custom/eduboom.jar

custom.pig:

```<code>register eduboom.jar;
raw = LOAD 'hbase://eduboom_table'
   USING com.eduboom.pig.load.HBaseMultiScanLoader('2017-03-30T14:00Z_00', '2017-03-30T14:01Z_25', 'cf:*')
   AS (key:chararray, data);
DUMP raw;
</code>```

Body:
I'm trying to submit a Pig job via Google Cloud Dataproc and include a custom jar that implements a custom load function I use in the Pig script, but I can't find out how to do that.

Adding my custom jar through the UI appears DOES NOT add it to the Pig classpath.

Here's the output of the Pig job, showing it fails to find my class:

17/03/29 16:12:21 INFO pig.ExecTypeProvider: Trying ExecType : LOCAL
17/03/29 16:12:21 INFO pig.ExecTypeProvider: Trying ExecType : MAPREDUCE
17/03/29 16:12:21 INFO pig.ExecTypeProvider: Picked MAPREDUCE as the ExecType
2017-03-29 16:12:21,961 [main] INFO  org.apache.pig.Main - Apache Pig version 0.16.0 (r: unknown) compiled Nov 27 2016, 23:14:51
2017-03-29 16:12:21,961 [main] INFO  org.apache.pig.Main - Logging error messages to: /tmp/cb3b0696-3f30-4db4-a6a7-bb716d2a8a89/pig_1490803941959.log
2017-03-29 16:12:22,379 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - mapred.job.tracker is deprecated. Instead, use mapreduce.jobtracker.address
2017-03-29 16:12:22,379 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - fs.default.name is deprecated. Instead, use fs.defaultFS
2017-03-29 16:12:22,379 [main] INFO  org.apache.pig.backend.hadoop.executionengine.HExecutionEngine - Connecting to hadoop file system at: hdfs://aspen-dp-central-m
2017-03-29 16:12:22,404 [main] INFO  com.google.cloud.hadoop.fs.gcs.GoogleHadoopFileSystemBase - GHFS version: 1.6.0-hadoop2
2017-03-29 16:12:22,890 [main] INFO  org.apache.pig.PigServer - Pig Script ID for the session: PIG-default-e53a2851-efe5-4e74-bf33-89dfe0733386
2017-03-29 16:12:22,890 [main] WARN  org.apache.pig.PigServer - ATS is disabled since yarn.timeline-service.enabled set to false
2017-03-29 16:12:23,247 [main] ERROR org.apache.pig.PigServer - exception during parsing: Error during parsing. Could not resolve com.turner.pig.load.HBaseMultiScanLoader using imports: [, java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]
Failed to parse: Pig script failed to parse:
<line 8, column 13> pig script failed to validate: org.apache.pig.backend.executionengine.ExecException: ERROR 1070: Could not resolve com.turner.pig.load.HBaseMultiScanLoader using imports: [, java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]
    at org.apache.pig.parser.QueryParserDriver.parse(QueryParserDriver.java:199)
    at org.apache.pig.PigServer$Graph.parseQuery(PigServer.java:1819)
    at org.apache.pig.PigServer$Graph.access$000(PigServer.java:1527)
    at org.apache.pig.PigServer.parseAndBuild(PigServer.java:460)
    at org.apache.pig.PigServer.executeBatch(PigServer.java:485)
    at org.apache.pig.PigServer.executeBatch(PigServer.java:471)
    at org.apache.pig.tools.grunt.GruntParser.executeBatch(GruntParser.java:172)
    at org.apache.pig.tools.grunt.GruntParser.processDump(GruntParser.java:742)
    at org.apache.pig.tools.pigscript.parser.PigScriptParser.parse(PigScriptParser.java:376)
    at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:231)
    at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:206)
    at org.apache.pig.tools.grunt.Grunt.exec(Grunt.java:81)
    at org.apache.pig.Main.run(Main.java:532)
    at org.apache.pig.Main.main(Main.java:176)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
Caused by:
<line 8, column 13> pig script failed to validate: org.apache.pig.backend.executionengine.ExecException: ERROR 1070: Could not resolve com.turner.pig.load.HBaseMultiScanLoader using imports: [, java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]
    at org.apache.pig.parser.LogicalPlanBuilder.validateFuncSpec(LogicalPlanBuilder.java:1339)
    at org.apache.pig.parser.LogicalPlanBuilder.buildFuncSpec(LogicalPlanBuilder.java:1324)
    at org.apache.pig.parser.LogicalPlanGenerator.func_clause(LogicalPlanGenerator.java:5184)
    at org.apache.pig.parser.LogicalPlanGenerator.load_clause(LogicalPlanGenerator.java:3515)
    at org.apache.pig.parser.LogicalPlanGenerator.op_clause(LogicalPlanGenerator.java:1625)
    at org.apache.pig.parser.LogicalPlanGenerator.general_statement(LogicalPlanGenerator.java:1102)
    at org.apache.pig.parser.LogicalPlanGenerator.statement(LogicalPlanGenerator.java:560)
    at org.apache.pig.parser.LogicalPlanGenerator.query(LogicalPlanGenerator.java:421)
    at org.apache.pig.parser.QueryParserDriver.parse(QueryParserDriver.java:191)
    ... 19 more
Caused by: org.apache.pig.backend.executionengine.ExecException: ERROR 1070: Could not resolve com.turner.pig.load.HBaseMultiScanLoader using imports: [, java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]
    at org.apache.pig.impl.PigContext.resolveClassName(PigContext.java:671)
    at org.apache.pig.parser.LogicalPlanBuilder.validateFuncSpec(LogicalPlanBuilder.java:1336)
    ... 27 more
2017-03-29 16:12:23,251 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1070: Could not resolve com.turner.pig.load.HBaseMultiScanLoader using imports: [, java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]
Details at logfile: /tmp/cb3b0696-3f30-4db4-a6a7-bb716d2a8a89/pig_1490803941959.log
2017-03-29 16:12:23,269 [main] INFO  org.apache.pig.Main - Pig script completed in 1 second and 477 milliseconds (1477 ms)
Job output is complete

Body:
Registering the custom jar inside the Pig script solves the problem.
So, basically:

Added my jar file to Google Storage

Registered the jar inside the script

Submitted Pig job either via UI or command line below:

gcloud dataproc jobs submit pig --cluster eduboom-central --file custom.pig
 --jars=gs://eduboom-dataproc/custom/eduboom.jar

custom.pig:

register eduboom.jar;
raw = LOAD 'hbase://eduboom_table'
   USING com.eduboom.pig.load.HBaseMultiScanLoader('2017-03-30T14:00Z_00', '2017-03-30T14:01Z_25', 'cf:*')
   AS (key:chararray, data);
DUMP raw;


来源: stackexchange

问:
Is there a focus changed event in urwid?
Is it possible to track the change of the highlighted item in an urwid.ListBox object? Or even via a ListWalker object?

I would like to call a callback when the user moves from one item to another using the arrow keys [], [], not when the user hits [Enter] on one item.

答:
After some research and experimentation, it's possible to do this by registering the modified signal with the ListWalker object.

```<code>import urwid

def callback():
    index = str(listBox.get_focus()[1])
    debug.set_text("Index of selected item: " + index)

debug = urwid.Text("Debug")

captions = "A B C D E F".split()
items = [urwid.Button(caption) for caption in captions]
walker = urwid.SimpleListWalker(items)
listBox = urwid.ListBox(walker)

urwid.connect_signal(walker, "modified", callback)

frame = urwid.Frame(body=listBox, header=debug)
urwid.MainLoop(frame).run()
</code>```

Reference: Urwid > Signal functions > connect

ContentLicense: CC BY-SA 3.0

Body:
After some research and experimentation, it's possible to do this by registering the modified signal with the ListWalker object.

import urwid

def callback():
    index = str(listBox.get_focus()[1])
    debug.set_text("Index of selected item: " + index)

debug = urwid.Text("Debug")

captions = "A B C D E F".split()
items = [urwid.Button(caption) for caption in captions]
walker = urwid.SimpleListWalker(items)
listBox = urwid.ListBox(walker)

urwid.connect_signal(walker, "modified", callback)

frame = urwid.Frame(body=listBox, header=debug)
urwid.MainLoop(frame).run()

Reference: Urwid > Signal functions > connect


问:
Block-scoped declarations not yet supported outside strict mode
I'm running Laravel 5.4 on my Homestead vagrant box. I've installed all the npm dependencies with npm install command. That didn't produce any errors.

In my webpack.min.js file I have:

```<code>const { mix } = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js([
        'resources/assets/plugins/jquery-1.11.3.min.js',
        'resources/assets/plugins/bootstrap/js/bootstrap.min.js',
        'resources/assets/js/main.js'
    ], 'public/js'
);

mix.combine([
       'resources/assets/plugins/bootstrap/css/bootstrap.min.css',
       'resources/assets/plugins/font-awesome/css/font-awesome.css',
       'resources/assets/css/styles.css'
   ], 'public/css/all.css');
</code>```

When I want to run npm run production I'm getting the following errors:

```<code>> @ production /home/vagrant/projects/nielsvroman
> node node_modules/cross-env/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

/home/vagrant/projects/nielsvroman/node_modules/laravel-mix/setup/webpack.config.js:120
        let extractPlugin = new plugins.ExtractTextPlugin(
        ^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:404:25)
    at Object.Module._extensions..js (module.js:432:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at requireConfig (/home/vagrant/projects/nielsvroman/node_modules/webpack/bin/convert-argv.js:96:18)
    at /home/vagrant/projects/nielsvroman/node_modules/webpack/bin/convert-argv.js:109:17
    at Array.forEach (native)

npm ERR! Linux 3.19.0-25-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "run" "production"
npm ERR! node v5.0.0
npm ERR! npm  v3.3.6
npm ERR! code ELIFECYCLE
npm ERR! @ production: `node node_modules/cross-env/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ production script 'node node_modules/cross-env/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js'.
npm ERR! This is most likely a problem with the  package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node node_modules/cross-env/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/vagrant/projects/nielsvroman/npm-debug.log
</code>```

What could be the problem with this?

答:
I had the same problem coused by the old version of nodejs package on Ubuntu. I've just updated to 7.5 and it's working.

curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
sudo apt-get install -y nodejs
```

ContentLicense: CC BY-SA 4.0

Body:
I'm running Laravel 5.4 on my Homestead vagrant box. I've installed all the npm dependencies with npm install command. That didn't produce any errors.

In my webpack.min.js file I have:

const { mix } = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js([
        'resources/assets/plugins/jquery-1.11.3.min.js',
        'resources/assets/plugins/bootstrap/js/bootstrap.min.js',
        'resources/assets/js/main.js'
    ], 'public/js'
);

mix.combine([
       'resources/assets/plugins/bootstrap/css/bootstrap.min.css',
       'resources/assets/plugins/font-awesome/css/font-awesome.css',
       'resources/assets/css/styles.css'
   ], 'public/css/all.css');

When I want to run npm run production I'm getting the following errors:

> @ production /home/vagrant/projects/nielsvroman
> node node_modules/cross-env/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

/home/vagrant/projects/nielsvroman/node_modules/laravel-mix/setup/webpack.config.js:120
        let extractPlugin = new plugins.ExtractTextPlugin(
        ^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:404:25)
    at Object.Module._extensions..js (module.js:432:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at requireConfig (/home/vagrant/projects/nielsvroman/node_modules/webpack/bin/convert-argv.js:96:18)
    at /home/vagrant/projects/nielsvroman/node_modules/webpack/bin/convert-argv.js:109:17
    at Array.forEach (native)

npm ERR! Linux 3.19.0-25-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "run" "production"
npm ERR! node v5.0.0
npm ERR! npm  v3.3.6
npm ERR! code ELIFECYCLE
npm ERR! @ production: `node node_modules/cross-env/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ production script 'node node_modules/cross-env/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js'.
npm ERR! This is most likely a problem with the  package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node node_modules/cross-env/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/vagrant/projects/nielsvroman/npm-debug.log

What could be the problem with this?


问:
Replace Multiple If\Else with Design Pattern
Based on various threads on SO (ex. Replacing if else statement with pattern ) I understand that I can replace multiple if\else statements with the Command pattern.

My situation is a bit different.

I have a series of Commands and I need to execute each Command only if the previous command was unsuccessful.

For example, suppose I need to retrieve text from a hypothetical web page - I could scrape the text directly from the page using screen scraping or I could fetch the text from the API. I would only want to fetch the text from API if screen scraping was not successful. In other words I would only execute the "fetch" command if the "scrape" command didn't work.

In this case, I  would test if the scraped String is empty or equal to null and then execute the second Command. If the second command is also unsuccessful I would execute the third Command and so on.

The important point is that we only execute subsequent commands if a certain condition is true/false. The condition is always the same for each Command but the number of commands might grow in the future.

I cannot implement this via the typically suggested route (using a Map and Command interface) bec this would not execute the next Command if the first one failed (it would also be unable to check if a Command was successful or not)

What design pattern could be used to solve this problem?

答:
People have suggested using the chain of responsibility pattern however as I was thinking of the problem it occurred to me I could use a variation of the Command pattern to solve this problem. It works like this.

Replace each if statement with a corresponding class which implements the Command interface. In our example, I would implement the classes ScreenScrapeTextCommand and FetchTextFromAPICommand. Since each class will implement the Command interface we will add the method execute() to each class (this method will actually execute the functionality we need such as screen scraping or fetching from API).

We'd then create a new class which contains all related commands. Let's call this class GetTextCommandCenter. The class would contain a list of Commands in the form of public List<Command> commandList; We'd then hard code commands by adding the first two classes to the list in the following manner:

```<code>commandList.add(new ScreenScrapeTextCommand();
commandList.add(new FetchTextFromAPICommand();
</code>```

We could then replace the if\else chain with the following:

```<code>public String replaceIfElseWithCommand()..

String text = null;
int commandIndex = 0;

while (text == null && text == someCondition)
{

text = new GetTextCommandCenter().commandList(commandIndex).execute();
commandIndex++;
}

return text;

}
</code>```

As soon as a command is successful the the condition in the while loop will fail and method will return accordingly.

This way, we can easily add more Commands by adding more classes to CommandCenter class or change the precedence of individual commands quickly.

I think this is a simple and straightforward solution to my problem (but please place a comment if you think the chain of responsibility pattern is more suitable and why you think so)

Body:
People have suggested using the chain of responsibility pattern however as I was thinking of the problem it occurred to me I could use a variation of the Command pattern to solve this problem. It works like this.

Replace each if statement with a corresponding class which implements the Command interface. In our example, I would implement the classes ScreenScrapeTextCommand and FetchTextFromAPICommand. Since each class will implement the Command interface we will add the method execute() to each class (this method will actually execute the functionality we need such as screen scraping or fetching from API).

We'd then create a new class which contains all related commands. Let's call this class GetTextCommandCenter. The class would contain a list of Commands in the form of public List<Command> commandList; We'd then hard code commands by adding the first two classes to the list in the following manner:

commandList.add(new ScreenScrapeTextCommand();
commandList.add(new FetchTextFromAPICommand();

We could then replace the if\else chain with the following:

public String replaceIfElseWithCommand()..

String text = null;
int commandIndex = 0;

while (text == null && text == someCondition)
{

text = new GetTextCommandCenter().commandList(commandIndex).execute();
commandIndex++;
}

return text;

}

As soon as a command is successful the the condition in the while loop will fail and method will return accordingly.

This way, we can easily add more Commands by adding more classes to CommandCenter class or change the precedence of individual commands quickly.

I think this is a simple and straightforward solution to my problem (but please place a comment if you think the chain of responsibility pattern is more suitable and why you think so)


问:
Look for a property in List of object using Hamcrest matcher
I have a Java POJO.

```<code>public class Emp {
    private String name;
    private int id;
}
</code>```

I have a list of employees (target):

```<code> List<Emp> target = new ArrayList<Emap>();
 // Add emp object in list
 assertThat(target, containsInAnyOrder(????));
</code>```

In containsInAnyOrder, I have to use something like i.e. hasProperty("name" , is(equalTo("John")). I have to check for a specific property in the list for specific value so what should be the syntax. I did not find any example of "containsInAnyOrder" with List of objects.

答:
I understand that you want a "generic" thing like: iterate a whole list; then retrieve a field of an object via name; to then check if any of the elements has a matching thing.

I think there is no such thing in Hamcrest: as that is ay too complicated for a pre-defined matcher.

In that sense, the only "answer" to exactly this requirement would be to create your own customer matcher that uses reflection to actually do that.

More details: you can start with an older answer of mine that contains a ready to use matcher that works for lists.

Actually, the only thing left to do now: change my list matcher to perform a different kind of check. And there you could make use of the Apache Commons EqualsBuilder listed in the other answer.

There should be no big hurdle in implementing that; its just "work".

But: I am not sure if that is really the correct approach. As said; the question you are trying to solve there sounds very specific too me; and you know: any unit test that uses reflection lacks the same problem that any "reflection based" code has - the compiler will not tell you, when somebody changes your production code; for example by changing the name of the field name.

Thus: instead of using reflection, I would rather compromise on the "production code" side of things; for example by adding a simple getter:

```<code>public class Emp {
... fields
  String getName() { return name; }
</code>```

And instead of using reflection to compare generic properties, you write a matcher that knows to use that getter to fetch names and compare them.h

Body:
I have a Java POJO.

public class Emp {
    private String name;
    private int id;
}

I have a list of employees (target):

 List<Emp> target = new ArrayList<Emap>();
 // Add emp object in list
 assertThat(target, containsInAnyOrder(????));

In containsInAnyOrder, I have to use something like i.e. hasProperty("name" , is(equalTo("John")). I have to check for a specific property in the list for specific value so what should be the syntax. I did not find any example of "containsInAnyOrder" with List of objects.

Body:
I understand that you want a "generic" thing like: iterate a whole list; then retrieve a field of an object via name; to then check if any of the elements has a matching thing.

I think there is no such thing in Hamcrest: as that is ay too complicated for a pre-defined matcher.

In that sense, the only "answer" to exactly this requirement would be to create your own customer matcher that uses reflection to actually do that.

More details: you can start with an older answer of mine that contains a ready to use matcher that works for lists.

Actually, the only thing left to do now: change my list matcher to perform a different kind of check. And there you could make use of the Apache Commons EqualsBuilder listed in the other answer.

There should be no big hurdle in implementing that; its just "work".

But: I am not sure if that is really the correct approach. As said; the question you are trying to solve there sounds very specific too me; and you know: any unit test that uses reflection lacks the same problem that any "reflection based" code has - the compiler will not tell you, when somebody changes your production code; for example by changing the name of the field name.

Thus: instead of using reflection, I would rather compromise on the "production code" side of things; for example by adding a simple getter:

public class Emp {
... fields
  String getName() { return name; }

And instead of using reflection to compare generic properties, you write a matcher that knows to use that getter to fetch names and compare them.h


问:
Pycharm Error - No module named MySQLdb
I have installed MySqldb as shown below:-

```<code>jab-MacBook-Pro-4:silkroute deb$ pip install MySQL-python
Collecting MySQL-python
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5
</code>```

But still I am getting the error:-

```<code>python --version
Python 2.7.11
</code>```

I am using version 2.7.10 in PyCharm

I have also installed MySQLDB as shown below:-

```<code>jab-MacBook-Pro-4:silkroute deb$ pip2.7 install MySQL-python
Requirement already satisfied: MySQL-python in /usr/local/lib/python2.7/site-packages
</code>```

Can someone let me know how can I get rid of this error?

答:
Open PyCharm, File>>Default Settings>>Project Interpreter>>Select the Interpreter you want to install the packages to, press the red '+' sign to the right, search the package and install.

This should most probably correct your error. You are better off creating a virtualenv though, will be really helpful. Use this to get started

Title: Pycharm Error - No module named MySQLdb

Body:
I have installed MySqldb as shown below:-

jab-MacBook-Pro-4:silkroute deb$ pip install MySQL-python
Collecting MySQL-python
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5

But still I am getting the error:-

python --version
Python 2.7.11

I am using version 2.7.10 in PyCharm

I have also installed MySQLDB as shown below:-

jab-MacBook-Pro-4:silkroute deb$ pip2.7 install MySQL-python
Requirement already satisfied: MySQL-python in /usr/local/lib/python2.7/site-packages

Can someone let me know how can I get rid of this error?


问:
Vb.net to golang AES
I am trying to convert a function encryption routine from VB to Golang.

My Go route returns the hex length of my what ever value I pass into it but the VB routine always returns a length of 32.

Could some please advice me on what I am doing wrong?

VB:

```<code>Function encryptString(ByVal source As String, ByVal key As Byte(), ByVal IV As Byte()) As Byte()
    Dim array As Byte() = Nothing
    Using aesManaged As System.Security.Cryptography.AesManaged = New System.Security.Cryptography.AesManaged()
        aesManaged.Key = key
        aesManaged.IV = IV
        Dim cryptoTransform As ICryptoTransform = aesManaged.CreateEncryptor(aesManaged.Key, aesManaged.IV)
        Using memoryStream As System.IO.MemoryStream = New System.IO.MemoryStream()
            Using cryptoStream As System.Security.Cryptography.CryptoStream = New System.Security.Cryptography.CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write)
                Using streamWriter As System.IO.StreamWriter = New System.IO.StreamWriter(cryptoStream)
                    streamWriter.Write(source)
                End Using
                array = memoryStream.ToArray()
            End Using
        End Using
    End Using
</code>```

Go

```<code>func Encrypt(key string, plaintext string) string {
    block, err := aes.NewCipher([]byte(key))

    if err != nil {
        panic(err)
    }
    str := []byte(plaintext)

    iv := []byte{178, 212, 4, 97, 181, 77, 129, 200, 198, 223, 84, 96, 81, 55, 3, 40}
    encrypter := cipher.NewCFBEncrypter(block, iv)
    encrypted := make([]byte, len(str))
    encrypter.XORKeyStream(encrypted, str)
    fmt.Printf("%s encrypted to %x\n", str, encrypted)
}
</code>```

Also both times the IV and the key have been the same but I get different results...

答:
The default mode of operation in .Net is probably CBC (you should set it explicitly), but your Go code uses CFB mode. They are not compatible.

CBC mode requires a padding scheme, but CFB not. .Net uses PKCS#7 padding by default, but Go doesn't provide you with any help to add or remove padding. You would need to implement it yourself. This question contains an implementation of PKCS#7 padding.

Title: Vb.net to golang AES

Body:
I am trying to convert a function encryption routine from VB to Golang.

My Go route returns the hex length of my what ever value I pass into it but the VB routine always returns a length of 32.

Could some please advice me on what I am doing wrong?

VB:

Function encryptString(ByVal source As String, ByVal key As Byte(), ByVal IV As Byte()) As Byte()
    Dim array As Byte() = Nothing
    Using aesManaged As System.Security.Cryptography.AesManaged = New System.Security.Cryptography.AesManaged()
        aesManaged.Key = key
        aesManaged.IV = IV
        Dim cryptoTransform As ICryptoTransform = aesManaged.CreateEncryptor(aesManaged.Key, aesManaged.IV)
        Using memoryStream As System.IO.MemoryStream = New System.IO.MemoryStream()
            Using cryptoStream As System.Security.Cryptography.CryptoStream = New System.Security.Cryptography.CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write)
                Using streamWriter As System.IO.StreamWriter = New System.IO.StreamWriter(cryptoStream)
                    streamWriter.Write(source)
                End Using
                array = memoryStream.ToArray()
            End Using
        End Using
    End Using

Go

func Encrypt(key string, plaintext string) string {
    block, err := aes.NewCipher([]byte(key))

    if err != nil {
        panic(err)
    }
    str := []byte(plaintext)

    iv := []byte{178, 212, 4, 97, 181, 77, 129, 200, 198, 223, 84, 96, 81, 55, 3, 40}
    encrypter := cipher.NewCFBEncrypter(block, iv)
    encrypted := make([]byte, len(str))
    encrypter.XORKeyStream(encrypted, str)
    fmt.Printf("%s encrypted to %x\n", str, encrypted)
}

Also both times the IV and the key have been the same but I get different results...


问:
How to display a
 on hover on another

i Have used bootstrap and css , here is my code

```<code><div class = "row" id="parent"=>

  <div class="col-md-8" id="ClildDiv1">

  //Some Content

</div>

<div class="col-md-4" id="ChildDiv2" style="display:none">

  //Some Content

<div>

</div>
</code>```

Now i want on hover on

All its Child  should be visible in this case

Any Help Would Be Appreciated And i want to achieve that only by CSS styling

答:
You want one of the sibling selectors.  General sibling ~ or next sibling +

```<code>.ClildDiv1:hover ~ .ChildDiv2 {
    display: block;
}
</code>```

See fiddle here

Or, the parent hover for any child div would be

```<code>.Parent:hover > div {
  display: block;
}
</code>```

Title: How to display a <div> on hover on another <div>

Body:
i Have used bootstrap and css , here is my code

  //Some Content

  //Some Content

Now i want on hover on

All its Child  should be visible in this case

Any Help Would Be Appreciated And i want to achieve that only by CSS styling

Body:
You want one of the sibling selectors.  General sibling ~ or next sibling +

.ClildDiv1:hover ~ .ChildDiv2 {
    display: block;
}

See fiddle here

Or, the parent hover for any child div would be

.Parent:hover > div {
  display: block;
}


问:
SQL Server constraint. Maximum number of rows filtered by field
First of all sorry for my English.

My problem: I have an application using Asp.Net + EF code-first. I have one table in SQL Server:

```<code>Id   TypeId   Name
--------------------
1    1        Suite
2    1        Desk
</code>```

In my app there two inserts that are running in 2 threads.

I need to create a constraint on my table - there can be only 3 rows per table for TypeId = 1.

So if two threads make a query, only one can be successful, because 1 rows left for TypeId = 1.

How can I check this?How can I run insert not concurrently or maybe you have other great solutions?

Constraint of rows count for each TypeId can be different. There are another table called TypeConstraints where stored two columns.

```<code>TypeId  RowsCount
1       3
2       5
3       4
4       11
5       8
</code>```

and so on..

HAVE FOUND SOLUTION:

```<code>ALTER function dbo.UdfCheckCount (
        @TypeId int
    ) returns int as
    begin;
    declare @max int;
    select @max = MaxCount from TypeConstraints where TypeId = @TypeId;
      declare @count int =
      (
        select count(*) from Data where TypeId = @TypeId
      )

      return @max - @count;
    end;
    go

    alter table Data  WITH NOCHECK add constraint test check (dbo.UdfCheckCount(TypeId) >= 0)
</code>```

答:
You could write a trigger on your database that checks this and throws an error.

```<code>CREATE TRIGGER dbo.Table
AFTER INSERT
AS
BEGIN
    -- Do your check here to see if the type count has been exceeded
    IF (SELECT COUNT(*) FROM dbo.Table WHERE TypeID = <etc ...> )
    BEGIN
        RAISERROR ('Maximum number of rows for this type has been exceeded', 16, 1);
        ROLLBACK TRANSACTION;
    END
END
</code>```

Then, just handle the error in your application and proceed from there.

However, I'm not sure how triggers work from an EF Code-First perspective.  I can't imagine it would cause any issues though.

Body:
First of all sorry for my English.

My problem: I have an application using Asp.Net + EF code-first. I have one table in SQL Server:

Id   TypeId   Name
--------------------
1    1        Suite
2    1        Desk

In my app there two inserts that are running in 2 threads.

I need to create a constraint on my table - there can be only 3 rows per table for TypeId = 1.

So if two threads make a query, only one can be successful, because 1 rows left for TypeId = 1.

How can I check this?How can I run insert not concurrently or maybe you have other great solutions?

Constraint of rows count for each TypeId can be different. There are another table called TypeConstraints where stored two columns.

TypeId  RowsCount
1       3
2       5
3       4
4       11
5       8

and so on..

HAVE FOUND SOLUTION:

ALTER function dbo.UdfCheckCount (
        @TypeId int
    ) returns int as
    begin;
    declare @max int;
    select @max = MaxCount from TypeConstraints where TypeId = @TypeId;
      declare @count int =
      (
        select count(*) from Data where TypeId = @TypeId
      )

      return @max - @count;
    end;
    go

    alter table Data  WITH NOCHECK add constraint test check (dbo.UdfCheckCount(TypeId) >= 0)

Body:
You could write a trigger on your database that checks this and throws an error.

CREATE TRIGGER dbo.Table
AFTER INSERT
AS
BEGIN
    -- Do your check here to see if the type count has been exceeded
    IF (SELECT COUNT(*) FROM dbo.Table WHERE TypeID = <etc ...> )
    BEGIN
        RAISERROR ('Maximum number of rows for this type has been exceeded', 16, 1);
        ROLLBACK TRANSACTION;
    END
END

Then, just handle the error in your application and proceed from there.

However, I'm not sure how triggers work from an EF Code-First perspective.  I can't imagine it would cause any issues though.


问:
A-Frame animations via JavaScript
I started with A-Frame VR framework. I have a simple box that I want to animate.

This box will be floating, when looking to the box, it will scale up, on click it will rotate:

```<code><a-box id="boxID" position="0 2 -5" rotation="0 45 45" scale="2 2 2" src="#boxTexture">
            <a-animation attribute="position" to="0 2.2 -5" direction="alternate" dur="2000" repeat="indefinite"></a-animation>

<!-- These animations will start when the box is looked at. -->
<a-animation attribute="scale" begin="mouseenter" dur="300" to="2.3 2.3 2.3"></a-animation>
<a-animation attribute="scale" begin="mouseleave" dur="300" to="2 2 2"></a-animation>
<a-animation attribute="rotation" begin="click" dur="2000" to="360 405 45"></a-animation>
</code>```

I would like to create above with Javascript. I started with the following:

```<code>AFRAME.registerComponent('scale-on-interact', {
    schema: {
        to: {default: '2.5 2.5 2.5'}
    },

    init: function () {
        var data = this.data;

    },

    update: function() {
        var data = this.data;
        console.log(data.color);

        // MOUSE ENTER EVENT
        this.el.addEventListener('mouseenter', function() {
            console.log("enter");
            this.setAttribute('to', data.to);
        });

        // CLICK EVENT
        this.el.addEventListener('click', function() {
            console.log("click");
        });

        // MOUSE LEAVE EVENT
        this.el.addEventListener('mouseleave', function() {
            console.log("leave");
        });
    }
});
</code>```

I receive the logs, but for example on mouse enter, the box doesn't scale up. Also I doesn't know and can't find how to create multiple schema's so I can create one 'to' property for on mouse enter and one for on click.

答:
Firstly, the  and Animation Component both take begin and startEvents properties that specify an event on the entity that will automatically trigger the animation.  or .

Secondly, there's an event-set component that might do what you want, set properties in response to events. .

Third, in your component, if you want to set the scale, you should setAttribute('scale', {x: 2, y: 2, z: 2}), not to. Also makes sure that component is attached to your entity .

Lastly, if you want a component to be able to have multiple instances, set multiple: true in your component. Then you can have multiple components set with __ delimiter:

Title: A-Frame animations via JavaScript

Body:
I started with A-Frame VR framework. I have a simple box that I want to animate.

This box will be floating, when looking to the box, it will scale up, on click it will rotate:

I would like to create above with Javascript. I started with the following:

AFRAME.registerComponent('scale-on-interact', {
    schema: {
        to: {default: '2.5 2.5 2.5'}
    },

    init: function () {
        var data = this.data;

    },

    update: function() {
        var data = this.data;
        console.log(data.color);

        // MOUSE ENTER EVENT
        this.el.addEventListener('mouseenter', function() {
            console.log("enter");
            this.setAttribute('to', data.to);
        });

        // CLICK EVENT
        this.el.addEventListener('click', function() {
            console.log("click");
        });

        // MOUSE LEAVE EVENT
        this.el.addEventListener('mouseleave', function() {
            console.log("leave");
        });
    }
});

I receive the logs, but for example on mouse enter, the box doesn't scale up. Also I doesn't know and can't find how to create multiple schema's so I can create one 'to' property for on mouse enter and one for on click.

Body:
Firstly, the <a-animation> and Animation Component both take begin and startEvents properties that specify an event on the entity that will automatically trigger the animation. <a-animation begin="mouseenter"> or <a-entity animation__1="property: scale; to: 2 2 2; startEvents: click">.

Secondly, there's an event-set component that might do what you want, set properties in response to events. <a-entity event-set__1="_event: mouseenter; scale: 2 2 2">.

Third, in your component, if you want to set the scale, you should setAttribute('scale', {x: 2, y: 2, z: 2}), not to. Also makes sure that component is attached to your entity <a-box id="boxID" scale-on-interact>.

Lastly, if you want a component to be able to have multiple instances, set multiple: true in your component. Then you can have multiple components set with __ delimiter: <a-box id="boxID" component__1="foo: 1; bar: 2" component__two="foo: 2; bar: 3">


问:
Read File and store element as array Scala
I am new to Scala and this is the first time I'm using it. I want to read in a textfile with with two columns of numbers and store each column items in a separate list or array that will have to be cast as integer. For example the textfile looks like this:

```<code>1 2
2 3
3 4
4 5
1 6
6 7
7 8
8 9
6 10
</code>```

I want to separate the two columns so that each column is stored in its on list or array.

答:
Lets say you named the file as "columns", this would be a solution:</p>

```<code>    val lines = Source.fromFile("columns").getLines()
    /* gets an Iterator[String] which interfaces a collection of all the lines in the file*/
    val linesAsArraysOfInts = lines.map(line => line.split(" ").map(_.toInt))
    /* Here you transform (map) any line to arrays of Int, so you will get as a result an Interator[Array[Int]] */
    val pair: (List[Int], List[Int]) = linesAsArraysOfInts.foldLeft((List[Int](), List[Int]()))((acc, cur) => (cur(0) :: acc._1, cur(1) :: acc._2))
    /* The foldLeft method on iterators, allows you to propagate an operation from left to right on the Iterator starting from an initial value and changing this value over the propagation process. In this case you start with two empty Lists stored as Tuple an on each step you prepend the first element of the array to the first List, and the second element to the second List. At the end you will have to Lists with the columns in reverse order*/

    val leftList: List[Int] = pair._1.reverse
    val rightList: List[Int] = pair._2.reverse
    //finally you apply reverse to the lists and it's done :)
</code>```

Body:
I am new to Scala and this is the first time I'm using it. I want to read in a textfile with with two columns of numbers and store each column items in a separate list or array that will have to be cast as integer. For example the textfile looks like this:

1 2
2 3
3 4
4 5
1 6
6 7
7 8
8 9
6 10

I want to separate the two columns so that each column is stored in its on list or array.

Body:
Lets say you named the file as "columns", this would be a solution:

    val lines = Source.fromFile("columns").getLines()
    /* gets an Iterator[String] which interfaces a collection of all the lines in the file*/
    val linesAsArraysOfInts = lines.map(line => line.split(" ").map(_.toInt))
    /* Here you transform (map) any line to arrays of Int, so you will get as a result an Interator[Array[Int]] */
    val pair: (List[Int], List[Int]) = linesAsArraysOfInts.foldLeft((List[Int](), List[Int]()))((acc, cur) => (cur(0) :: acc._1, cur(1) :: acc._2))
    /* The foldLeft method on iterators, allows you to propagate an operation from left to right on the Iterator starting from an initial value and changing this value over the propagation process. In this case you start with two empty Lists stored as Tuple an on each step you prepend the first element of the array to the first List, and the second element to the second List. At the end you will have to Lists with the columns in reverse order*/

    val leftList: List[Int] = pair._1.reverse
    val rightList: List[Int] = pair._2.reverse
    //finally you apply reverse to the lists and it's done :)


问:
Calling upon a locally defined variable later on python
I am trying to recall upon these locally defined variables (p1,p2,w1,w2) later on outside. In my program I made it so if the user inputted something other than a number the program would prompt the user that they incorrectly inputted their response. However, this caused my variables to defined locally and I am unaware of how to use those locally defined variables later on. Any help would be much appreciated, thank you.</p>

```<code>fp=input("\nWhat percentage do you want to finish the class with?")

def main():
    p1 = get_number("\nWhat is your 1st marking period percentage? ")
    w1 = get_number("\nWhat is the weighting of the 1st marking period? ")
    p2 = get_number("\nWhat is your 2nd marking period percentage? ")
    w2 = get_number("\nWhat is the weighting of the 2nd marking period? ")

def get_number(prompt):
    while True:
        try:
            text = input(prompt)
        except EOFError:
            raise SystemExit()
        else:
            try:
                number = float(text)
            except ValueError:
                print("Please enter a number.")
            else:
                break
    return number

def calculate_score(percentages, weights):
    if len(percentages) != len(weights):
        raise ValueError("percentages and weights must have same length")
    return sum(p * w for p, w in zip(percentages, weights)) / sum(weights)

if __name__ == "__main__":
    main()

mid=input("\nDid your have a midterm exam? (yes or no)")
if mid=="yes":
    midg=input("\nWhat was your grade on the midterm?")
    midw=input("\nWhat is the weighting of the midterm exam?")
elif mid=="no":
    midw=0
    midg=0
fw=input("\nWhat is the weighting of the final exam? (in decimal)")

fg=(fp-(w1*p1)-(w2*p2)-(midw*midg))/(fw)
print("You will need to get a", fg ,"on your final to finish the class with a", fp)
</code>```

答:
One way to pass variables from scope to scope is to return them from your function:

```<code>def main():
    p1 = get_number("\nWhat is your 1st marking period percentage? ")
    w1 = get_number("\nWhat is the weighting of the 1st marking period? ")
    p2 = get_number("\nWhat is your 2nd marking period percentage? ")
    w2 = get_number("\nWhat is the weighting of the 2nd marking period? ")

    return p1, w1, p2, w2
</code>```

Then, when you call the main function, assign that function's outputs to the appropriate names:

```<code>if __name__ == "__main__":
    p1, w1, p2, w2 = main()
</code>```

Note that you don't have to call them p1, w1, p2, and w2 at this stage—you can assign them to whatever names make sense in the scope you're working in.  That's the power of dividing things into functions—outside the function, you don't have to worry about following the same naming convention that's used inside the function (which you may not even know). You could also assign/refer to the four outputs together as a tuple, i.e. call:

```<code>if __name__ == "__main__":
    numbers = main()
</code>```

and subsequently refer to them as numbers[0], numbers[1], numbers[2] and numbers[3].

Body:
I am trying to recall upon these locally defined variables (p1,p2,w1,w2) later on outside. In my program I made it so if the user inputted something other than a number the program would prompt the user that they incorrectly inputted their response. However, this caused my variables to defined locally and I am unaware of how to use those locally defined variables later on. Any help would be much appreciated, thank you.

fp=input("\nWhat percentage do you want to finish the class with?")

def main():
    p1 = get_number("\nWhat is your 1st marking period percentage? ")
    w1 = get_number("\nWhat is the weighting of the 1st marking period? ")
    p2 = get_number("\nWhat is your 2nd marking period percentage? ")
    w2 = get_number("\nWhat is the weighting of the 2nd marking period? ")

def get_number(prompt):
    while True:
        try:
            text = input(prompt)
        except EOFError:
            raise SystemExit()
        else:
            try:
                number = float(text)
            except ValueError:
                print("Please enter a number.")
            else:
                break
    return number

def calculate_score(percentages, weights):
    if len(percentages) != len(weights):
        raise ValueError("percentages and weights must have same length")
    return sum(p * w for p, w in zip(percentages, weights)) / sum(weights)

if __name__ == "__main__":
    main()

mid=input("\nDid your have a midterm exam? (yes or no)")
if mid=="yes":
    midg=input("\nWhat was your grade on the midterm?")
    midw=input("\nWhat is the weighting of the midterm exam?")
elif mid=="no":
    midw=0
    midg=0
fw=input("\nWhat is the weighting of the final exam? (in decimal)")

fg=(fp-(w1*p1)-(w2*p2)-(midw*midg))/(fw)
print("You will need to get a", fg ,"on your final to finish the class with a", fp)

Body:
One way to pass variables from scope to scope is to return them from your function:

def main():
    p1 = get_number("\nWhat is your 1st marking period percentage? ")
    w1 = get_number("\nWhat is the weighting of the 1st marking period? ")
    p2 = get_number("\nWhat is your 2nd marking period percentage? ")
    w2 = get_number("\nWhat is the weighting of the 2nd marking period? ")

    return p1, w1, p2, w2

Then, when you call the main function, assign that function's outputs to the appropriate names:

if __name__ == "__main__":
    p1, w1, p2, w2 = main()

Note that you don't have to call them p1, w1, p2, and w2 at this stage—you can assign them to whatever names make sense in the scope you're working in.  That's the power of dividing things into functions—outside the function, you don't have to worry about following the same naming convention that's used inside the function (which you may not even know). You could also assign/refer to the four outputs together as a tuple, i.e. call:

if __name__ == "__main__":
    numbers = main()

and subsequently refer to them as numbers[0], numbers[1], numbers[2] and numbers[3].


问:
Low speed network with high risk of disconnection
I have some computers on a network, the network is somehow serial, I mean computers are connected to each other via radio transmitters and in a line, if a radio transmitter goes off or face some problems other computers are not accessible.
the architecture would be something like this:

RT = radio transmitters

Computer#1<-RT#1->Computer#2<-RT#2->Computer#3<-RT#3->....<-RT#(N-1)->Computer#N

Distances between computers are about 20 to 30 kilometers and network speed varies between 0 and 10Kbps. computers are running windows XP and a very high loaded program (2GB of ram, 90% CPU Usage) are always running on them, all computers IP addresses are known and static.

I'm going to write a program which is going to run on every computer and get commands or packages to run or install and update on that computer. because of the low speed network and high risk of disconnection sending data between computers should have resume capability. the question is how should I implement that? using .NET remoting or use simple network sockets and TCP? which one is better? feel free to explain your suggestion or approaches you think suites this solution.

答: Have a read up on UUCP, historically the solution to this problem and configuration.</p>

ContentLicense: CC BY-SA 2.5


问:
$ionicPlatform.ready() not firing
Recently I started working with ionic and I'm stuck in a weird bug that I can't find any solution, I have searching over the web and there isn't many solutions.
The problem is that the app works fine testing on pc and then when using it on an android device (not tested on ios) some code just dont fire.

Here is what I have:
(index.html)

```<code><!-- compiled css output -->
<link href="css/ionic.app.css" rel="stylesheet">

<!-- ionic/angularjs js -->
<script src="lib/ionic-platform-web-client/dist/ionic.io.bundle.js"> </script>
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic-service-core/ionic-core.js"></script>

<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>

<!-- your app's js -->
<script src="js/app.js"></script>
</code>```

(app.js)

```<code>angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])

.run(function ($ionicPlatform, $ionicPopup) {
    $ionicPlatform.ready(function () {

        var push = new Ionic.Push({
     "debug": true
    });

      push.register(function(token) {
      console.log("My Device token:",token.token);
      push.saveToken(token);  // persist the token in the Ionic Platform
      window.localStorage.setItem("idToken", token.token);

    });

        // Check for network connection
        if (window.Connection) {
            if (navigator.connection.type == Connection.NONE) {
                $ionicPopup.confirm({
                        title: 'No Internet Connection',
                        content: 'Sorry, no Internet connectivity detected. Please reconnect and try again.'
                    })
                    .then(function (result) {
                        if (!result) {
                            ionic.Platform.exitApp();
                        }
                    });
            }
        }

        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            cordova.plugins.Keyboard.disableScroll(true);
        }
        if (window.StatusBar) {
            // org.apache.cordova.statusbar required
            StatusBar.styleDefault();
        }
    });
})
</code>```

One of the errors that I get in android when I use the emulator is this:

```<code>Unable to open asset URL: file:///android_asset/www/cordova_plugins.js
</code>```

But in my path:

```<code>C:\myApp\platforms\android\assets\www
</code>```

There is cordova_plugins.js

Is there something that I'm missing out?
Thank you in advance for the help.

答:
If any file name is not correct or any spelling mistake it will not show in browser. bcz browser is not case sensitive.. but device is case sensitive. check your file names and folder names.

If you want to test which error throwing when you install app.. Go to remote debugging.

Its like, you can see errors in browser, when you operate app in device.

Procedure for remote debugging:

Make sure your device is USB debugging,

open browser in your mubile, just minimize

connect mobile to pc using usb,

in command prompt, type "ionic run android"

Now go to PC browser, click on setting button (right corner 3 dots),

go to more tools, then developer tools, in that you can find your device name

once app fire up in your device, click on inspect in browser. then it will show error if it is there.

I hope you understand. If not plz ask.

Title: $ionicPlatform.ready() not firing

Body:
Recently I started working with ionic and I'm stuck in a weird bug that I can't find any solution, I have searching over the web and there isn't many solutions.
The problem is that the app works fine testing on pc and then when using it on an android device (not tested on ios) some code just dont fire.

Here is what I have:
(index.html)

<link href="css/ionic.app.css" rel="stylesheet">

(app.js)

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])

.run(function ($ionicPlatform, $ionicPopup) {
    $ionicPlatform.ready(function () {

        var push = new Ionic.Push({
     "debug": true
    });

      push.register(function(token) {
      console.log("My Device token:",token.token);
      push.saveToken(token);  // persist the token in the Ionic Platform
      window.localStorage.setItem("idToken", token.token);

    });

        // Check for network connection
        if (window.Connection) {
            if (navigator.connection.type == Connection.NONE) {
                $ionicPopup.confirm({
                        title: 'No Internet Connection',
                        content: 'Sorry, no Internet connectivity detected. Please reconnect and try again.'
                    })
                    .then(function (result) {
                        if (!result) {
                            ionic.Platform.exitApp();
                        }
                    });
            }
        }

        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            cordova.plugins.Keyboard.disableScroll(true);
        }
        if (window.StatusBar) {
            // org.apache.cordova.statusbar required
            StatusBar.styleDefault();
        }
    });
})

One of the errors that I get in android when I use the emulator is this:

Unable to open asset URL: file:///android_asset/www/cordova_plugins.js

But in my path:

C:\myApp\platforms\android\assets\www

There is cordova_plugins.js

Is there something that I'm missing out?
Thank you in advance for the help.


问:
simpleITK N4BiasFieldCorrection performs strange in terms of running speed and results
I am doing a project about brain tumor segmentation. And when I apply N4BiasCorrection to my file(.mha), I used slicer and simpleITK methods.
Slicer performs well but is time-consuming because I do not know how to use code to run through all my file, I just use the Slicer-N4ITK module and process each file by hand.

Then I try the simpleITK with python, problems show up. First, it runs very slow on each .mha file and gets a really big file(36.7MB compare with 4.4MB using Slicer) after applying n4biasfieldcorrection. Second, in order to speed up, I set the Shrink parameter to 4 but the whole .mha file becomes really blurred, which will not happen using slicer.

So can anyone tell me whether it is normal ? are there any methods to speed up without blurring my file? Or could you please tell me an example to apply N4BiasFieldCorrection within Slicer python interactor .

Thanks!!

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
from __future__ import print_function
import SimpleITK as sitk
import sys
import os
#from skimage import io
from glob import glob
import numpy as np

def n4process(inputimage, outpath):
    inputImage = sitk.ReadImage( inputimage )
#    numberFilltingLevels = 4
    maskImage = sitk.OtsuThreshold( inputImage, 0, 1, 200 )
#    inputImage = sitk.Shrink( inputImage, [ 2 ] * inputImage.GetDimension() )
#    maskImage = sitk.Shrink( maskImage, [ 2 ] * inputImage.GetDimension() )
    inputImage = sitk.Cast( inputImage, sitk.sitkFloat32 )
    corrector = sitk.N4BiasFieldCorrectionImageFilter();
    corrector.SetConvergenceThreshold=0.001
    corrector.SetBiasFieldFullWidthAtHalfMaximum=0.15
    corrector.SetMaximumNumberOfIterations=50
    corrector.SetNumberOfControlPoints=4
    corrector.SetNumberOfHistogramBins=200
    corrector.SetSplineOrder=3
    corrector.SetWienerFilterNoise=0.1
    output = corrector.Execute( inputImage,maskImage )
    sitk.WriteImage( output, outpath )

input_path = '/Users/chenrui/Desktop/BRATS2015_Training/HGG/'
patientpath = glob('/Users/chenrui/Desktop/BRATS2015_Training/HGG/*')
num = 0
for i in patientpath:
    num = num+1
#i = '/Users/chenrui/Desktop/BRATS2015_Training/HGG/brats_2013_pat0001_1'
    flair = glob(i + '/*Flair*/*.mha')
    flair_outpath = '/Users/chenrui/Desktop/BRATS2015_Training/test/'+'Flair/'+str(num)+'.mha'
    n4process(flair[0], flair_outpath)

    t2 = glob(i + '/*T2*/*.mha')
    t2_outpath = '/Users/chenrui/Desktop/BRATS2015_Training/HGG_n4/'+'T2/'+str(num)+'.mha'
    n4process(t2[0], t2_outpath)

    t1c = glob(i + '/*_T1c*/*.mha')
    t1c_outpath = '/Users/chenrui/Desktop/BRATS2015_Training/HGG_n4/'+'T1c/'+str(num)+'.mha'
    n4process(t1c[0], t1c_outpath)

    t1 = glob(i + '/*_T1*/*.mha')
    t1 = [scan for scan in t1 if scan not in t1c]
    t1_outpath = '/Users/chenrui/Desktop/BRATS2015_Training/HGG_n4/'+'T1/'+str(num)+'.mha'
    n4process(t1[0],t1_outpath)```

答:
From a look at the original implementation http://www.insight-journal.org/browse/publication/640

You can download this and generate the example to then test on your data. The parameters you set appear to be the same as defined in the defaults except for WeinerFilterNoise which should be 0.01 unless you've changed this for a reason - is this the blurring issue?

The size differential (x 8 increase) will be that you've probably saved out the data from 8bit to 64 bit or something. Checking the metaimage header will show this. This can be resolved with casting.


问:
Pyodbc on El Capitan
I'm having trouble installing pyodbc on El Capitan. I have another virtualenv which was created during Yosemite days that has pyodbc.

I am installing pyodbc through the following command:

```<code>pip install --global-option=build_ext --global-option="-I/usr/local/include" --allow-external pyodbc --allow-unverified pyodbc pyodbc
</code>```

It errs out saying it cannot find odbc dynamic library.

ld: library not found for -lodbc

The version of python I'm using is python 2.7.10(but has similar problems installing in python 2.6.9 too)

答: pyodbc now supplies binary wheels for macOS, for Python 2.7 and 3.4+, so no compilation is necessary.  Note that these are built with unixODBC, not iODBC, however.</p>

Title: Pyodbc on El Capitan

Body:
I'm having trouble installing pyodbc on El Capitan. I have another virtualenv which was created during Yosemite days that has pyodbc.

I am installing pyodbc through the following command:

pip install --global-option=build_ext --global-option="-I/usr/local/include" --allow-external pyodbc --allow-unverified pyodbc pyodbc

It errs out saying it cannot find odbc dynamic library.

ld: library not found for -lodbc

The version of python I'm using is python 2.7.10(but has similar problems installing in python 2.6.9 too)


问:
When enqueueing in tensorflow is it a race condition to use the same placeholder variables from multiple threads?
```<code>queue = tf.FIFOQueue(batch_size * 2, dtypes=[tf.uint8, tf.float32], shapes=[[1,1080,1920,3], [1,11]], name='queue')

x_enqueue = tf.placeholder(dtype=tf.uint8, shape=[1,1080,1920,3], name="x_enqueue")
labels_enqueue = tf.placeholder(tf.float32, shape=[1, 11], name="labels_enqueue")  # todo define in loader thread
</code>```

I've defined a FIFOQueue that I'm going to load from a custom function using multiple threads.

I've also defined placeholders to feed the data to the queue.

Should I define a different placeholder per thread? Or can all threads use the x_enqueue and labels_enqueue placeholders concurrently?

答: As far as I've been able to learn from experimentation, the answer to this is NO. Multiple calls to a session essentially snapshot a point in time view of the current values of the variables, and those values are not visible outside of a run until it has completed all processing. For some more details on how I came to this conclusion see this related question: How are variables shared between concurrent `session.run(...)` calls in tensorflow?</p>

Body:
queue = tf.FIFOQueue(batch_size * 2, dtypes=[tf.uint8, tf.float32], shapes=[[1,1080,1920,3], [1,11]], name='queue')

x_enqueue = tf.placeholder(dtype=tf.uint8, shape=[1,1080,1920,3], name="x_enqueue")
labels_enqueue = tf.placeholder(tf.float32, shape=[1, 11], name="labels_enqueue")  # todo define in loader thread

I've defined a FIFOQueue that I'm going to load from a custom function using multiple threads.

I've also defined placeholders to feed the data to the queue.

Should I define a different placeholder per thread? Or can all threads use the x_enqueue and labels_enqueue placeholders concurrently?


问:
Connect dynamically to signals of dynamically created objects
The title might be a bit confusing, but my intent is pretty simple:

I have a [Repeater/Instantiator] which creates multiple instances of a arbitrary delegate. I want to react to all changes of the properties (only first-level, so no properties of properties) of the instances of the delegate, calling a function

```<code>function update(index, propertyName)
</code>```

This seems to be easy, but I fail. This is my code

TestObj.qml

```<code>Repeater {
    onItemAdded: {
        var keys = Object.keys(item)
        console.log(keys)
        for (var k = 0; k < keys.length; k++) {
            if (item[keys[k] + 'Changed'] !== undefined  && keys[k] !== 'objectName') {
                var key = keys[k]
                var str = "function() { console.log('Property, " + key + " of " + index + " changed') }"
                console.log(str)
                item[key + 'Changed'].connect(function() { console.log('Property', key, 'of', index, 'changed') })
            }
        }
    }
}
</code>```

main.qml:

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQml 2.2
import QtQuick.Controls 1.4 as Ctrl
import '.'
import 'test.js' as Test

ApplicationWindow {
    id: root
    visible: true
    minimumWidth: 500
    minimumHeight: 500
    property var blub: []

    Column {
        spacing: 5
        TestObj {
            model: 5
            delegate: Row {
                spacing: 2
                property int p1: 0
                property int p2: 2
                property int p3: 4

                Button {
                    text: parent.p1
                    onClicked: parent.p1++
                }
                Button {
                    text: parent.p2
                    onClicked: parent.p2 *= 2
                }
                Button {
                    text: parent.p3
                    onClicked: parent.p3 *= parent.p3
                }
            }
        }
    }
}
</code>```

It succesfully connects something, but I can't get the key properly locked. Whichever property I change, I always get the info, I had changed property p3 in my example.

How can I lock the key, so that I get propertyName when I change the the property with the corresponding name?

答:
One possible solution is, to create an object that has the function, and then just assign this function

```<code>Repeater {
    onItemAdded: {
        var keys = Object.keys(item)
        for (var k = 0; k < keys.length; k++) {
            if (item[keys[k] + 'Changed'] !== undefined  && keys[k] !== 'objectName') {
                var key = keys[k]
                var f = __funproto.createObject(this, { i: index, n: key })
                item[key + 'Changed'].connect(f.fun)
            }
        }
    }
}

Component {
    id: __funproto
    QtObject {
        property int i
        property string n
        function fun() { /*do something with it!*/}
    }
}
</code>```

But maybe there is a even better solution waiting to be disclosed?

Body:
The title might be a bit confusing, but my intent is pretty simple:

I have a [Repeater/Instantiator] which creates multiple instances of a arbitrary delegate. I want to react to all changes of the properties (only first-level, so no properties of properties) of the instances of the delegate, calling a function

function update(index, propertyName)

This seems to be easy, but I fail. This is my code

TestObj.qml

Repeater {
    onItemAdded: {
        var keys = Object.keys(item)
        console.log(keys)
        for (var k = 0; k < keys.length; k++) {
            if (item[keys[k] + 'Changed'] !== undefined  && keys[k] !== 'objectName') {
                var key = keys[k]
                var str = "function() { console.log('Property, " + key + " of " + index + " changed') }"
                console.log(str)
                item[key + 'Changed'].connect(function() { console.log('Property', key, 'of', index, 'changed') })
            }
        }
    }
}

main.qml:

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQml 2.2
import QtQuick.Controls 1.4 as Ctrl
import '.'
import 'test.js' as Test

ApplicationWindow {
    id: root
    visible: true
    minimumWidth: 500
    minimumHeight: 500
    property var blub: []

    Column {
        spacing: 5
        TestObj {
            model: 5
            delegate: Row {
                spacing: 2
                property int p1: 0
                property int p2: 2
                property int p3: 4

                Button {
                    text: parent.p1
                    onClicked: parent.p1++
                }
                Button {
                    text: parent.p2
                    onClicked: parent.p2 *= 2
                }
                Button {
                    text: parent.p3
                    onClicked: parent.p3 *= parent.p3
                }
            }
        }
    }
}

It succesfully connects something, but I can't get the key properly locked. Whichever property I change, I always get the info, I had changed property p3 in my example.

How can I lock the key, so that I get propertyName when I change the the property with the corresponding name?

Body:
One possible solution is, to create an object that has the function, and then just assign this function

Repeater {
    onItemAdded: {
        var keys = Object.keys(item)
        for (var k = 0; k < keys.length; k++) {
            if (item[keys[k] + 'Changed'] !== undefined  && keys[k] !== 'objectName') {
                var key = keys[k]
                var f = __funproto.createObject(this, { i: index, n: key })
                item[key + 'Changed'].connect(f.fun)
            }
        }
    }
}

Component {
    id: __funproto
    QtObject {
        property int i
        property string n
        function fun() { /*do something with it!*/}
    }
}

But maybe there is a even better solution waiting to be disclosed?


问:
Best way to write a hash to a file
According to the dbmopen-docu this function has been largely superseded by the "tie" function.
I know the Tie::File module which accesses the lines of a disk file via a Perl array.
How would I do it if I don't need an array but a hash?</p>

答:
The core-module SDBM_File could tie a hash to a file:

```<code>use Fcntl;
use SDBM_File;

tie(%h, 'SDBM_File', 'filename', O_RDWR|O_CREAT, 0666) or die $!;
...
...
untie %h;
</code>```

But: "...the length of a key, plus the length of its associated value, may not exceed 1008 bytes."

Title: Best way to write a hash to a file

Body:
The core-module SDBM_File could tie a hash to a file:

use Fcntl;
use SDBM_File;

tie(%h, 'SDBM_File', 'filename', O_RDWR|O_CREAT, 0666) or die $!;
...
...
untie %h;

But: "...the length of a key, plus the length of its associated value, may not exceed 1008 bytes."


问:
Jquery Modal Confirmation on Django form submit for deletion of object
I am using Django with Crispy forms and am also using the Shopify Embedded Apps SDK. I am trying to have a modal window appear to let the user confirm that they want to delete an object.

My code is attached so far. I have the modal window appearing with the following code, however, the form is not submitted (and the object is not deleted) after the user selects 'delete' on the modal window:

It just closed the modal and nothing happens.

I have tried various methods from around the net, but haven't had any luck.

form.py

```<code>class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper(self)

        self.helper.form_id = 'edit_form'

        self.helper.layout = Layout(
            [... some input fields...]
        )

        # Add delete button
        self.helper.layout.append(Button('delete', 'delete'))

        # Normal submit button
        self.helper.layout.append(Submit('save', 'save'))
</code>```

views.py

```<code>@login_required
def edit_object(request, *args, **kwargs):
    # Form handling logic
     with request.user.session:
         object = get_object_or_404(models.Object, pk=kwargs['object_id'], ...)

        if request.method == "POST":
            form = forms.MyForm(request.POST, request=request, instance=object)

            if not form.is_valid():
               [... do some stuff ...]

            if form.is_valid():

                # If the save button is pressed
                if request.POST.get('save'):
                    [... do some stuff to save and redirect to url of my choice ...]

                # If the delete button is pressed <<<< The Modal should appear prior to this
                if request.POST.get('delete'):
                    [... delete to object and redirect to url of my choice ... ]
        else:
            form = forms.MyForm(request=request, instance=supplier)

        return render(request, 'template.html', {'form': form})
</code>```

template.html using Shopify Embedded App SDK:

```<code>    <script type="text/javascript">
        [...]
        ShopifyApp.ready(function() {
            ShopifyApp.Bar.initialize({});

            $("#button-id-delete").click(function(ev){
                ShopifyApp.Modal.confirm({message: "Are you sure you want to delete?"}, function(result){
                    if(!result){
                        result.preventDefault();
                    }
                    else {
                        alert("Contine");
                        $("form#edit_form").submit();
                    }
                });
            });
        });
    </script>

<form enctype="multipart/form-data" method="post">
    {% crispy form %}
</form>
</code>```

rendered html

```<code><form enctype="multipart/form-data" method="post">
    <form  id="edit_form" method="post" > <input type='hidden' name='csrfmiddlewaretoken' value='.......' />
       [.... various input fields .....]
       <input type="button"
          name="delete"
          value="delete"
          class="btn destroy btn"
          id="button-id-delete"
          />
       <input type="submit"
          name="save"
          value="save"
          class="btn btn-primary"
          id="submit-id-save"
          />
    </form>
</form>
</code>```

答:
I was able to get it working with this js:</p>

```<code>$("#submit-id-delete").click(function(ev){
    ev.preventDefault();

    var deleteBtn = $(this);

    ShopifyApp.Modal.confirm(
        {
            title: "Delete?",
            message: "Are you sure you want to delete this?",
            okButton: "Yes, delete",
            style: "danger"
        },
            function(result){

        if(!result){
            return false;
        }
        else {
            deleteBtn.parents('form').append('<input type="hidden" name="delete" id="delete" value="delete" />').submit();
            return true;
        }

    });
});
</code>```

Body:
I am using Django with Crispy forms and am also using the Shopify Embedded Apps SDK. I am trying to have a modal window appear to let the user confirm that they want to delete an object.

My code is attached so far. I have the modal window appearing with the following code, however, the form is not submitted (and the object is not deleted) after the user selects 'delete' on the modal window:

It just closed the modal and nothing happens.

I have tried various methods from around the net, but haven't had any luck.

form.py

class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper(self)

        self.helper.form_id = 'edit_form'

        self.helper.layout = Layout(
            [... some input fields...]
        )

        # Add delete button
        self.helper.layout.append(Button('delete', 'delete'))

        # Normal submit button
        self.helper.layout.append(Submit('save', 'save'))

views.py

@login_required
def edit_object(request, *args, **kwargs):
    # Form handling logic
     with request.user.session:
         object = get_object_or_404(models.Object, pk=kwargs['object_id'], ...)

        if request.method == "POST":
            form = forms.MyForm(request.POST, request=request, instance=object)

            if not form.is_valid():
               [... do some stuff ...]

            if form.is_valid():

                # If the save button is pressed
                if request.POST.get('save'):
                    [... do some stuff to save and redirect to url of my choice ...]

                # If the delete button is pressed <<<< The Modal should appear prior to this
                if request.POST.get('delete'):
                    [... delete to object and redirect to url of my choice ... ]
        else:
            form = forms.MyForm(request=request, instance=supplier)

        return render(request, 'template.html', {'form': form})

template.html using Shopify Embedded App SDK:

<form enctype="multipart/form-data" method="post">
    {% crispy form %}
</form>

rendered html

<form enctype="multipart/form-data" method="post">
    <form  id="edit_form" method="post" > <input type='hidden' name='csrfmiddlewaretoken' value='.......' />
       [.... various input fields .....]
       <input type="button"
          name="delete"
          value="delete"
          class="btn destroy btn"
          id="button-id-delete"
          />
       <input type="submit"
          name="save"
          value="save"
          class="btn btn-primary"
          id="submit-id-save"
          />
    </form>
</form>

Body:
I was able to get it working with this js:

$("#submit-id-delete").click(function(ev){
    ev.preventDefault();

    var deleteBtn = $(this);

    ShopifyApp.Modal.confirm(
        {
            title: "Delete?",
            message: "Are you sure you want to delete this?",
            okButton: "Yes, delete",
            style: "danger"
        },
            function(result){

        if(!result){
            return false;
        }
        else {
            deleteBtn.parents('form').append('<input type="hidden" name="delete" id="delete" value="delete" />').submit();
            return true;
        }

    });
});


问:
Multiple lines not reading into one list item
For some reason when I read in clipboard data and write it to a file, read that file in and set it to a list after delineating it with ¢ it loads up my listbox just fine on the first load as in when my form first loads up. However I have the following trigger on a button click, it is for some reason splitting up multiple line sections into separate list items, which is not what I want and not what the same code does when the form first loads. It's a little frustrating as it's writing to the text file and everything the same way.

```<code>private void button2_Click_1(object sender, EventArgs e)
    {

        // until next comment this is the same as what I have run at the start of the
        // program, it loads up multiple lines into one list item as it should
        string checkForDupe = File.ReadAllText(@"C:\temp\testfile.txt");
        string checkResponses = File.ReadAllText(@"C:\temp\testfile2.txt");
        if (Clipboard.ContainsText() && !checkForDupe.Contains(Clipboard.GetText()))
        {
            if (!checkResponses.Contains(Clipboard.GetText()))
            {
                var text = "\n" + Clipboard.GetText() + "¢";

                File.AppendAllText(@"C:\temp\testfile.txt", text);
            }
        }
        //The following has no affect on the issue stated in my question I have tried with out it.
        string[] responseTags2 = File.ReadAllLines(@"C:\temp\testfile.txt");
        List<string> _responseTags2 = new List<string>(responseTags2);
        var count = _responseTags2.Count;
        // Perform a reverse tracking.
        for (var i = count - 1; i > -1; i--)
        {
            if (_responseTags2[i] == string.Empty) _responseTags2.RemoveAt(i);
        }
        // Keep only the unique list items.
        _responseTags2 = _responseTags2.Distinct().ToList();

        listBox1.BeginUpdate();
        listBox1.DataSource = _responseTags2;
        listBox1.EndUpdate();
    }
</code>```

input example:
"This is multiple lines in
a text file that is for testing
this application"

right output example (what I get when the same code is running at the start of the program before the form is loaded):
"This is multiple lines in
a text file that is for testing
this application" ,

"This is ANOTHER multiple lines in
a text file that is for testing
this application" ,

"This is a single line"

WRONG output (what I get when I run off the button click that eventual updates the UI):

"This is multiple lines in",
"a text file that is for testing",
"this application"

答:
You are getting multiple lines in your listbox because you are not breaking the text by ¢ but just reading them into lines. This is your code:

```<code>string[] responseTags2 = File.ReadAllLines(@"C:\temp\testfile.txt");
</code>```

Do this instead. Read all the text:

```<code>var contents = File.ReadAllText(@"C:\temp\testfile.txt");
</code>```

Now split them using the character ¢:

```<code>var lines = s.Split('¢');
</code>```

Here is the final linq to remove any empties and return distinct items:

```<code>var lines = s.Split('¢')
          .Where(item => item != string.Empty)
          .Distinct()
          .ToList();
</code>```

Then set lines to be the datasource:

```<code>listBox1.BeginUpdate();
listBox1.DataSource = lines;
listBox1.EndUpdate();
</code>```

Body:
For some reason when I read in clipboard data and write it to a file, read that file in and set it to a list after delineating it with ¢ it loads up my listbox just fine on the first load as in when my form first loads up. However I have the following trigger on a button click, it is for some reason splitting up multiple line sections into separate list items, which is not what I want and not what the same code does when the form first loads. It's a little frustrating as it's writing to the text file and everything the same way.

private void button2_Click_1(object sender, EventArgs e)
    {

        // until next comment this is the same as what I have run at the start of the
        // program, it loads up multiple lines into one list item as it should
        string checkForDupe = File.ReadAllText(@"C:\temp\testfile.txt");
        string checkResponses = File.ReadAllText(@"C:\temp\testfile2.txt");
        if (Clipboard.ContainsText() && !checkForDupe.Contains(Clipboard.GetText()))
        {
            if (!checkResponses.Contains(Clipboard.GetText()))
            {
                var text = "\n" + Clipboard.GetText() + "¢";

                File.AppendAllText(@"C:\temp\testfile.txt", text);
            }
        }
        //The following has no affect on the issue stated in my question I have tried with out it.
        string[] responseTags2 = File.ReadAllLines(@"C:\temp\testfile.txt");
        List<string> _responseTags2 = new List<string>(responseTags2);
        var count = _responseTags2.Count;
        // Perform a reverse tracking.
        for (var i = count - 1; i > -1; i--)
        {
            if (_responseTags2[i] == string.Empty) _responseTags2.RemoveAt(i);
        }
        // Keep only the unique list items.
        _responseTags2 = _responseTags2.Distinct().ToList();

        listBox1.BeginUpdate();
        listBox1.DataSource = _responseTags2;
        listBox1.EndUpdate();
    }

input example:
"This is multiple lines in
a text file that is for testing
this application"

right output example (what I get when the same code is running at the start of the program before the form is loaded):
"This is multiple lines in
a text file that is for testing
this application" ,

"This is ANOTHER multiple lines in
a text file that is for testing
this application" ,

"This is a single line"

WRONG output (what I get when I run off the button click that eventual updates the UI):

"This is multiple lines in",
"a text file that is for testing",
"this application"

Body:
You are getting multiple lines in your listbox because you are not breaking the text by ¢ but just reading them into lines. This is your code:

string[] responseTags2 = File.ReadAllLines(@"C:\temp\testfile.txt");

Do this instead. Read all the text:

var contents = File.ReadAllText(@"C:\temp\testfile.txt");

Now split them using the character ¢:

var lines = s.Split('¢');

Here is the final linq to remove any empties and return distinct items:

var lines = s.Split('¢')
          .Where(item => item != string.Empty)
          .Distinct()
          .ToList();

Then set lines to be the datasource:

listBox1.BeginUpdate();
listBox1.DataSource = lines;
listBox1.EndUpdate();


问:
How to pass a variant of Jquery to a Javascript function?
I'm begginer in Jquery and Javascript,
I need to know if it is possible to send the value of a jquery variable to javascript.
I have this code in Jquery:

```<code>var value;
    $('#cb-tab').on("click", function () {
       value = $(this).data("valor" , 2);
       console.log(value);
    });
</code>```

How do I make the "value" parameter can be sent to a function in javascript.

答:
Pass the value as an argument to the function you need to call:

```<code>$('#cb-tab').on("click", function() {
  var value = $(this).data("valor");
  someFunction(value);
});

function someFunction(value) {
    alert("the value is: " + value);
}
</code>```

JSFiddle Demo: https://jsfiddle.net/69zkturp/

Body:
I'm begginer in Jquery and Javascript,
I need to know if it is possible to send the value of a jquery variable to javascript.
I have this code in Jquery:

var value;
    $('#cb-tab').on("click", function () {
       value = $(this).data("valor" , 2);
       console.log(value);
    });

How do I make the "value" parameter can be sent to a function in javascript.

Body:
Pass the value as an argument to the function you need to call:

$('#cb-tab').on("click", function() {
  var value = $(this).data("valor");
  someFunction(value);
});

function someFunction(value) {
    alert("the value is: " + value);
}

JSFiddle Demo: https://jsfiddle.net/69zkturp/


问:
jQuery DataTables: Can I have 3 states for Sort : ASC, DESC and NO_SORT?
jQuery Datatable's sorting order on clicking column header toggles only between asc(Down Arrow) and desc(Up Arrow). i.e.,

```<code>1st-click ascending
2nd-click descending
3rd-click asc
4th-click desc
   ||   ||
   ||   ||
   ||   ||
   ||   ||
odd-click asc
even-click desc.
</code>```

I want to induce something like this :

```<code>1st-click ascending
2nd-click descending
3rd-click no-sorting
4th-click asc
5th-click desc
6th-click no-sort
   ||   ||
   ||   ||
   ||   ||
   ||   ||
(n%3==1)-click asc
(n%3==2)-click desc
(n%3==0)-click no-sort.
</code>```

Is there a way to change this behavior in jQuery dataTables? Please help!
Thanks in advance.

答:
Wow, that was interesting. This should do what you need though it's not elegant:

```<code>$('#example').on("order.dt", function () {
    if(example.settings().order().length === 1){
        var order = example.settings().order()[0];
        var th = $("#example th:eq(" + order[0] + ")");
        if(th.attr("data-sort-next") === "false"){
            example.order([]).draw();
            th.attr("data-sort-next", true);
        }else{
            if(order[1] === "desc"){
                th.attr("data-sort-next", false);
            }else{
                th.attr("data-sort-next", true);
            }
        }
    }
});
</code>```

This working JSFiddle illustrates what's going on. Basically, what you want is available out of the box for multi-column sorting (as noted in the comments). What I've done is intercept the sorting if there's only one column being sorted, without messing up the multi-column sorting. I'll keep on trying to refine it but that should work for you.

Body:
jQuery Datatable's sorting order on clicking column header toggles only between asc(Down Arrow) and desc(Up Arrow). i.e.,

1st-click ascending
2nd-click descending
3rd-click asc
4th-click desc
   ||   ||
   ||   ||
   ||   ||
   ||   ||
odd-click asc
even-click desc.

I want to induce something like this :

1st-click ascending
2nd-click descending
3rd-click no-sorting
4th-click asc
5th-click desc
6th-click no-sort
   ||   ||
   ||   ||
   ||   ||
   ||   ||
(n%3==1)-click asc
(n%3==2)-click desc
(n%3==0)-click no-sort.

Is there a way to change this behavior in jQuery dataTables? Please help!
Thanks in advance.

Body:
Wow, that was interesting. This should do what you need though it's not elegant:

$('#example').on("order.dt", function () {
    if(example.settings().order().length === 1){
        var order = example.settings().order()[0];
        var th = $("#example th:eq(" + order[0] + ")");
        if(th.attr("data-sort-next") === "false"){
            example.order([]).draw();
            th.attr("data-sort-next", true);
        }else{
            if(order[1] === "desc"){
                th.attr("data-sort-next", false);
            }else{
                th.attr("data-sort-next", true);
            }
        }
    }
});

This working JSFiddle illustrates what's going on. Basically, what you want is available out of the box for multi-column sorting (as noted in the comments). What I've done is intercept the sorting if there's only one column being sorted, without messing up the multi-column sorting. I'll keep on trying to refine it but that should work for you.


问:
Add a tag in remote repository without adding the repo on local
Do have anyway to add a tag in remote repository without cloning/adding it on local. I just need to do it for marking QA builds</p>

答:
I needed to push a tag to remote that didn't exist in local and was at the remote's head, rather than mine.

```<code>git push origin origin/head:refs/tags/foo
</code>```

We were having the problem of deploying from individual machines, who may or may not have gotten the latest, and tagging the release. The tag would show up further down the log even though the release incorporated the latest commit.

The answer above is correct and very well-explained, but didn't address my variation on the asked question.

Body:
I needed to push a tag to remote that didn't exist in local and was at the remote's head, rather than mine.

git push origin origin/head:refs/tags/foo

We were having the problem of deploying from individual machines, who may or may not have gotten the latest, and tagging the release. The tag would show up further down the log even though the release incorporated the latest commit.

The answer above is correct and very well-explained, but didn't address my variation on the asked question.