问:
Error while installing react native app in MIUI device
In my MIUI device USB debugging is enabled and MIUI optimization is disabled. But when I run react-native run-android command. I have such error:

```<code>Installing APK 'app-debug.apk' on 'Redmi Note 3 - 5.0.2' for app:debug
Unable to install C:\Users\admin\FirstProject\android\app\build\outputs\apk\app-debug.apk
com.android.ddmlib.InstallException: Failed to install all
at com.android.ddmlib.SplitApkInstaller.install(SplitApkInstaller.java:89)
at com.android.ddmlib.Device.installPackages(Device.java:904)
at com.android.builder.testing.ConnectedDevice.installPackages(ConnectedDevice.java:137)
at com.android.build.gradle.internal.tasks.InstallVariantTask.install(InstallVariantTask.java:134)
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.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:228)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:221)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:210)
at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:621)
at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:604)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:66)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:25)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:110)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.java:153)
at org.gradle.internal.Factories$1.create(Factories.java:22)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:53)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:150)
at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:32)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:98)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:92)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:63)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:92)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:83)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:99)
at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:48)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:81)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:46)
at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:51)
at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:28)
at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:43)
at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:173)
at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:239)
at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:212)
at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:205)
at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
at org.gradle.launcher.Main.doAction(Main.java:33)
at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
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.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:55)
at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:36)
at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
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.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:30)
at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:127)
at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
    06:42:06 E/1316520576: Error while uploading app-debug.apk : Unknown failure ([CDS]close[0])
    :app:installDebug FAILED

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ':app:installDebug'.
    > com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: Failed to install all
</code>```

I could not find the solution over the Internet, please help me, I want to run React native app on my device!

答:
I faced similar issue on my miui device couldnt make it work with react-native run-android.
An alternative solution  is to build debug apk with cd android && ./gradlew assembleDebug and copy to your phone and install, you could do debugging by remote js debugging. You can find the output apk in android/app/build/outputs/apk/. Remember to keep the packager running and be in same network.

Body:
In my MIUI device USB debugging is enabled and MIUI optimization is disabled. But when I run react-native run-android command. I have such error:

Installing APK 'app-debug.apk' on 'Redmi Note 3 - 5.0.2' for app:debug
Unable to install C:\Users\admin\FirstProject\android\app\build\outputs\apk\app-debug.apk
com.android.ddmlib.InstallException: Failed to install all
at com.android.ddmlib.SplitApkInstaller.install(SplitApkInstaller.java:89)
at com.android.ddmlib.Device.installPackages(Device.java:904)
at com.android.builder.testing.ConnectedDevice.installPackages(ConnectedDevice.java:137)
at com.android.build.gradle.internal.tasks.InstallVariantTask.install(InstallVariantTask.java:134)
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.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:228)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:221)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:210)
at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:621)
at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:604)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:66)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:25)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:110)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.java:153)
at org.gradle.internal.Factories$1.create(Factories.java:22)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:53)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:150)
at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:32)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:98)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:92)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:63)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:92)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:83)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:99)
at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:48)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:81)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:46)
at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:51)
at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:28)
at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:43)
at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:173)
at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:239)
at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:212)
at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:205)
at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
at org.gradle.launcher.Main.doAction(Main.java:33)
at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
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.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:55)
at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:36)
at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
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.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:30)
at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:127)
at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
    06:42:06 E/1316520576: Error while uploading app-debug.apk : Unknown failure ([CDS]close[0])
    :app:installDebug FAILED

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ':app:installDebug'.
    > com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: Failed to install all

I could not find the solution over the Internet, please help me, I want to run React native app on my device!


来源: stackexchange

问:
How to read a file from inside an OpenWhisk action
I'm writing an OpenWhisk action in Python 3, which needs to read a local file. It seems once I create an OpenWhisk action with this python file and invoke it, the python action can't read this local file anymore. The local file locates in the same dir as the python file does. The logs reads
    stderr: IOError: [Errno 2] No such file or directory: './localFile'

Does any one know how to access a file from within an OpenWhisk action?

答:
The problem is that a relative reference to a file will not work, since the source code runs from a different direction (/action) compared to the internal runtime. This can be remedied in a brute force way by not referencing files using a relative path (e.g., ./).

For example, this will work - but no ideal:

```<code>$ cat __main__.py
def main(args):
  f = open('/action/workfile', 'r')
  return {'file': f.read()}

$ echo "hello" > workfile

$ zip p.zip __main__.py workfile

$ wsk action update p p.zip --kind python:3
ok: updated action p

$ wsk action invoke -br p
{
    "file": "hello\n"
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The problem is that a relative reference to a file will not work, since the source code runs from a different direction (/action) compared to the internal runtime. This can be remedied in a brute force way by not referencing files using a relative path (e.g., ./).

For example, this will work - but no ideal:

$ cat __main__.py
def main(args):
  f = open('/action/workfile', 'r')
  return {'file': f.read()}

$ echo "hello" > workfile

$ zip p.zip __main__.py workfile

$ wsk action update p p.zip --kind python:3
ok: updated action p

$ wsk action invoke -br p
{
    "file": "hello\n"
}


问:
Angular2 Templates: How to bind keydown.arrow to whole div instead of only control elements?
I have a simple navigator component with some buttons and a date-picker subcomponent. Now the idea is, that I can bind keydown.arrowleft etc. for the whole div (which has css style of 100% height and width). It's template looks like this:

```<code><div id="ck-navigator" (keydown.arrowleft)="decrementDate();
    $event.preventDefault()" (keydown.arrowright)="incrementDate();
$event.preventDefault()">
    <button (click)="decrementDate()" class="fa fa-2x fa-chevron-left">
    </button>
    <ck-date-picker [date]="date" (dateChange)="changeDate($event)">
    </ck-date-picker>
    <button (click)="incrementDate()" class="fa fa-2x fa-chevron-right"></button>
</div>
</code>```

I don't show the component code, it does not matter for this question (afaik).
This is working, but only if I actively select a button or the date-picker in advance (aka a control element). Is there a possibility to extend the keybinding to the whole div (i.e. if I just click somewhere on the site). Sorry for my lack of understanding the DOM and thanks for any push in the right direction.

答: The problem is that your div is not focusable so it isn't reacting to your keybindings. Try adding the attribute tabindex="0" to the div.

Body:
I have a simple navigator component with some buttons and a date-picker subcomponent. Now the idea is, that I can bind keydown.arrowleft etc. for the whole div (which has css style of 100% height and width). It's template looks like this:

    <button (click)="decrementDate()" class="fa fa-2x fa-chevron-left">
    </button>
    <ck-date-picker [date]="date" (dateChange)="changeDate($event)">
    </ck-date-picker>
    <button (click)="incrementDate()" class="fa fa-2x fa-chevron-right"></button>

I don't show the component code, it does not matter for this question (afaik).
This is working, but only if I actively select a button or the date-picker in advance (aka a control element). Is there a possibility to extend the keybinding to the whole div (i.e. if I just click somewhere on the site). Sorry for my lack of understanding the DOM and thanks for any push in the right direction.


问:
Construct an adjacency matrix
We want to construct an adjacency matrix (value of 1 if A_Number called B_Number, 0 if otherwise).
Weight= number of times the two numbers called.

Input:

```<code>B = matrix(c(1,4,1, 2,4,1, 3,2,1, 4,5,1, 5,2,1),
           nrow = 5,
           ncol = 3,
           byrow = TRUE)

colnames(B) <- c("A_NUMBER", "B_NUMBER", "Weight")

#      A_NUMBER B_NUMBER Weight
# [1,]        1        4      1
# [2,]        2        4      1
# [3,]        3        2      1
# [4,]        4        5      1
# [5,]        5        2      1
</code>```

Wanted output:

We tried following code:

```<code>p<-as.matrix(dcast(SNA_data, A_NUMBER~B_NUMBER, value.var="W", fill=0))
</code>```

But this did not gave as an adjacency matrix as the names of the rows were not the same as the names of the columns.
Does somebody know how to make a proper adjacency matrix?

答: xtabs(Weight ~ A_NUMBER + B_NUMBER,B) will do it.  If you want the zero rows/columns as well, just add some dummy rows (Weight=0) to your matrix, covering the full range of values that A_NUMBER and B_NUMBER might take.

Title: Construct an adjacency matrix

Body:
We want to construct an adjacency matrix (value of 1 if A_Number called B_Number, 0 if otherwise).
Weight= number of times the two numbers called.

Input:

B = matrix(c(1,4,1, 2,4,1, 3,2,1, 4,5,1, 5,2,1),
           nrow = 5,
           ncol = 3,
           byrow = TRUE)

colnames(B) <- c("A_NUMBER", "B_NUMBER", "Weight")

#      A_NUMBER B_NUMBER Weight
# [1,]        1        4      1
# [2,]        2        4      1
# [3,]        3        2      1
# [4,]        4        5      1
# [5,]        5        2      1

Wanted output:

We tried following code:

p<-as.matrix(dcast(SNA_data, A_NUMBER~B_NUMBER, value.var="W", fill=0))

But this did not gave as an adjacency matrix as the names of the rows were not the same as the names of the columns.
Does somebody know how to make a proper adjacency matrix?


问:
Get List of Official Docker Images
I am trying to get a list of all the official images from the Docker Store. However, I could not find any simple way to get the list. Docker CLI has a docker search command but it does not have any argument to get
 a list of all the images from the Docker Store and then filter it later.

Any ideas how it could be done?

答:
If you click the "explore" menu item at the top; https://store.docker.com/search?q=&source=verified&type=image all official images are shown. You can find non official images in the "Community (Docker Hub)" section.

From the command-line, you can search using the --filter is-official=true filter option, for example:

```<code>docker search --filter is-official=true php
NAME             DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
php              While designed for web development, the PH...   2210      [OK]
php-zendserver   Zend Server - the integrated PHP applicati...   110       [OK]
</code>```

Title: Get List of Official Docker Images

Body:
If you click the "explore" menu item at the top; https://store.docker.com/search?q=&source=verified&type=image all official images are shown. You can find non official images in the "Community (Docker Hub)" section.

From the command-line, you can search using the --filter is-official=true filter option, for example:

docker search --filter is-official=true php
NAME             DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
php              While designed for web development, the PH...   2210      [OK]
php-zendserver   Zend Server - the integrated PHP applicati...   110       [OK]


问:
Order of conditions are effecting radio buttons
I am working on a test page where users can configure there planter.
Calculation etc works fine. But when the radio buttons are used the order of conditions are effecting them.

When Bottom no is selected user should not be able to select feet of wheels > OK
When Bottom yes is selected user should not be able to select feet of wheels > OK

But feet or wheels can not be selected at the same time.
So when wheels yes is selected and then feet yes selected > wheels has to be set to no > OK

But the other way around when feet yes is selected and the wheels yes the script is unable (due to order of conditions?) to set feet to no?

Any suggestions?

```<code><script type="text/javascript">
function calculatie()
{
// very much code

// Totaalprijs met of zonder pootjes
if(document.getElementById('feet_no').checked)
{
    document.getElementsByName('kosten_inkoop')[0].value = (document.getElementsByName('kosten_inkoop')[0].value);
}
else if(document.getElementById('feet_yes').checked)
{
    document.getElementsByName('kosten_inkoop')[0].value = ((document.getElementsByName('kosten_inkoop')[0].value * 1) + (document.getElementsByName('kosten_pootjes')[0].value * 1)).toFixed( 2 );
    document.getElementById('wheel_no').checked = true;
}

// Totaalprijs met of zonder wieltjes
if(document.getElementById('wheel_no').checked)
{
    document.getElementsByName('kosten_inkoop')[0].value = (document.getElementsByName('kosten_inkoop')[0].value);
}
else if(document.getElementById('wheel_yes').checked)
{
    document.getElementsByName('kosten_inkoop')[0].value = ((document.getElementsByName('kosten_inkoop')[0].value * 1) + (document.getElementsByName('kosten_wieltjes')[0].value * 1)).toFixed( 2 );
    document.getElementById('feet_no').checked = true;
}
}
</script>

<tr>
    <td>Bottom</td>
    <td>No <input type="radio" name="bottom" onChange="calculatie()"
    onfocus="document.getElementById('bottom').style.display='block';document.getElementById('basis').style.display='none';"
    onblur="document.getElementById('bottom').style.display='none';document.getElementById('basis').style.display='block';"
    value="no" id="bottom_no" checked="checked">

    <input type="radio" name="bottom" onChange="calculatie()"
    onfocus="document.getElementById('bottom').style.display='block';document.getElementById('basis').style.display='none';"
    onblur="document.getElementById('bottom').style.display='none';document.getElementById('basis').style.display='block';"
    value="yes" id="bottom_yes" > Yes</td>

    <td><div id="dim_top">Dim from top <input type="text" name="bottom_dim" size="2" onChange="calculatie()"
    onfocus="document.getElementById('bottom_dim').style.display='block';document.getElementById('basis').style.display='none';"
    onblur="document.getElementById('bottom_dim').style.display='none';document.getElementById('basis').style.display='block';"
    value="" /> cm </div></td>
</tr>
<tr>
    <td>Feet</td>
    <td>No <input type="radio" name="feet" onChange="calculatie()"
    onfocus="document.getElementById('feet').style.display='block';document.getElementById('basis').style.display='none';"
    onblur="document.getElementById('feet').style.display='none';document.getElementById('basis').style.display='block';"
    value="no" id="feet_no" checked="checked">

    <input type="radio" name="feet" onChange="calculatie()"
    onfocus="document.getElementById('feet').style.display='block';document.getElementById('basis').style.display='none';"
    onblur="document.getElementById('feet').style.display='none';document.getElementById('basis').style.display='block';"
    value="yes" id="feet_yes" > Yes</td>
</tr>
<tr>
    <td>wheel</td>
    <td>No <input type="radio" name="wheel" onChange="calculatie()"
    onfocus="document.getElementById('wheel').style.display='block';document.getElementById('basis').style.display='none';"
    onblur="document.getElementById('wheel').style.display='none';document.getElementById('basis').style.display='block';"
    value="no" id="wheel_no" checked="checked">

    <input type="radio" name="wheel" onChange="calculatie()"
    onfocus="document.getElementById('wheel').style.display='block';document.getElementById('basis').style.display='none';"
    onblur="document.getElementById('wheel').style.display='none';document.getElementById('basis').style.display='block';"
    value="yes" id="wheel_yes" > Yes</td>
</tr>
</code>```

http://torza.nl/leon2.php

答:
Try the below script and it should work. Made a slight change in it,

```

The order of the if conditions is creating the problem. The radio button is switched when "Wheel Yes" is clicked, but due to the if condition its reverting back.

Body:
I am working on a test page where users can configure there planter.
Calculation etc works fine. But when the radio buttons are used the order of conditions are effecting them.

When Bottom no is selected user should not be able to select feet of wheels > OK
When Bottom yes is selected user should not be able to select feet of wheels > OK

But feet or wheels can not be selected at the same time.
So when wheels yes is selected and then feet yes selected > wheels has to be set to no > OK

But the other way around when feet yes is selected and the wheels yes the script is unable (due to order of conditions?) to set feet to no?

Any suggestions?

    Bottom
    No <input type="radio" name="bottom" onChange="calculatie()"
    onfocus="document.getElementById('bottom').style.display='block';document.getElementById('basis').style.display='none';"
    onblur="document.getElementById('bottom').style.display='none';document.getElementById('basis').style.display='block';"
    value="no" id="bottom_no" checked="checked">

    <input type="radio" name="bottom" onChange="calculatie()"
    onfocus="document.getElementById('bottom').style.display='block';document.getElementById('basis').style.display='none';"
    onblur="document.getElementById('bottom').style.display='none';document.getElementById('basis').style.display='block';"
    value="yes" id="bottom_yes" > Yes

Dim from top <input type="text" name="bottom_dim" size="2" onChange="calculatie()"
    onfocus="document.getElementById('bottom_dim').style.display='block';document.getElementById('basis').style.display='none';"
    onblur="document.getElementById('bottom_dim').style.display='none';document.getElementById('basis').style.display='block';"
    value="" /> cm

    Feet
    No <input type="radio" name="feet" onChange="calculatie()"
    onfocus="document.getElementById('feet').style.display='block';document.getElementById('basis').style.display='none';"
    onblur="document.getElementById('feet').style.display='none';document.getElementById('basis').style.display='block';"
    value="no" id="feet_no" checked="checked">

    <input type="radio" name="feet" onChange="calculatie()"
    onfocus="document.getElementById('feet').style.display='block';document.getElementById('basis').style.display='none';"
    onblur="document.getElementById('feet').style.display='none';document.getElementById('basis').style.display='block';"
    value="yes" id="feet_yes" > Yes

    wheel
    No <input type="radio" name="wheel" onChange="calculatie()"
    onfocus="document.getElementById('wheel').style.display='block';document.getElementById('basis').style.display='none';"
    onblur="document.getElementById('wheel').style.display='none';document.getElementById('basis').style.display='block';"
    value="no" id="wheel_no" checked="checked">

    <input type="radio" name="wheel" onChange="calculatie()"
    onfocus="document.getElementById('wheel').style.display='block';document.getElementById('basis').style.display='none';"
    onblur="document.getElementById('wheel').style.display='none';document.getElementById('basis').style.display='block';"
    value="yes" id="wheel_yes" > Yes

http://torza.nl/leon2.php

Body:
Try the below script and it should work. Made a slight change in it,

<script type="text/javascript">
function calculatie()
{
// very much code

// Totaalprijs met of zonder pootjes
if(document.getElementById('feet_no').checked)
{
    document.getElementsByName('kosten_inkoop')[0].value = (document.getElementsByName('kosten_inkoop')[0].value);
}
else if(document.getElementById('feet_yes').checked && document.getElementById('wheel_yes').checked)
{
    document.getElementsByName('kosten_inkoop')[0].value = ((document.getElementsByName('kosten_inkoop')[0].value * 1) + (document.getElementsByName('kosten_pootjes')[0].value * 1)).toFixed( 2 );
    document.getElementById('wheel_no').checked = true;
}

// Totaalprijs met of zonder wieltjes
if(document.getElementById('wheel_no').checked)
{
    document.getElementsByName('kosten_inkoop')[0].value = (document.getElementsByName('kosten_inkoop')[0].value);
}
else if(document.getElementById('wheel_yes').checked)
{
    document.getElementsByName('kosten_inkoop')[0].value = ((document.getElementsByName('kosten_inkoop')[0].value * 1) + (document.getElementsByName('kosten_wieltjes')[0].value * 1)).toFixed( 2 );
    document.getElementById('feet_no').checked = true;
}
}
</script>

The order of the if conditions is creating the problem. The radio button is switched when "Wheel Yes" is clicked, but due to the if condition its reverting back.


问:
Laravel orderBy using 2 tables?
Please don't tell me to put the orderBy inside the function, because that doesn't work. kill_count and death_count are columns of the roleplay relationship

here is my full code:

```<code>$topCredits = Player::whereHas("roleplay", function($q) {
            $q->where('government_id', '<', '1');
        })->orderBy('credits', 'DESC')->limit(10)->get();

        $topKills = Player::whereHas("roleplay", function($q) {
            $q->where('government_id', '<', '1')->orderBy('kill_count', 'DESC');
        })->limit(10)->get();

        $topDeaths = Player::whereHas("roleplay", function($q) {
            $q->where('government_id', '<', '1')->orderBy('death_count', 'DESC');
        })->limit(10)->get();
</code>```

Now, the first $topCredits works perfectly, but the bottom 2 don't. They work very well except for the fact it doesn't order by the death_count and kill_count, can anyone help with this? The roleplay is a relationship of hasOne on both sides.

答:
The orderBy in the whereHas would not have any effect on players. Since whereHas is a subquery of Payers.

```<code> $topKills = Player::whereHas("roleplay", function($q) {
      $q->where('government_id', '<', '1');
  })->leftJoin("roleplay","roleplay.player_id","=","players.id")
   ->select("players.*")
   ->orderBy('roleplay.kill_count', 'DESC')
   ->limit(10)
   ->get();
</code>```

Hope this helps

Title: Laravel orderBy using 2 tables?

Body:
Please don't tell me to put the orderBy inside the function, because that doesn't work. kill_count and death_count are columns of the roleplay relationship

here is my full code:

$topCredits = Player::whereHas("roleplay", function($q) {
            $q->where('government_id', '<', '1');
        })->orderBy('credits', 'DESC')->limit(10)->get();

        $topKills = Player::whereHas("roleplay", function($q) {
            $q->where('government_id', '<', '1')->orderBy('kill_count', 'DESC');
        })->limit(10)->get();

        $topDeaths = Player::whereHas("roleplay", function($q) {
            $q->where('government_id', '<', '1')->orderBy('death_count', 'DESC');
        })->limit(10)->get();

Now, the first $topCredits works perfectly, but the bottom 2 don't. They work very well except for the fact it doesn't order by the death_count and kill_count, can anyone help with this? The roleplay is a relationship of hasOne on both sides.

Body:
The orderBy in the whereHas would not have any effect on players. Since whereHas is a subquery of Payers.

 $topKills = Player::whereHas("roleplay", function($q) {
      $q->where('government_id', '<', '1');
  })->leftJoin("roleplay","roleplay.player_id","=","players.id")
   ->select("players.*")
   ->orderBy('roleplay.kill_count', 'DESC')
   ->limit(10)
   ->get();

Hope this helps


问:
No kernel for language json found - Hydrogen on atom
I have found some people complaining about the python kernel but that is not my issue. Here is a print screen of the error, where you can see that when I try to run an ipynb file it gives me an error with the json kernel.

The package is configure with default and I have the Python2 and Python3 kernels for Jupyter as you can see below.

```<code>:~ jupyter kernelspec list --json
{
"kernelspecs": {
"python2": {
  "spec": {
    "language": "python",
    "argv": [
      "/usr/local/opt/python/bin/python2.7",
      "-m",
      "ipykernel",
      "-f",
      "{connection_file}"
    ],
    "display_name": "Python 2",
    "env": {}
  },
  "resource_dir": "/usr/local/share/jupyter/kernels/python2"
},
"python3": {
  "spec": {
    "language": "python",
    "argv": [
      "/usr/local/opt/python3/bin/python3.5",
      "-m",
      "ipykernel",
      "-f",
      "{connection_file}"
    ],
    "display_name": "Python 3",
    "env": {}
  },
  "resource_dir": "/usr/local/share/jupyter/kernels/python3"
}
}
}
</code>```

Any ideas on how to fix this?

答: From your screenshot it looks like you're trying to open a .ipynb file in hydrogen. According to an issue at https://github.com/nteract/hydrogen/issues/153 Hydrogen does not support ipynb files, it only runs directly on python files. I found this confusing as well.</p>

Body:
I have found some people complaining about the python kernel but that is not my issue. Here is a print screen of the error, where you can see that when I try to run an ipynb file it gives me an error with the json kernel.

The package is configure with default and I have the Python2 and Python3 kernels for Jupyter as you can see below.

:~ jupyter kernelspec list --json
{
"kernelspecs": {
"python2": {
  "spec": {
    "language": "python",
    "argv": [
      "/usr/local/opt/python/bin/python2.7",
      "-m",
      "ipykernel",
      "-f",
      "{connection_file}"
    ],
    "display_name": "Python 2",
    "env": {}
  },
  "resource_dir": "/usr/local/share/jupyter/kernels/python2"
},
"python3": {
  "spec": {
    "language": "python",
    "argv": [
      "/usr/local/opt/python3/bin/python3.5",
      "-m",
      "ipykernel",
      "-f",
      "{connection_file}"
    ],
    "display_name": "Python 3",
    "env": {}
  },
  "resource_dir": "/usr/local/share/jupyter/kernels/python3"
}
}
}

Any ideas on how to fix this?


问:
ES6 Class Multiple inheritance
I've done most of my research on this on BabelJS and on MDN (which has no information at all), but please feel free to tell me if I have not been careful enough in looking around for more information about the ES6 Spec.

I'm wondering whether or not ES6 supports multiple inheritance in the same fashion as other duck-typed languages do. For instance, can I do something like:

```<code>class Example extends ClassOne, ClassTwo {
    constructor() {
    }
}
</code>```

to extend multiple classes on to the new class? If so, will the interpreter prefer methods/properties from ClassTwo over ClassOne?

答:
From the page es6-features.org/#ClassInheritanceFromExpressions, it is possible to write an aggregation function to allow multiple inheritance:

class Rectangle extends aggregation(Shape, Colored, ZCoord) {}

```<code>var aggregation = (baseClass, ...mixins) => {
    let base = class _Combined extends baseClass {
        constructor (...args) {
            super(...args)
            mixins.forEach((mixin) => {
                mixin.prototype.initializer.call(this)
            })
        }
    }
    let copyProps = (target, source) => {
        Object.getOwnPropertyNames(source)
            .concat(Object.getOwnPropertySymbols(source))
            .forEach((prop) => {
            if (prop.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/))
                return
            Object.defineProperty(target, prop, Object.getOwnPropertyDescriptor(source, prop))
        })
    }
    mixins.forEach((mixin) => {
        copyProps(base.prototype, mixin.prototype)
        copyProps(base, mixin)
    })
    return base
}
</code>```

But that is already provided in libraries like aggregation.

Title: ES6 Class Multiple inheritance

Body:
I've done most of my research on this on BabelJS and on MDN (which has no information at all), but please feel free to tell me if I have not been careful enough in looking around for more information about the ES6 Spec.

I'm wondering whether or not ES6 supports multiple inheritance in the same fashion as other duck-typed languages do. For instance, can I do something like:

class Example extends ClassOne, ClassTwo {
    constructor() {
    }
}

to extend multiple classes on to the new class? If so, will the interpreter prefer methods/properties from ClassTwo over ClassOne?

Body:
From the page es6-features.org/#ClassInheritanceFromExpressions, it is possible to write an aggregation function to allow multiple inheritance:

class Rectangle extends aggregation(Shape, Colored, ZCoord) {}

var aggregation = (baseClass, ...mixins) => {
    let base = class _Combined extends baseClass {
        constructor (...args) {
            super(...args)
            mixins.forEach((mixin) => {
                mixin.prototype.initializer.call(this)
            })
        }
    }
    let copyProps = (target, source) => {
        Object.getOwnPropertyNames(source)
            .concat(Object.getOwnPropertySymbols(source))
            .forEach((prop) => {
            if (prop.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/))
                return
            Object.defineProperty(target, prop, Object.getOwnPropertyDescriptor(source, prop))
        })
    }
    mixins.forEach((mixin) => {
        copyProps(base.prototype, mixin.prototype)
        copyProps(base, mixin)
    })
    return base
}

But that is already provided in libraries like aggregation.


问:
TableView binding and Object HAS-A relation
I have the following classes

```<code>Class Car{
  private StringProperty type;

  //+setters and getters
}

Class Person{
  private Car car;

  private StringProperty name;

  //+setters and getters
}
</code>```

And I have tableView TableView<Person>. In this tableView I have two columns - Person Name and Car Type.

This is how I build column for Person Name

```<code>TableColumn<Person,String> column=new TableColumn("Person Name");
column.setCellValueFactory(data->data.getValue().getName());
</code>```

You can see, there can be two changes with Car in class Person. First of all a person can get another car, and secondly car can change its type.

How can I build column Car Type and bind to "these two changes"

答:
The select* methods of the Bindings class are made for this:

```<code>carTypeColumn.setCellValueFactory(
    data -> Bindings.selectString(data.getValue(), "car", "type"));
</code>```

Note that your getters and setters should follow JavaFX conventions, like all JavaFX classes do:

```<code>class Car {
    private final StringProperty type = new SimpleStringProperty();

    public StringProperty typeProperty() { return type; }
    public String getType() { return type.get(); }
    public void setType(String newType) { type.set(newType); }
}

class Person {
    private final ObjectProperty<Car> car = new SimpleObjectProperty<>();

    private final StringProperty name = new SimpleStringProperty();

    public ObjectProperty<Car> carProperty() { return car; }
    public Car getCar() { return car.get(); }
    public void setCar(Car newCar) { car.set(newCar); }

    public StringProperty nameProperty() { return name; }
    public String getName() { return name.get(); }
    public void setName(String newName) { name.set(newName); }
}
</code>```

Body:
I have the following classes

Class Car{
  private StringProperty type;

  //+setters and getters
}

Class Person{
  private Car car;

  private StringProperty name;

  //+setters and getters
}

And I have tableView TableView<Person>. In this tableView I have two columns - Person Name and Car Type.

This is how I build column for Person Name

TableColumn<Person,String> column=new TableColumn("Person Name");
column.setCellValueFactory(data->data.getValue().getName());

You can see, there can be two changes with Car in class Person. First of all a person can get another car, and secondly car can change its type.

How can I build column Car Type and bind to "these two changes"

Body:
The select* methods of the Bindings class are made for this:

carTypeColumn.setCellValueFactory(
    data -> Bindings.selectString(data.getValue(), "car", "type"));

Note that your getters and setters should follow JavaFX conventions, like all JavaFX classes do:

class Car {
    private final StringProperty type = new SimpleStringProperty();

    public StringProperty typeProperty() { return type; }
    public String getType() { return type.get(); }
    public void setType(String newType) { type.set(newType); }
}

class Person {
    private final ObjectProperty<Car> car = new SimpleObjectProperty<>();

    private final StringProperty name = new SimpleStringProperty();

    public ObjectProperty<Car> carProperty() { return car; }
    public Car getCar() { return car.get(); }
    public void setCar(Car newCar) { car.set(newCar); }

    public StringProperty nameProperty() { return name; }
    public String getName() { return name.get(); }
    public void setName(String newName) { name.set(newName); }
}


问:
jQuery: if string matches one of these href's
I have this var in my code:

```<code>var href = $(this).attr('href'),
str = href.split('/').slice(-2,-1)[0];
</code>```

How do I check if 'images', 'images-2' or 'images-3'
matches the 'href' string, then do something..

答:
```<code>if href.match(/images(-[23])?/){
    doStuf();
}
</code>```

should do the trick.

ContentLicense: CC BY-SA 2.5

Body:
I have this var in my code:

var href = $(this).attr('href'),
str = href.split('/').slice(-2,-1)[0];

How do I check if 'images', 'images-2' or 'images-3'
matches the 'href' string, then do something..

Body:
if href.match(/images(-[23])?/){
    doStuf();
}

should do the trick.


问:
inline assembler in gives c2400 in vs 2015
try to implement a basic operating system but this asm stuff is messing with my head i am using vs2015

the code that gives error

```<code>inline cpu_flags DisableInterrupts()

{
cpu_flags fl;

_asm volatile ("pushfl; popl %0; cli" : "=g" (fl));

return fl;
}
</code>```

it gives error like this

Error    C2400   inline assembler syntax error in 'opcode'; found 'data type'

after removing volatile also no luck

```<code>inline cpu_flags DisableInterrupts()
 {

 cpu_flags fl;

_asm ("pushfl; popl %0; cli" : "=g" (fl));

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

it gives

Error   C2400   inline assembler syntax error in 'opcode'; found '('

thank you

答:
That's AT&T syntax used by gcc.

Visual Studio uses Intel syntax for its inline assembler. However, there is also a built in _disable() function that doesn't require any assembler code.

Also not the remarks about the limited use of this function:

This function is only available in kernel mode. If used in user mode, a Privileged Instruction exception is thrown at run time.

Body:
try to implement a basic operating system but this asm stuff is messing with my head i am using vs2015

the code that gives error

inline cpu_flags DisableInterrupts()

{
cpu_flags fl;

_asm volatile ("pushfl; popl %0; cli" : "=g" (fl));

return fl;
}

it gives error like this

Error    C2400   inline assembler syntax error in 'opcode'; found 'data type'

after removing volatile also no luck

inline cpu_flags DisableInterrupts()
 {

 cpu_flags fl;

_asm ("pushfl; popl %0; cli" : "=g" (fl));

return fl;`
}

it gives

Error   C2400   inline assembler syntax error in 'opcode'; found '('

thank you


问:
show progressbar while sending email using jquery ajax
i need to send a new password to user's email. to do that, i made a modal on my login page that will be appear when i click "forget password" button.

here is my modal code :

```<code><div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content col-md-8 col-md-offset-2">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h4 class="modal-title" id="myModalLabel"></h4>
          </div>
          <div class="modal-body">
            <div id="alert_lupa">

            </div>
            <form action="javascript:lupa();" id="formLupa" name="formLupa" method="post" autocomplete="off">
              <div class="form-group">
                <input class="form-control" placeholder="Email" name="email" type="text">
                <span class="help-block"></span>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary btn-sm" id="btnKirim" onclick="lupa()">Kirim</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
</code>```

then if i click "kirim" button, it will run "lupa()" function, and here is the code :

```<code>function lupa(){
    $("#alert_lupa").html('<div class="progress progress-striped active">\
      <div class="progress-bar progress-bar-success" role="progressbar" style="width: 100%">\
      </div>\
    </div>').fadeIn();
    $('#btnKirim').text('Mengirim..');
    $('#btnKirim').attr('disabled',true);
    $.ajax({
      url:"<?=site_url('login/validasiLupa')?>",
      type: "POST",
      data: $('#formLupa').serialize(),
      dataType:"JSON",
      success:function(data){
        $("#alert_lupa").html(null);
        if (data.valid===false) {
          for (var i = data.namafield.length; i >= 0; i--)
              {
                $('[name="'+data.namafield[i]+'"]').focus();
                $('[name="'+data.namafield[i]+'"]').parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
                $('[name="'+data.namafield[i]+'"]').next().text(data.texterror[i]);
              }
        }else if(data.valid===true){

          if (data.kirim===true) {
            var div = "#alert_lupa";
            var message = "Password Baru Telah Dikirim ke Alamat Email Anda";
            emailSent(div,message);
            $('#email').val(null);
          }else if (data.kirim===false) {
            var div = "#alert_lupa";
            var message = "Alamat Email Tidak Ditemukan";
            dataAlert(div,message);
            $('#email').val(null);
            $('#email').focus();
          }
        }
        $('#btnKirim').text('Kirim');
        $('#btnKirim').attr('disabled',false);
      },
      error: function (jqXHR, textStatus, errorThrown)
      {
          alert('Error adding / update data');
      }
    })
  }
</code>```

as you can see, "lupa" function is accessing "validasiLupa" function in my controller, which the code is :

```<code>public function validasiLupa(){
$this->form_validation->set_message($this->uangmuka->message());
$this->form_validation->set_error_delimiters('', '');

$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|custom_email|max_length[100]');

$data = array();
$data['valid']=TRUE;

if ($this->form_validation->run() == FALSE)
{
  $data['namafield']=array();
  $data['texterror']=array();
  $data['valid']=FALSE;
  if (form_error('email')) {
    $data['namafield'][]='email';
    $data['texterror'][]=form_error('email');
  }
}

//verifikasiLupa
$mail = $this->input->post('email');
$pwd = $this->uangmuka->generatePwd();

    $anggota = $this->crud_m->selectX("anggota","email_anggota = '$mail'")->row();
    if (isset($anggota)) {
  $pwdbaru = array("password_anggota"=>md5($pwd));
        $this->crud_m->update_data('anggota',$pwdbaru,"nik_anggota=$anggota->nik_anggota");

  $this->sendEmail($mail,$pwd);

  $data['kirim']=TRUE;
  // $data['load']=FALSE;
    }else {
      $data['kirim']=FALSE;
  // $data['load']=FALSE;
    }
echo json_encode($data);
</code>```

}

so far, i find a way to showed the progressbar, but it width is static. is there any ways to make the progressbar width increasing dynamically?

答: I don't know why you appending progress bar instead of doing writing that progress bar DIV in html page itself and handle it from your function by using show or hide methods. So finally you won't get any issues with templates.

Body:
i need to send a new password to user's email. to do that, i made a modal on my login page that will be appear when i click "forget password" button.

here is my modal code :

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

            <form action="javascript:lupa();" id="formLupa" name="formLupa" method="post" autocomplete="off">

                <input class="form-control" placeholder="Email" name="email" type="text">

            </form>

            <button type="button" class="btn btn-primary btn-sm" id="btnKirim" onclick="lupa()">Kirim</button>

then if i click "kirim" button, it will run "lupa()" function, and here is the code :

function lupa(){
    $("#alert_lupa").html('
\

\

\

').fadeIn();
    $('#btnKirim').text('Mengirim..');
    $('#btnKirim').attr('disabled',true);
    $.ajax({
      url:"<?=site_url('login/validasiLupa')?>",
      type: "POST",
      data: $('#formLupa').serialize(),
      dataType:"JSON",
      success:function(data){
        $("#alert_lupa").html(null);
        if (data.valid===false) {
          for (var i = data.namafield.length; i >= 0; i--)
              {
                $('[name="'+data.namafield[i]+'"]').focus();
                $('[name="'+data.namafield[i]+'"]').parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
                $('[name="'+data.namafield[i]+'"]').next().text(data.texterror[i]);
              }
        }else if(data.valid===true){

          if (data.kirim===true) {
            var div = "#alert_lupa";
            var message = "Password Baru Telah Dikirim ke Alamat Email Anda";
            emailSent(div,message);
            $('#email').val(null);
          }else if (data.kirim===false) {
            var div = "#alert_lupa";
            var message = "Alamat Email Tidak Ditemukan";
            dataAlert(div,message);
            $('#email').val(null);
            $('#email').focus();
          }
        }
        $('#btnKirim').text('Kirim');
        $('#btnKirim').attr('disabled',false);
      },
      error: function (jqXHR, textStatus, errorThrown)
      {
          alert('Error adding / update data');
      }
    })
  }

as you can see, "lupa" function is accessing "validasiLupa" function in my controller, which the code is :

public function validasiLupa(){
$this->form_validation->set_message($this->uangmuka->message());
$this->form_validation->set_error_delimiters('', '');

$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|custom_email|max_length[100]');

$data = array();
$data['valid']=TRUE;

if ($this->form_validation->run() == FALSE)
{
  $data['namafield']=array();
  $data['texterror']=array();
  $data['valid']=FALSE;
  if (form_error('email')) {
    $data['namafield'][]='email';
    $data['texterror'][]=form_error('email');
  }
}

//verifikasiLupa
$mail = $this->input->post('email');
$pwd = $this->uangmuka->generatePwd();

    $anggota = $this->crud_m->selectX("anggota","email_anggota = '$mail'")->row();
    if (isset($anggota)) {
  $pwdbaru = array("password_anggota"=>md5($pwd));
        $this->crud_m->update_data('anggota',$pwdbaru,"nik_anggota=$anggota->nik_anggota");

  $this->sendEmail($mail,$pwd);

  $data['kirim']=TRUE;
  // $data['load']=FALSE;
    }else {
      $data['kirim']=FALSE;
  // $data['load']=FALSE;
    }
echo json_encode($data);

}

so far, i find a way to showed the progressbar, but it width is static. is there any ways to make the progressbar width increasing dynamically?


问:
Javascript, Canvas, and Resizing
I'm looking to make a finished canvas project resizeable.  Some websites I've read recommend using CSS to restyle, however I've also seen people say never to do that because it blurs text by stretching things.  But if you simply tell the canvas to resize in javascript won't filltexts such as in the example below need to be redone?

```<code>var canvas = document.getElementById("example");
var ctx = canvas.getContext('2d');
var cornerRadius = 10;

function drawMe() {
  ctx.fillStyle = "red";
  ctx.strokeStyle = "red";
  ctx.lineJoin = "round";
  ctx.lineWidth = cornerRadius;
  ctx.strokeRect(5+(cornerRadius/2), 23+(cornerRadius/2), 155-cornerRadius,     406-cornerRadius);
  ctx.fillRect(5+(cornerRadius/2), 23+(cornerRadius/2), 155-cornerRadius,     406-cornerRadius);
  ctx.font = '16pt Arial';
 ctx.fillStyle = 'white';
 ctx.textAlign="start";
 ctx.fillText('Text', 8, 70);
 ctx.fillText('Text', 8, 128);
}

function redraw() {
  ctx.strokeStyle = 'blue';
  ctx.lineWidth = '5';
  ctx.strokeRect(0, 0, window.innerWidth, window.innerHeight);
  drawMe();
}
window.onload = function () {
  redraw();
};
</code>```

Example of project.

Canvas is set in html to 1280 x 800.
edited to include https://jsfiddle.net/o1rkg1tf/

答:
In order to get a canvas element resizable, you need to handle the window resize event.
After that you need to set the canvas width and height to the window size values.
And finally, in your canvas element use relative values, percentages of the main width and height values.

Here's an update of your example:
https://jsfiddle.net/abelflopes/o1rkg1tf/5/

```<code>var wH = window.innerHeight;
var wW = window.innerWidth;
...
function drawMe() {
    canvas.height = wH;
    canvas.width = wW;
    ...
}
window.addEventListener("resize", function () {
    wH = window.innerHeight;
    wW = window.innerWidth;
    drawMe();
    redraw();
});
</code>```

I hope i was clear enough to help you.

Title: Javascript, Canvas, and Resizing

Body:
I'm looking to make a finished canvas project resizeable.  Some websites I've read recommend using CSS to restyle, however I've also seen people say never to do that because it blurs text by stretching things.  But if you simply tell the canvas to resize in javascript won't filltexts such as in the example below need to be redone?

var canvas = document.getElementById("example");
var ctx = canvas.getContext('2d');
var cornerRadius = 10;

function drawMe() {
  ctx.fillStyle = "red";
  ctx.strokeStyle = "red";
  ctx.lineJoin = "round";
  ctx.lineWidth = cornerRadius;
  ctx.strokeRect(5+(cornerRadius/2), 23+(cornerRadius/2), 155-cornerRadius,     406-cornerRadius);
  ctx.fillRect(5+(cornerRadius/2), 23+(cornerRadius/2), 155-cornerRadius,     406-cornerRadius);
  ctx.font = '16pt Arial';
 ctx.fillStyle = 'white';
 ctx.textAlign="start";
 ctx.fillText('Text', 8, 70);
 ctx.fillText('Text', 8, 128);
}

function redraw() {
  ctx.strokeStyle = 'blue';
  ctx.lineWidth = '5';
  ctx.strokeRect(0, 0, window.innerWidth, window.innerHeight);
  drawMe();
}
window.onload = function () {
  redraw();
};

Example of project.

Canvas is set in html to 1280 x 800.
edited to include https://jsfiddle.net/o1rkg1tf/

Body:
In order to get a canvas element resizable, you need to handle the window resize event.
After that you need to set the canvas width and height to the window size values.
And finally, in your canvas element use relative values, percentages of the main width and height values.

Here's an update of your example:
https://jsfiddle.net/abelflopes/o1rkg1tf/5/

var wH = window.innerHeight;
var wW = window.innerWidth;
...
function drawMe() {
    canvas.height = wH;
    canvas.width = wW;
    ...
}
window.addEventListener("resize", function () {
    wH = window.innerHeight;
    wW = window.innerWidth;
    drawMe();
    redraw();
});

I hope i was clear enough to help you.


答:
This use javascript

```<code><script>
    window.onload=function(){
        var elem = document.getElementById('chart');
        elem.style.width = 70 + "%";

    }
    </script>
</code>```

add a id on your div chart with id="chart" and it will works
see a basic example below:

<!DOCTYPE html>

          <title>Bootstrap Example</title>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Basic Progress Bar

              70% Complete

        ```

Title: show progressbar while sending email using jquery ajax

Body:
This use javascript

<script>
    window.onload=function(){
        var elem = document.getElementById('chart');
        elem.style.width = 70 + "%";

    }
    </script>

add a id on your div chart with id="chart" and it will works
see a basic example below:

<!DOCTYPE html>
        <html lang="en">
        <head>
          <title>Bootstrap Example</title>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
          <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        </head>
        <body>
        <script>
            window.onload=function(){
                var elem = document.getElementById('chart');
                elem.style.width = 70 + "%";

            }
            </script>
        <div class="container">
          <h2>Basic Progress Bar</h2>
          <div class="progress">
            <div class="progress-bar" role="progressbar" id="chart" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100">
              <span class="sr-only">70% Complete</span>
            </div>
          </div>
        </div>

        </body>
        </html>


问:
Android Studio: TimerTask
I am creating a simple click game that spawns enemies on screen and when the user clicks them, they get points and the enemies are destroyed. I do this with making imageboxs visible and invisible when the user clicks on them. They run on a timer and have a constant loop of spawning.

Currently I want to implement a way the user will start to loose health. So I would like to check if the enemy imagebox is visible, if it is, the player will slowly loose health.

I am confused with creating a timer task that can refresh the UI for this job. I want to be able to check the UI constantly if some images are visible or not. I have made a start on this from my own research but the game crashes when loaded if this is implemented.

Timer to refresh UI:

```<code>private Timer mTimer1;
private TimerTask mTt1;
private Handler mTimerHandler = new Handler();

  public void onStart() {
    mTimer1 = new Timer();
    mTt1 = new TimerTask() {
        public void run() {
            mTimerHandler.post(new Runnable() {
                public void run() {
                    //TODO
                    final TextView health = (TextView) findViewById(R.id.Health);
                    health.setText("Health:  " + health2);

                    //Enemy ImageViews
                    final ImageView enemy1 = (ImageView) findViewById(R.id.enemy1);
                    final ImageView enemy2 = (ImageView) findViewById(R.id.enemy2);
                    final ImageView enemy3 = (ImageView) findViewById(R.id.enemy3);
                    final ImageView enemy4 = (ImageView) findViewById(R.id.enemy4);

                    //sets imageViews into array
                    final ImageView[] enemies = new ImageView[4];
                    enemies[0] = enemy1;
                    enemies[1] = enemy2;
                    enemies[2] = enemy3;
                    enemies[3] = enemy4;

                    boolean running = true;
                    while (running) {
                        if (enemy1.getVisibility() == View.VISIBLE) {
                            int damage = 1;
                            health2 = health2 - damage;
                            health.setText("Health:" + health2);
                        } else {
                            // Either gone or invisible
                        }
                        if (enemy2.getVisibility() == View.VISIBLE) {
                            int damage = 1;
                            health2 = health2 - damage;
                            health.setText("Health:" + health2);
                        } else {
                            // Either gone or invisible
                        }
                        if (enemy3.getVisibility() == View.VISIBLE) {
                            int damage = 1;
                            health2 = health2 - damage;
                            health.setText("Health:" + health2);
                        } else {
                            // Either gone or invisible
                        }
                        if (enemy4.getVisibility() == View.VISIBLE) {
                            int damage = 1;
                            health2 = health2 - damage;
                            health.setText("Health:" + health2);
                        } else {
                            // Either gone or invisible
                        }

                    }
                }
            });
        }

    };
    mTimer1.schedule(mTt1, 1, 5000);
}

}
</code>```

This is the timer task I have created. I would like some clarity to why this crashes my game and how to fix this issue. I have never used timer in this way before so if the problem is obvious that is why I have not noticed it.

I have a lot more code inside the onCreate method and can post if needed. Thank you for all the help and advice for this begineer.

Crash:

答:
Based on the error message you need to call super.onStart()
so you need to add that here:

public void onStart() {

super.onStart();

//your code

}

I assume you know, but just in case super is class you extend, the parent. if you override it's onStart function the normal onStart procedure isn't done, if you don't call the super function.

EDIT: as for your other question, i (as a beginner with java, so i'm not claiming this is the best way to go) would be thinking along the lines of doing something like:

First create a handler and make runnables for the enemies:

```<code>Handler handler = new Handler();
Runnable[] eRunnables = new Runnable[enemies.length-1];

for(int i = 0; i < eRunnables.length; i++){
   eRunnables[i] = new Runnable(){
        public void run(){
            if(enemies[i].getVisibility() == View.VISIBLE){
                health2--;
                health.setText("Health:" + health2);
                handler.postDelayed(eRunnables[i], 1000);
            }
        }
    };
}
</code>```

And then where you initially make the enemies visible (besides setting them to visible) do something like

handler.postDelayed(eRunnable[enemyNr], 1000);

ofcourse replace the 1000 with however many milliseconds you want.

Again i'm not saying this is the best way, just what i thought up.

Title: Android Studio: TimerTask

Body:
I am creating a simple click game that spawns enemies on screen and when the user clicks them, they get points and the enemies are destroyed. I do this with making imageboxs visible and invisible when the user clicks on them. They run on a timer and have a constant loop of spawning.

Currently I want to implement a way the user will start to loose health. So I would like to check if the enemy imagebox is visible, if it is, the player will slowly loose health.

I am confused with creating a timer task that can refresh the UI for this job. I want to be able to check the UI constantly if some images are visible or not. I have made a start on this from my own research but the game crashes when loaded if this is implemented.

Timer to refresh UI:

private Timer mTimer1;
private TimerTask mTt1;
private Handler mTimerHandler = new Handler();

  public void onStart() {
    mTimer1 = new Timer();
    mTt1 = new TimerTask() {
        public void run() {
            mTimerHandler.post(new Runnable() {
                public void run() {
                    //TODO
                    final TextView health = (TextView) findViewById(R.id.Health);
                    health.setText("Health:  " + health2);

                    //Enemy ImageViews
                    final ImageView enemy1 = (ImageView) findViewById(R.id.enemy1);
                    final ImageView enemy2 = (ImageView) findViewById(R.id.enemy2);
                    final ImageView enemy3 = (ImageView) findViewById(R.id.enemy3);
                    final ImageView enemy4 = (ImageView) findViewById(R.id.enemy4);

                    //sets imageViews into array
                    final ImageView[] enemies = new ImageView[4];
                    enemies[0] = enemy1;
                    enemies[1] = enemy2;
                    enemies[2] = enemy3;
                    enemies[3] = enemy4;

                    boolean running = true;
                    while (running) {
                        if (enemy1.getVisibility() == View.VISIBLE) {
                            int damage = 1;
                            health2 = health2 - damage;
                            health.setText("Health:" + health2);
                        } else {
                            // Either gone or invisible
                        }
                        if (enemy2.getVisibility() == View.VISIBLE) {
                            int damage = 1;
                            health2 = health2 - damage;
                            health.setText("Health:" + health2);
                        } else {
                            // Either gone or invisible
                        }
                        if (enemy3.getVisibility() == View.VISIBLE) {
                            int damage = 1;
                            health2 = health2 - damage;
                            health.setText("Health:" + health2);
                        } else {
                            // Either gone or invisible
                        }
                        if (enemy4.getVisibility() == View.VISIBLE) {
                            int damage = 1;
                            health2 = health2 - damage;
                            health.setText("Health:" + health2);
                        } else {
                            // Either gone or invisible
                        }

                    }
                }
            });
        }

    };
    mTimer1.schedule(mTt1, 1, 5000);
}

}

This is the timer task I have created. I would like some clarity to why this crashes my game and how to fix this issue. I have never used timer in this way before so if the problem is obvious that is why I have not noticed it.

I have a lot more code inside the onCreate method and can post if needed. Thank you for all the help and advice for this begineer.

Crash:

Body:
Based on the error message you need to call super.onStart()
so you need to add that here:

public void onStart() {

super.onStart();

//your code

}

I assume you know, but just in case super is class you extend, the parent. if you override it's onStart function the normal onStart procedure isn't done, if you don't call the super function.

EDIT: as for your other question, i (as a beginner with java, so i'm not claiming this is the best way to go) would be thinking along the lines of doing something like:

First create a handler and make runnables for the enemies:

Handler handler = new Handler();
Runnable[] eRunnables = new Runnable[enemies.length-1];

for(int i = 0; i < eRunnables.length; i++){
   eRunnables[i] = new Runnable(){
        public void run(){
            if(enemies[i].getVisibility() == View.VISIBLE){
                health2--;
                health.setText("Health:" + health2);
                handler.postDelayed(eRunnables[i], 1000);
            }
        }
    };
}

And then where you initially make the enemies visible (besides setting them to visible) do something like

handler.postDelayed(eRunnable[enemyNr], 1000);

ofcourse replace the 1000 with however many milliseconds you want.

Again i'm not saying this is the best way, just what i thought up.


问:
Textarea adjust size based on content (with form-control class) using Jquery
Hiii Everyone,

I want to resize my textarea based on content.For that I tried code like

```<code><div class="form-group">
    <label class="control-label col-sm-2" for="pwd">Sample Answer</label>
    <div class="col-sm-10">
     <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" onkeyup="textAreaAdjust(this)"></textarea>
      <br/>
    </div>
  </div>
</code>```

And using jquery

```<code> function textAreaAdjust(o) {
  o.style.height = "1px";
  o.style.height = (25+o.scrollHeight)+"px";
}
</code>```

And what is the issue I am facing is even for backspace,delete for any press textarea is expanding like verylong.It keeps working like textarea will increase for any key press.If I tried textarea without 'class="form-control"' its working fine.But the responsiveness is not well.Please anyone help me to get out of this issue.Thanks in advance.

答:
Use jquery-elastic plugin Link is dead

Check a fork of the project here Github Jquery-elastic

Use just need a line of code..

```<code>$('#answer_sample').elastic();
</code>```

See JSFiddle

/**
 * @name             Elastic+
 * @descripton       grow and shrink your textareas automatically
 *
 * @author           Casey W. Stark
 * @author-email     casey@thestarkeffect.com
 * @author-website   http://thestarkeffect.com
 *
 * @license           MIT License - http://www.opensource.org/licenses/mit-license.php
 *
 * the original by:
 * @author           Jan Jarfalk
 * @author-email     jan.jarfalk@unwrongest.com
 * @author-website   http://www.unwrongest.com
 */

(function($) {
  $.fn.elastic = function(options) {
    // We will create a div clone of the textarea
    // by copying these attributes from the textarea to the div.
    var mimics = [
      'paddingTop',
      'paddingRight',
      'paddingBottom',
      'paddingLeft',
      'fontSize',
      'lineHeight',
      'fontFamily',
      'width',
      'fontWeight',
      'textIndent'
    ];

    // support multiple elements
    if (this.length > 1) {
      this.each(function() {
        // textareas only
        if (this.type != 'textarea') return false;
        $this.elastic()
      });
      return this;
    }

    // cache the textarea jquery object
    var textarea = this;
    var twin = $('

').css({
      'position': 'absolute',
      'display': 'none',
      'word-wrap': 'break-word'
    });
    var lineHeight = parseInt(textarea.css('line-height'), 10) || parseInt(textarea.css('font-size'), 10);
    var minHeight = parseInt(textarea.css('height'), 10) || lineHeight * 2;
    var maxHeight = parseInt(textarea.css('max-height'), 10) || Number.MAX_VALUE;
    var goalHeight = 0;
    var i = 0;

    // Opera returns max-height of -1 if not set
    if (maxHeight < 0) {
      maxHeight = Number.MAX_VALUE;
    }

    // Append the twin to the DOM
    // We are going to meassure the height of this, not the textarea.
    twin.appendTo(this.parent());

    // Copy the essential styles (mimics) from the textarea to the twin
    var i = mimics.length;
    while (i--) {
      twin.css(mimics[i].toString(), textarea.css(mimics[i].toString()));
    }

    // Sets a given height and overflow state on the textarea
    function setHeightAndOverflow(height, overflow) {
      curratedHeight = Math.floor(parseInt(height, 10));
      if (textarea.height() != curratedHeight) {
        textarea.css({
          'height': curratedHeight + 'px',
          'overflow': overflow
        });
      }
    }

    // This function will update the height of the textarea if necessary
    this.resize = function(options) {
      // need to update the lineheight if not set
      if (!lineHeight) {
        lineHeight = parseInt(textarea.css('line-height'), 10);
      }

      // set width to get proper height (width could change)
      twin.width(textarea.width());

      // Get curated content from the textarea.
      var textareaContent = textarea.val().replace(/&/g, '&').replace(/  /g, ' ').replace(/<|>/g, '>').replace(/\n/g, '
');

      var twinContent = twin.html();

      if (textareaContent + ' ' != twinContent) {
        // Add an extra white space so new rows are added when you are at the end of a row.
        twin.html(textareaContent + ' ');

        // Change textarea height if twin plus the height of one line differs more than 3 pixel from textarea height
        if (Math.abs(twin.height() - textarea.height()) > 3) {
          var goalHeight = twin.height();
          if (goalHeight >= maxHeight) {
            setHeightAndOverflow(maxHeight, 'auto');
          } else if (goalHeight <= minHeight) {
            setHeightAndOverflow(minHeight, 'hidden');
          } else {
            setHeightAndOverflow(goalHeight, 'hidden');
          }
        }
      }

      return textarea;
    };

    // Hide scrollbars
    textarea.css({
      'overflow': 'hidden'
    });

    // Update textarea size on keyup
    textarea.keyup(function() {
      textarea.resize();
    });

    // And this line is to catch the browser paste event
    textarea.on('input paste', function(e) {
      setTimeout(textarea.resize, 250);
    });

    // Run resize once when elastic is initialized and return the textarea for chaining
    return this.resize();
  };
})(jQuery);

$('#answer_sample').elastic();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('http://getbootstrap.com/dist/css/bootstrap.css');</code>```

    <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit

 Duis autem vel eum iriure dolor in hendrerit in vulputate velit es
     </textarea>

```

Body:
Hiii Everyone,

I want to resize my textarea based on content.For that I tried code like

    Sample Answer

     <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" onkeyup="textAreaAdjust(this)"></textarea>

And using jquery

 function textAreaAdjust(o) {
  o.style.height = "1px";
  o.style.height = (25+o.scrollHeight)+"px";
}

And what is the issue I am facing is even for backspace,delete for any press textarea is expanding like verylong.It keeps working like textarea will increase for any key press.If I tried textarea without 'class="form-control"' its working fine.But the responsiveness is not well.Please anyone help me to get out of this issue.Thanks in advance.

Body:
Use jquery-elastic plugin Link is dead

Check a fork of the project here Github Jquery-elastic

Use just need a line of code..

$('#answer_sample').elastic();

See JSFiddle

/**
 * @name             Elastic+
 * @descripton       grow and shrink your textareas automatically
 *
 * @author           Casey W. Stark
 * @author-email     casey@thestarkeffect.com
 * @author-website   http://thestarkeffect.com
 *
 * @license           MIT License - http://www.opensource.org/licenses/mit-license.php
 *
 * the original by:
 * @author           Jan Jarfalk
 * @author-email     jan.jarfalk@unwrongest.com
 * @author-website   http://www.unwrongest.com
 */

(function($) {
  $.fn.elastic = function(options) {
    // We will create a div clone of the textarea
    // by copying these attributes from the textarea to the div.
    var mimics = [
      'paddingTop',
      'paddingRight',
      'paddingBottom',
      'paddingLeft',
      'fontSize',
      'lineHeight',
      'fontFamily',
      'width',
      'fontWeight',
      'textIndent'
    ];

    // support multiple elements
    if (this.length > 1) {
      this.each(function() {
        // textareas only
        if (this.type != 'textarea') return false;
        $this.elastic()
      });
      return this;
    }

    // cache the textarea jquery object
    var textarea = this;
    var twin = $('<div></div>').css({
      'position': 'absolute',
      'display': 'none',
      'word-wrap': 'break-word'
    });
    var lineHeight = parseInt(textarea.css('line-height'), 10) || parseInt(textarea.css('font-size'), 10);
    var minHeight = parseInt(textarea.css('height'), 10) || lineHeight * 2;
    var maxHeight = parseInt(textarea.css('max-height'), 10) || Number.MAX_VALUE;
    var goalHeight = 0;
    var i = 0;

    // Opera returns max-height of -1 if not set
    if (maxHeight < 0) {
      maxHeight = Number.MAX_VALUE;
    }

    // Append the twin to the DOM
    // We are going to meassure the height of this, not the textarea.
    twin.appendTo(this.parent());

    // Copy the essential styles (mimics) from the textarea to the twin
    var i = mimics.length;
    while (i--) {
      twin.css(mimics[i].toString(), textarea.css(mimics[i].toString()));
    }

    // Sets a given height and overflow state on the textarea
    function setHeightAndOverflow(height, overflow) {
      curratedHeight = Math.floor(parseInt(height, 10));
      if (textarea.height() != curratedHeight) {
        textarea.css({
          'height': curratedHeight + 'px',
          'overflow': overflow
        });
      }
    }

    // This function will update the height of the textarea if necessary
    this.resize = function(options) {
      // need to update the lineheight if not set
      if (!lineHeight) {
        lineHeight = parseInt(textarea.css('line-height'), 10);
      }

      // set width to get proper height (width could change)
      twin.width(textarea.width());

      // Get curated content from the textarea.
      var textareaContent = textarea.val().replace(/&/g, '&amp;').replace(/  /g, '&nbsp;').replace(/<|>/g, '&gt;').replace(/\n/g, '<br />');

      var twinContent = twin.html();

      if (textareaContent + '&nbsp;' != twinContent) {
        // Add an extra white space so new rows are added when you are at the end of a row.
        twin.html(textareaContent + '&nbsp;');

        // Change textarea height if twin plus the height of one line differs more than 3 pixel from textarea height
        if (Math.abs(twin.height() - textarea.height()) > 3) {
          var goalHeight = twin.height();
          if (goalHeight >= maxHeight) {
            setHeightAndOverflow(maxHeight, 'auto');
          } else if (goalHeight <= minHeight) {
            setHeightAndOverflow(minHeight, 'hidden');
          } else {
            setHeightAndOverflow(goalHeight, 'hidden');
          }
        }
      }

      return textarea;
    };

    // Hide scrollbars
    textarea.css({
      'overflow': 'hidden'
    });

    // Update textarea size on keyup
    textarea.keyup(function() {
      textarea.resize();
    });

    // And this line is to catch the browser paste event
    textarea.on('input paste', function(e) {
      setTimeout(textarea.resize, 250);
    });

    // Run resize once when elastic is initialized and return the textarea for chaining
    return this.resize();
  };
})(jQuery);

$('#answer_sample').elastic();

@import url('http://getbootstrap.com/dist/css/bootstrap.css');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <div class="col-sm-10">
    <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit

 Duis autem vel eum iriure dolor in hendrerit in vulputate velit es
     </textarea>
    <br/>
  </div>
</div>


问:
word_tokenize in nltk not taking a list of string as argument
```<code>from nltk.tokenize import word_tokenize

music_comments = [['So cant you just run the bot outside of the US? ', ''], ["Just because it's illegal doesn't mean it will stop. I hope it actually gets enforced. ", ''], ['Can they do something about all the fucking bots on Tinder next?   \n\nEdit: Holy crap my inbox just blew up ', '']]

print(word_tokenize(music_comments[1]))
</code>```

I found this other question which says to pass a list of strings to word_tokenize, but in my case after running the above I get the following output:

```<code>Traceback (most recent call last):
  File "testing.py", line 5, in <module>
    print(word_tokenize(music_comments[1]))
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\__init__.py", line 109, in word_tokenize
    return [token for sent in sent_tokenize(text, language)
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\__init__.py", line 94, in sent_tokenize
    return tokenizer.tokenize(text)
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1237, in tokenize
    return list(self.sentences_from_text(text, realign_boundaries))
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1285, in sentences_from_text
    return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in span_tokenize
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in <listcomp>
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1316, in _realign_boundaries
    for sl1, sl2 in _pair_iter(slices):
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 310, in _pair_iter
    prev = next(it)
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1289, in _slices_from_text
    for match in self._lang_vars.period_context_re().finditer(text):
TypeError: expected string or bytes-like object
</code>```

What is the problem? What am I missing?

答:
You are feeding a list with two items into tokenize():

```<code>["Just because it's illegal doesn't mean it will stop. I hope it actually gets enforced. ", '']
</code>```

i.e the sentence and an empty string.

Changing your code to this should do the trick:

```<code>print(word_tokenize(music_comments[1][0]))
</code>```

Body:
from nltk.tokenize import word_tokenize

music_comments = [['So cant you just run the bot outside of the US? ', ''], ["Just because it's illegal doesn't mean it will stop. I hope it actually gets enforced. ", ''], ['Can they do something about all the fucking bots on Tinder next?   \n\nEdit: Holy crap my inbox just blew up ', '']]

print(word_tokenize(music_comments[1]))

I found this other question which says to pass a list of strings to word_tokenize, but in my case after running the above I get the following output:

Traceback (most recent call last):
  File "testing.py", line 5, in <module>
    print(word_tokenize(music_comments[1]))
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\__init__.py", line 109, in word_tokenize
    return [token for sent in sent_tokenize(text, language)
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\__init__.py", line 94, in sent_tokenize
    return tokenizer.tokenize(text)
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1237, in tokenize
    return list(self.sentences_from_text(text, realign_boundaries))
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1285, in sentences_from_text
    return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in span_tokenize
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in <listcomp>
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1316, in _realign_boundaries
    for sl1, sl2 in _pair_iter(slices):
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 310, in _pair_iter
    prev = next(it)
  File "C:\Users\Shraddheya Shendre\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1289, in _slices_from_text
    for match in self._lang_vars.period_context_re().finditer(text):
TypeError: expected string or bytes-like object

What is the problem? What am I missing?

Body:
You are feeding a list with two items into tokenize():

["Just because it's illegal doesn't mean it will stop. I hope it actually gets enforced. ", '']

i.e the sentence and an empty string.

Changing your code to this should do the trick:

print(word_tokenize(music_comments[1][0]))


问:
How to dynamically build a JSON object?
I am new to Python and I am playing with JSON data. I would like to dynamically build a JSON object by adding some key-value to an existing JSON object.

I tried the following but I get TypeError: 'str' object does not support item assignment:

```<code>import json

json_data = json.dumps({})
json_data["key"] = "value"

print 'JSON: ', json_data
</code>```

答:
You can create the Python dictionary and serialize it to JSON in one line and it's not even ugly.</p>

```<code>my_json_string = json.dumps({'key1': val1, 'key2': val2})
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to dynamically build a JSON object?

Body:
I am new to Python and I am playing with JSON data. I would like to dynamically build a JSON object by adding some key-value to an existing JSON object.

I tried the following but I get TypeError: 'str' object does not support item assignment:

import json

json_data = json.dumps({})
json_data["key"] = "value"

print 'JSON: ', json_data

Body:
You can create the Python dictionary and serialize it to JSON in one line and it's not even ugly.

my_json_string = json.dumps({'key1': val1, 'key2': val2})


问:
How can I use a parameter that I get with scanf in another function?
```<code>#include <-stdio.h>
float q, w, e, v1, v2;
int h, j;

int eqn(float q, float w, float e);
float val(int x);

int main (){

    eqn(q,w,e);
    scanf("%d%d",&h,&j);

return 0;
}

int eqn(float q, float w, float e) {
    scanf("%f %f %f", &q, &w, &e);
    printf("Entered equation: %.2fx^2 + %.2fx + %.2f\n", q, w, e);
    v1=val(h);
    v2=val(j);
    printf("values %f %f", value1, value2);
}

float val(int x){
    float value = q*x*x+w*x+e;
    return value;
}
</code>```

So, I want to get h and j values from the user and use them in eqn function in order to get the values. I am also requesting the q, w, e values from the user.
How can I get both the coefficients of the equation and the points that I'd like to calculate the value on?

答:
Refrain from using global variables, as sooner or later your code gets much to messy, when doing so.

Just put the all in correct order and pass what is necessary:

```<code>#include <stdio.h>

int eqn(int h, int j);
float val(float q, float w, float e, int x);

int main(void)
{
  int h, j;

  scanf("%d%d", &h, &j);
  eqn(h, j);

  return 0;
}

int eqn(int h, int j)
{
  float v1, v2;
  float q, w, e;

  scanf("%f %f %f", &q, &w, &e);

  printf("Entered equation: %.2fx^2 + %.2fx + %.2f\n", q, w, e);

  v1 = val(q, w, e, h);
  v2 = val(q, w, e, j);

  printf("values %f %f\n", v1, v2);
}

float val(float q, float w, float e, int x)
{
  float value = q*x*x + w*x + e;
  return value;
}
</code>```

If you want to call val() from main, switch to passing addresses to allow the caller to see what the callee assigned:

```<code>#include <stdio.h>

int eqn(float * pq, float * pw, float * pe);
float val(float q, float w, float e, int x);

int main(void)
{
  float q, w, e;
  int h, j;
  float v1, v2;

  eqn(&q, &w, &e);

  scanf("%d%d", &h, &j);

  v1 = val(q, w, e, h);
  v2 = val(q, w, e, j);

  printf("values %f %f\n", v1, v2);

  return 0;
}

int eqn(float * pq, float * pw, float * pe)
{
  scanf("%f %f %f", pq, pw, pe);

  printf("Entered equation: %.2fx^2 + %.2fx + %.2f\n", *pq, *pw, *pe);
}

float val(float q, float w, float e, int x)
{
  float value = q*x*x + w*x + e;
  return value;
}
</code>```

To define the scope of your variables even tighter change main() to look like this:

```<code>int main(void)
{
  float q, w, e;
  eqn(&q, &w, &e);

  {
    int h, j;
    scanf("%d%d", &h, &j);

    {
      float v1 = val(q, w, e, h);
      float v2 = val(q, w, e, j);

      printf("values %f %f\n", v1, v2);
    }
  }

  return 0;
}
</code>```

Body:
#include <-stdio.h>
float q, w, e, v1, v2;
int h, j;

int eqn(float q, float w, float e);
float val(int x);

int main (){

    eqn(q,w,e);
    scanf("%d%d",&h,&j);

return 0;
}

int eqn(float q, float w, float e) {
    scanf("%f %f %f", &q, &w, &e);
    printf("Entered equation: %.2fx^2 + %.2fx + %.2f\n", q, w, e);
    v1=val(h);
    v2=val(j);
    printf("values %f %f", value1, value2);
}

float val(int x){
    float value = q*x*x+w*x+e;
    return value;
}

So, I want to get h and j values from the user and use them in eqn function in order to get the values. I am also requesting the q, w, e values from the user.
How can I get both the coefficients of the equation and the points that I'd like to calculate the value on?

Body:
Refrain from using global variables, as sooner or later your code gets much to messy, when doing so.

Just put the all in correct order and pass what is necessary:

#include <stdio.h>

int eqn(int h, int j);
float val(float q, float w, float e, int x);

int main(void)
{
  int h, j;

  scanf("%d%d", &h, &j);
  eqn(h, j);

  return 0;
}

int eqn(int h, int j)
{
  float v1, v2;
  float q, w, e;

  scanf("%f %f %f", &q, &w, &e);

  printf("Entered equation: %.2fx^2 + %.2fx + %.2f\n", q, w, e);

  v1 = val(q, w, e, h);
  v2 = val(q, w, e, j);

  printf("values %f %f\n", v1, v2);
}

float val(float q, float w, float e, int x)
{
  float value = q*x*x + w*x + e;
  return value;
}

If you want to call val() from main, switch to passing addresses to allow the caller to see what the callee assigned:

#include <stdio.h>

int eqn(float * pq, float * pw, float * pe);
float val(float q, float w, float e, int x);

int main(void)
{
  float q, w, e;
  int h, j;
  float v1, v2;

  eqn(&q, &w, &e);

  scanf("%d%d", &h, &j);

  v1 = val(q, w, e, h);
  v2 = val(q, w, e, j);

  printf("values %f %f\n", v1, v2);

  return 0;
}

int eqn(float * pq, float * pw, float * pe)
{
  scanf("%f %f %f", pq, pw, pe);

  printf("Entered equation: %.2fx^2 + %.2fx + %.2f\n", *pq, *pw, *pe);
}

float val(float q, float w, float e, int x)
{
  float value = q*x*x + w*x + e;
  return value;
}

To define the scope of your variables even tighter change main() to look like this:

int main(void)
{
  float q, w, e;
  eqn(&q, &w, &e);

  {
    int h, j;
    scanf("%d%d", &h, &j);

    {
      float v1 = val(q, w, e, h);
      float v2 = val(q, w, e, j);

      printf("values %f %f\n", v1, v2);
    }
  }

  return 0;
}