问:
rails how to know when send_file done
As it takes some time to prepare the content of the data to be downloaded, I want to show a message "Preparing file to download" when the user submits the request

Then when the file is ready, I use send_file to send the data

Once it's done, I need to clear the message

Thanks a lot

答:
Here is what I would do.

1. Create a prepare_file action

First, I would create an action whose job would just be to create the file and rather than rendering HTML, it would render a JSON object with the name of the file that was created.

2. Use AJAX to call the prepare_file action

On the client, when the user clicks to download the file, you display the message, "Preparing download..." and just do an AJAX request to that action. The response you'll get back via AJAX is the name of the file created.

3. Redirect to the file download

Finally, you can hide the preparing download message and redirect the browser to the file download via JavaScript with the name of the file that was created. You would use send_file in this action.

I know that, in the question, you also wanted to be able to display to the user a message when the file is downloading and another message when it is finished. However, this isn't possible unless you write your own client-side download manager. The browser handles file downloads entirely and the user will see in the browser that the file is downloading and what the progress is. So, I understand where you're coming from, but you shouldn't feel like the user isn't being informed of what's happening.

At least with this solution, you're displaying a message to them when the file is being prepared and then once that message disappears, they'll get the download file dialog from the browser.

If you need help with actual code samples of how to do this, let me know.

Title: rails how to know when send_file done


来源: stackexchange

问:
Gradle sync failed after switching to 3.0 canary 5
After switching to Android Studio 3.0 canary 5 I can't build my gradle after some searching i found out that the error is caused due to outdated Guava library but i am not using Guava in my project.

Project Gradle

```<code>buildscript {
ext.kotlin_version = '1.1.3'
repositories {
    jcenter()
    maven { url 'https://maven.fabric.io/public' }
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-alpha5'
    classpath 'com.google.gms:google-services:3.1.0'
    classpath 'io.fabric.tools:gradle:1.22.2'
    classpath 'com.google.firebase:firebase-plugins:1.1.0'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
    maven { url 'https://maven.google.com' }
    maven { url 'https://maven.fabric.io/public' }
    mavenCentral()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}
</code>```

App Gradle

```<code>apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android'
apply plugin: 'com.google.firebase.firebase-perf'

android {
compileSdkVersion 26
buildToolsVersion '26.0.0'
defaultConfig {
    applicationId "com.nrs.nsnik.notes"
    minSdkVersion 19
    targetSdkVersion 26
    versionCode 15
    versionName "1.9.5"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
    transitive = true;
}
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
compile 'com.android.support:appcompat-v7:26.0.0-beta2'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:support-v4:26.0.0-beta2'
compile 'com.android.support:design:26.0.0-beta2'
compile 'com.android.support:cardview-v7:26.0.0-beta2'
compile 'com.android.support:palette-v7:26.0.0-beta2'
compile 'com.jakewharton:butterknife:8.6.0'
compile 'com.github.fafaldo:fab-toolbar:1.2.0'
compile 'com.google.firebase:firebase-perf:11.0.2'
compile 'com.google.firebase:firebase-ads:11.0.2'
compile 'com.google.android.gms:play-services-ads:11.0.2'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.1.0'
compile 'com.github.bumptech.glide:glide:4.0.0-RC1'
compile 'com.android.support:customtabs:26.0.0-beta2'
compile 'com.google.guava:guava:22.0-android'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

The Error :

```<code>Gradle sync failed: Cause: com.google.common.base.Preconditions.checkArgument(ZLjava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V
            Consult IDE log for more details (Help | Show Log) (18s 189ms)

Error:(1, 0) Unable to find method 'com.google.common.base.Preconditions.checkArgument(ZLjava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V'.
</code>```

Possible causes for this unexpected error include:

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

Re-download dependencies and sync project (requires network)

The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)

Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.

In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.

答:
For me work</p>

```<code>    classpath ('com.google.firebase:firebase-plugins:1.1.0') {
        exclude group: 'com.google.guava', module: 'guava-jdk5'
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
After switching to Android Studio 3.0 canary 5 I can't build my gradle after some searching i found out that the error is caused due to outdated Guava library but i am not using Guava in my project.

Project Gradle

buildscript {
ext.kotlin_version = '1.1.3'
repositories {
    jcenter()
    maven { url 'https://maven.fabric.io/public' }
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-alpha5'
    classpath 'com.google.gms:google-services:3.1.0'
    classpath 'io.fabric.tools:gradle:1.22.2'
    classpath 'com.google.firebase:firebase-plugins:1.1.0'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
    maven { url 'https://maven.google.com' }
    maven { url 'https://maven.fabric.io/public' }
    mavenCentral()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

App Gradle

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android'
apply plugin: 'com.google.firebase.firebase-perf'

android {
compileSdkVersion 26
buildToolsVersion '26.0.0'
defaultConfig {
    applicationId "com.nrs.nsnik.notes"
    minSdkVersion 19
    targetSdkVersion 26
    versionCode 15
    versionName "1.9.5"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
    transitive = true;
}
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
compile 'com.android.support:appcompat-v7:26.0.0-beta2'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:support-v4:26.0.0-beta2'
compile 'com.android.support:design:26.0.0-beta2'
compile 'com.android.support:cardview-v7:26.0.0-beta2'
compile 'com.android.support:palette-v7:26.0.0-beta2'
compile 'com.jakewharton:butterknife:8.6.0'
compile 'com.github.fafaldo:fab-toolbar:1.2.0'
compile 'com.google.firebase:firebase-perf:11.0.2'
compile 'com.google.firebase:firebase-ads:11.0.2'
compile 'com.google.android.gms:play-services-ads:11.0.2'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.1.0'
compile 'com.github.bumptech.glide:glide:4.0.0-RC1'
compile 'com.android.support:customtabs:26.0.0-beta2'
compile 'com.google.guava:guava:22.0-android'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

The Error :

Gradle sync failed: Cause: com.google.common.base.Preconditions.checkArgument(ZLjava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V
            Consult IDE log for more details (Help | Show Log) (18s 189ms)

Error:(1, 0) Unable to find method 'com.google.common.base.Preconditions.checkArgument(ZLjava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V'.

Possible causes for this unexpected error include:

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

Re-download dependencies and sync project (requires network)

The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)

Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.

In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.

Body:
For me work

    classpath ('com.google.firebase:firebase-plugins:1.1.0') {
        exclude group: 'com.google.guava', module: 'guava-jdk5'
    }


问:
Splitting an LSTM output using Lambda Functions in Keras
I am using Keras with tensorflow backend. I am using functional layers in Keras. What I want to achieve is that I have the following architecture at some layer.

Tensor of (20,200)----> LSTM----> Split into two Tensors of size (20,100) each

Then use those two tensors as two branches of a further network. (We can think of this as being the opposite of a Merge operation)

I am given to understand that the only way to achieve this is currently using the Lambda layer since there is no "Split" functionality in Keras.

However looking into the documentation for Lambda function, it seems the output_shape functionality is only relevant iff we are using Keras.

Can anyone offer any advice on how to achieve this ? This is the rough pseudo-code of what I want to achieve.

```<code>#Other code before this
lstm_1st_layer = LSTM(nos_hidden_neurons, return_sequences=True)(lstm_0th_layer)
#this layer outputs a tensor of size(20,200)
#Split it into two tensors of size (20,100) each (call them left and right)
left_lstm = LSTM(200, return_sequences=True)(left)
right_lstm = LSTM(200, return_sequences=True)(right)
#Other code after this
</code>```

答:
In your place I would simply use two LSTM layers with half the numbers of units.

Then you get the two outputs ready to go:

```<code>left = LSTM(half_nos_hidden_neurons,.....)(lstm_0th_layer)
right = LSTM(half_nos_hidden_neurons,.....)(lstm_0th_layer)
</code>```

The effect is the same.

Body:
I am using Keras with tensorflow backend. I am using functional layers in Keras. What I want to achieve is that I have the following architecture at some layer.

Tensor of (20,200)----> LSTM----> Split into two Tensors of size (20,100) each

Then use those two tensors as two branches of a further network. (We can think of this as being the opposite of a Merge operation)

I am given to understand that the only way to achieve this is currently using the Lambda layer since there is no "Split" functionality in Keras.

However looking into the documentation for Lambda function, it seems the output_shape functionality is only relevant iff we are using Keras.

Can anyone offer any advice on how to achieve this ? This is the rough pseudo-code of what I want to achieve.

#Other code before this
lstm_1st_layer = LSTM(nos_hidden_neurons, return_sequences=True)(lstm_0th_layer)
#this layer outputs a tensor of size(20,200)
#Split it into two tensors of size (20,100) each (call them left and right)
left_lstm = LSTM(200, return_sequences=True)(left)
right_lstm = LSTM(200, return_sequences=True)(right)
#Other code after this

Body:
In your place I would simply use two LSTM layers with half the numbers of units.

Then you get the two outputs ready to go:

left = LSTM(half_nos_hidden_neurons,.....)(lstm_0th_layer)
right = LSTM(half_nos_hidden_neurons,.....)(lstm_0th_layer)

The effect is the same.


问:
Can't bundle update due to multiple ruby versions
I try to update with bundle:

```<code>bundle update
Warning: the running version of Bundler (1.13.6) is older than the version that created the lockfile (1.13.7). We suggest you upgrade to the latest version of Bundler by running `gem install bundler`.
Ignoring ffi-1.9.10 because its extensions are not built.  Try: gem pristine ffi --version 1.9.10
Ignoring json-1.8.3 because its extensions are not built.  Try: gem pristine json --version 1.8.3
Fetching gem metadata from https://rubygems.org/...........
Fetching version metadata from https://rubygems.org/..
Fetching dependency metadata from https://rubygems.org/.
Resolving dependencies...
liquid-4.0.0 requires ruby version >= 2.1.0, which is incompatible with the
current version, ruby 2.0.0p648
</code>```

So I try

```<code>ruby --version
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-darwin16]
</code>```

It seems like bundle is using a different instance of ruby?

答:
What version is used when you run bundle env?

You could try reinstalling bundler with: gem install bundler

But first you can read a little more about it here

Body:
I try to update with bundle:

bundle update
Warning: the running version of Bundler (1.13.6) is older than the version that created the lockfile (1.13.7). We suggest you upgrade to the latest version of Bundler by running `gem install bundler`.
Ignoring ffi-1.9.10 because its extensions are not built.  Try: gem pristine ffi --version 1.9.10
Ignoring json-1.8.3 because its extensions are not built.  Try: gem pristine json --version 1.8.3
Fetching gem metadata from https://rubygems.org/...........
Fetching version metadata from https://rubygems.org/..
Fetching dependency metadata from https://rubygems.org/.
Resolving dependencies...
liquid-4.0.0 requires ruby version >= 2.1.0, which is incompatible with the
current version, ruby 2.0.0p648

So I try

ruby --version
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-darwin16]

It seems like bundle is using a different instance of ruby?


问:
convert string to datetime in powershell 2.0
I am trying to parse a file for only the most recent entries. Each entry in the log file starts with date in the format "m/d/yyyy h:mm:ss PM".

I write a script that accomplishes what I wanted but unfortunately this script runs on Powershell 5 but not Powershell 2

```<code>$regex = '\b([1-2][0-9]|[0-9])\/([1-3][0-9]|[0-9])\/(20[0-9][0-9]) ((1[0-2]|0?[1-9]):([0-5][0-9]):([0-5][0-9]) ([AaPp][Mm]))'

$lines = gci C:\temp\Gateway.log | select-string -pattern $regex |select linenumber, matches
$log=@()
foreach($line in $lines)
{
    [datetime]$logdate = ($line.matches).value
    $ln = $line.linenumber

    if ($logdate -gt '2017-06-29 12:00:00')
    {
        $log += $ln
    }
}

$log
</code>```

When i try to run this script on the server with powershell 2, i get the following error.

Cannot convert null to type "System.DateTime".

I am having trouble converting the value found by the select-string into datetime. tried convert to string with tostring and also with out-string

```<code>  $dt = $line.matches
    $val = $dt|select Value
    $val1 = $val|Out-String
    $val2 = $val.tostring()
    [datetime]$val1
    [datetime]$val2
</code>```

How can I get the value as datetime so I can do datemath on in it powershell 2?

答:
To my experience the am/pm conversion doesn't work (also not with [CultureInfo]::InvariantCulture) if your current locale settings don't apply with it.

You need to specify a cultureinfo object which supports am/pm

```<code>$enUS = 'en-US' -as [Globalization.CultureInfo]
$val1 = (get-date).ToString("M/d/yyyy H:mm:ss tt", $enUS)
$val1
[DateTime]::ParseExact($val1, "M/d/yyyy H:mm:ss tt", $enUS)
</code>```

Body:
I am trying to parse a file for only the most recent entries. Each entry in the log file starts with date in the format "m/d/yyyy h:mm:ss PM".

I write a script that accomplishes what I wanted but unfortunately this script runs on Powershell 5 but not Powershell 2

$regex = '\b([1-2][0-9]|[0-9])\/([1-3][0-9]|[0-9])\/(20[0-9][0-9]) ((1[0-2]|0?[1-9]):([0-5][0-9]):([0-5][0-9]) ([AaPp][Mm]))'

$lines = gci C:\temp\Gateway.log | select-string -pattern $regex |select linenumber, matches
$log=@()
foreach($line in $lines)
{
    [datetime]$logdate = ($line.matches).value
    $ln = $line.linenumber

    if ($logdate -gt '2017-06-29 12:00:00')
    {
        $log += $ln
    }
}

$log

When i try to run this script on the server with powershell 2, i get the following error.

Cannot convert null to type "System.DateTime".

I am having trouble converting the value found by the select-string into datetime. tried convert to string with tostring and also with out-string

  $dt = $line.matches
    $val = $dt|select Value
    $val1 = $val|Out-String
    $val2 = $val.tostring()
    [datetime]$val1
    [datetime]$val2

How can I get the value as datetime so I can do datemath on in it powershell 2?

Body:
To my experience the am/pm conversion doesn't work (also not with [CultureInfo]::InvariantCulture) if your current locale settings don't apply with it.

You need to specify a cultureinfo object which supports am/pm

$enUS = 'en-US' -as [Globalization.CultureInfo]
$val1 = (get-date).ToString("M/d/yyyy H:mm:ss tt", $enUS)
$val1
[DateTime]::ParseExact($val1, "M/d/yyyy H:mm:ss tt", $enUS)


问:
Saving and loading mxGraph file without using a server
I want to create an editor which can save and load (XML format) without using a server. I see the example of grapheditor but it seems that code need a server in order to save.

How do I save/load in mxGraph without the use of a server, that is downloading and uploading the file through browser. Thank you.

答:
In the past Javascript was only allowed to load ressources if the user selected them via the file dialogs. Writing a file was and is still considered a security risk.

But modern browsers support the local storage! You can enable the use of the local storage in the GraphEditor example (https://jgraph.github.io/mxgraph/javascript/examples/grapheditor/www/index.html) by adding the GET parameter storage=local to your request.

For example: localhost:8000/index.html?storage=local

This is the explanation from the GraphEditor code:

```<code>// - storage=local: Enables HTML5 local storage.
</code>```

Body:
In the past Javascript was only allowed to load ressources if the user selected them via the file dialogs. Writing a file was and is still considered a security risk.

But modern browsers support the local storage! You can enable the use of the local storage in the GraphEditor example (https://jgraph.github.io/mxgraph/javascript/examples/grapheditor/www/index.html) by adding the GET parameter storage=local to your request.

For example: localhost:8000/index.html?storage=local

This is the explanation from the GraphEditor code:

// - storage=local: Enables HTML5 local storage.


问:
WMI query to Read 'Microsoft-Windows-AppLocker/EXE and DLL' C#
I have created an agent to read windows event using WMI. I ma using the agent from last 3 years to collect events. It is used in a SEIM product. The query looks like

```<code>SELECT * FROM Win32_NTLogEvent where LogFile = 'System' or logFile='Active Directory Web Services'
</code>```

I am able to get the events properly. But Now I want to read apploacker events 'Microsoft-Windows-AppLocker/EXE and DLL' (Application and Security Logs -> Microsoft -> Windows -> AppLocker -> Exe And DLL).

I tried the below query but it returns zero record though I have 40+ records in it. I can see the record in event viewer.

```<code>SELECT * FROM Win32_NTLogEvent where LogFile = 'Microsoft-Windows-AppLocker/EXE and DLL'
</code>```

I have tried with "wbemtest" but no record with no error.

I am not sure if this can be achieved by any other way using WMI. I know Powershell has a cmdlet and through which I am able to read 'Microsoft-Windows-AppLocker/EXE and DLL' events. But I want to read it using WMI.

Any pointers will be highly appreciated.

Thanks in advance to all viewers.

答:
It seems that the WMI Query parses the registry location HKLM\SYSTEM\CurrentControlSet\Services\EventLog for available event logs (see MSDN Forum post).
Check the list you find there with the result of the query Select * FROM Win32_NTEventLogFile.

To add a logfile for WMI operations, add a new key under the above registry location with the name of the log ('Microsoft-Windows-AppLocker/EXE and DLL' in your case). Now it should return that log with your WMI query.

Body:
I have created an agent to read windows event using WMI. I ma using the agent from last 3 years to collect events. It is used in a SEIM product. The query looks like

SELECT * FROM Win32_NTLogEvent where LogFile = 'System' or logFile='Active Directory Web Services'

I am able to get the events properly. But Now I want to read apploacker events 'Microsoft-Windows-AppLocker/EXE and DLL' (Application and Security Logs -> Microsoft -> Windows -> AppLocker -> Exe And DLL).

I tried the below query but it returns zero record though I have 40+ records in it. I can see the record in event viewer.

SELECT * FROM Win32_NTLogEvent where LogFile = 'Microsoft-Windows-AppLocker/EXE and DLL'

I have tried with "wbemtest" but no record with no error.

I am not sure if this can be achieved by any other way using WMI. I know Powershell has a cmdlet and through which I am able to read 'Microsoft-Windows-AppLocker/EXE and DLL' events. But I want to read it using WMI.

Any pointers will be highly appreciated.

Thanks in advance to all viewers.


问:
Get first and second values in dictionary in CPython 3.6
Now that dictionaries are ordered in python 3.6, it must be the case that there is a way to get the first and second values of a dictionary in only two lines.  Right now, I have to use 7 lines to accomplish this:

```<code>for key, value in class_sent.items():
    i += 1
    if i == 1:
        first_sent = value
    elif i == 2:
        second_sent = value
</code>```

I also tried:

```<code>first_sent = next(iter(class_sent))
    second_sent = next(iter(class_sent))
</code>```

But in that case the second_sent is equal to the first_sent. If anyone knows how to obtain the first and second values in a dictionary in as few lines as possible I would seriously appreciate it.

答:
Right now Python only guarantees that the order of **kwargs and class attributes are preserved.

Considering that the implementation of Python you're using guarantees this behaviour you could do.

Using itertools.islice.

```<code>>>> from itertools import islice
>>> dct = {'a': 1, 'b': 2, 'c': 3}
>>> first, second = islice(dct.values(), 2)
>>> first, second
(1, 2)
</code>```

Using iter().

```<code>>>> it = iter(dct.values())
>>> first, second = next(it), next(it)
>>> first, second
(1, 2)
</code>```

Using extended iterable unpacking(will result in unnecessary unpacking of other values as well):

```<code>>>> first, second, *_ = dct.values()
>>> first, second
(1, 2)
</code>```

Body:
Now that dictionaries are ordered in python 3.6, it must be the case that there is a way to get the first and second values of a dictionary in only two lines.  Right now, I have to use 7 lines to accomplish this:

for key, value in class_sent.items():
    i += 1
    if i == 1:
        first_sent = value
    elif i == 2:
        second_sent = value

I also tried:

first_sent = next(iter(class_sent))
    second_sent = next(iter(class_sent))

But in that case the second_sent is equal to the first_sent. If anyone knows how to obtain the first and second values in a dictionary in as few lines as possible I would seriously appreciate it.

Body:
Right now Python only guarantees that the order of **kwargs and class attributes are preserved.

Considering that the implementation of Python you're using guarantees this behaviour you could do.

Using itertools.islice.

>>> from itertools import islice
>>> dct = {'a': 1, 'b': 2, 'c': 3}
>>> first, second = islice(dct.values(), 2)
>>> first, second
(1, 2)

Using iter().

>>> it = iter(dct.values())
>>> first, second = next(it), next(it)
>>> first, second
(1, 2)

Using extended iterable unpacking(will result in unnecessary unpacking of other values as well):

>>> first, second, *_ = dct.values()
>>> first, second
(1, 2)


问:
Issue with Arduino code running Motors with H Bridge and Arduino according to the written code
So i have an issue in which when I run my code with my ultrasonic sensors, and h bridge with motors one motor spins at all times and the other spins every 6 seconds for 2 seconds but i don't know why. Any help?

Here is the code:

```<code>int in1 = 2;
int in2 = 3;
int in3 = 4;
int in4 = 5;
int in5 = 6;
int in6 = 7;
int trig = 8;
int echol = 9;
int echor = 12;
int echof = 11;
long df, tf, dr, tr, dl, tl;
 void setup() {

  Serial.begin(9600);
    }

void loop() {

 pinMode (in1, OUTPUT);
 pinMode (in2, OUTPUT);
 pinMode (in3, OUTPUT);
 pinMode (in4, OUTPUT);
 pinMode (in5, OUTPUT);
 pinMode (in6, OUTPUT);
 pinMode (trig, OUTPUT);
 pinMode (echol, INPUT);
 pinMode (echor, INPUT);
 pinMode (echof, INPUT);

forward();

  digitalWrite (trig, HIGH);
  delay (0.01);
  tf = pulseIn (echof, HIGH);
  digitalWrite (trig, LOW);
  df = tf * 0.03156;

  if (df < 1.5){
  digitalWrite (trig, HIGH);
  delay (0.01);
  tr = pulseIn (echor, HIGH);
  tl = pulseIn (echol, HIGH);
  digitalWrite (trig, LOW);
  dr = tr * 0.03156;
  dl = tl * 0.03156;

   if (dr > dl) {

    right();
    delay (5000);
    forward();

  }
  else {

    left();
    delay (5000);
    forward();

  }

}

}

void forward(){
 digitalWrite (in1, HIGH);
 digitalWrite (in2, LOW);
 digitalWrite (in3, HIGH);
 digitalWrite (in4, LOW);
 digitalWrite (in5, HIGH);
 digitalWrite (in6, LOW);
}

void backward(){
  digitalWrite (in1, LOW);
  digitalWrite (in2, HIGH);
  digitalWrite (in3, LOW);
  digitalWrite (in4, HIGH);
  digitalWrite (in5, LOW);
  digitalWrite (in6, HIGH);
}

void left(){
  digitalWrite (in1, LOW);
  digitalWrite (in2, LOW);
  digitalWrite (in3, HIGH);
  digitalWrite (in4, LOW);
  digitalWrite (in5, HIGH);
  digitalWrite (in6, LOW);
}

void right(){
  digitalWrite (in1, HIGH);
  digitalWrite (in2, LOW);
  digitalWrite (in3, LOW);
  digitalWrite (in4, LOW);
  digitalWrite (in5, HIGH);
  digitalWrite (in6, LOW);
}
</code>```

答: Not sure of everything that is wrong, but multiplying a long by tl * 0.03156 and storing the value in a long is probably not doing what you intend.  You should use floating-point values to contain the results of that sort of calculation.

Body:
So i have an issue in which when I run my code with my ultrasonic sensors, and h bridge with motors one motor spins at all times and the other spins every 6 seconds for 2 seconds but i don't know why. Any help?

Here is the code:

int in1 = 2;
int in2 = 3;
int in3 = 4;
int in4 = 5;
int in5 = 6;
int in6 = 7;
int trig = 8;
int echol = 9;
int echor = 12;
int echof = 11;
long df, tf, dr, tr, dl, tl;
 void setup() {

  Serial.begin(9600);
    }

void loop() {

 pinMode (in1, OUTPUT);
 pinMode (in2, OUTPUT);
 pinMode (in3, OUTPUT);
 pinMode (in4, OUTPUT);
 pinMode (in5, OUTPUT);
 pinMode (in6, OUTPUT);
 pinMode (trig, OUTPUT);
 pinMode (echol, INPUT);
 pinMode (echor, INPUT);
 pinMode (echof, INPUT);

forward();

  digitalWrite (trig, HIGH);
  delay (0.01);
  tf = pulseIn (echof, HIGH);
  digitalWrite (trig, LOW);
  df = tf * 0.03156;

  if (df < 1.5){
  digitalWrite (trig, HIGH);
  delay (0.01);
  tr = pulseIn (echor, HIGH);
  tl = pulseIn (echol, HIGH);
  digitalWrite (trig, LOW);
  dr = tr * 0.03156;
  dl = tl * 0.03156;

   if (dr > dl) {

    right();
    delay (5000);
    forward();

  }
  else {

    left();
    delay (5000);
    forward();

  }

}

}

void forward(){
 digitalWrite (in1, HIGH);
 digitalWrite (in2, LOW);
 digitalWrite (in3, HIGH);
 digitalWrite (in4, LOW);
 digitalWrite (in5, HIGH);
 digitalWrite (in6, LOW);
}

void backward(){
  digitalWrite (in1, LOW);
  digitalWrite (in2, HIGH);
  digitalWrite (in3, LOW);
  digitalWrite (in4, HIGH);
  digitalWrite (in5, LOW);
  digitalWrite (in6, HIGH);
}

void left(){
  digitalWrite (in1, LOW);
  digitalWrite (in2, LOW);
  digitalWrite (in3, HIGH);
  digitalWrite (in4, LOW);
  digitalWrite (in5, HIGH);
  digitalWrite (in6, LOW);
}

void right(){
  digitalWrite (in1, HIGH);
  digitalWrite (in2, LOW);
  digitalWrite (in3, LOW);
  digitalWrite (in4, LOW);
  digitalWrite (in5, HIGH);
  digitalWrite (in6, LOW);
}


问:
Android multiple and dynamically images aligned
Right now, I have a RecyclerView and multiple CardView to show my items.

My CardView have a RelativeLayout where I add some ImageViews (in this case 3, but can be more).

Each of my items will have a list of images to show, lets suppose #item1 have Facebook, Twitter and Youtube, but #item2 just have Facebook and Youtube images.

How should I align the images? If I just remove Twitter image, I need to update layout_toLeftOf of my Facebook image to Youtube image.

I think I shouldn't do this kind of logic to all my items, it will be over power...

Example image:
https://i.stack.imgur.com/uJZTi.png

```<code><android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
card_view:cardCornerRadius="4dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/card_height"
        android:orientation="vertical">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal">

            <ImageView
                android:id="@+id/coverImageView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:scaleType="centerCrop"
                />

            <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="end|top">
                <ImageView android:background="@null"
                    android:id="@+id/facebook"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/facebook_icon"
                    android:layout_toLeftOf="@+id/twitter"/>
                <ImageView android:background="@null"
                    android:id="@+id/twitter"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/twitter_icon"
                    android:layout_toLeftOf="@+id/youtube"/>
                <ImageView android:background="@null"
                    android:id="@+id/youtube"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/youtube_icon"
                    android:layout_alignParentRight="true"/>
            </RelativeLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|bottom"
                android:background="@android:drawable/screen_background_dark_transparent"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/titleTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="16dp"
                    android:textSize="@dimen/text_size"
                    android:textColor="#FFFFFF"
                    android:textStyle="bold" />
            </LinearLayout>
        </FrameLayout>
    </LinearLayout>
</code>```

答:
You should use LinearLayout with Horizontal Orientation !</p>

```<code><LinearLayout
 ...
  android:orientation="horizontal">

    //ImageViews in priority order

</LinearLayout>
</code>```

Body:
Right now, I have a RecyclerView and multiple CardView to show my items.

My CardView have a RelativeLayout where I add some ImageViews (in this case 3, but can be more).

Each of my items will have a list of images to show, lets suppose #item1 have Facebook, Twitter and Youtube, but #item2 just have Facebook and Youtube images.

How should I align the images? If I just remove Twitter image, I need to update layout_toLeftOf of my Facebook image to Youtube image.

I think I shouldn't do this kind of logic to all my items, it will be over power...

Example image:
https://i.stack.imgur.com/uJZTi.png

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
card_view:cardCornerRadius="4dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/card_height"
        android:orientation="vertical">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal">

            <ImageView
                android:id="@+id/coverImageView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:scaleType="centerCrop"
                />

            <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="end|top">
                <ImageView android:background="@null"
                    android:id="@+id/facebook"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/facebook_icon"
                    android:layout_toLeftOf="@+id/twitter"/>
                <ImageView android:background="@null"
                    android:id="@+id/twitter"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/twitter_icon"
                    android:layout_toLeftOf="@+id/youtube"/>
                <ImageView android:background="@null"
                    android:id="@+id/youtube"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/youtube_icon"
                    android:layout_alignParentRight="true"/>
            </RelativeLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|bottom"
                android:background="@android:drawable/screen_background_dark_transparent"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/titleTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="16dp"
                    android:textSize="@dimen/text_size"
                    android:textColor="#FFFFFF"
                    android:textStyle="bold" />
            </LinearLayout>
        </FrameLayout>
    </LinearLayout>

Body:
You should use LinearLayout with Horizontal Orientation !

<LinearLayout
 ...
  android:orientation="horizontal">

    //ImageViews in priority order

</LinearLayout>


问:
Accessing private fields, when explicit 'this' parameter is provided
Not sure, is it a bug or feature, but if i provide an explicit 'this' parameter
to a function, i will not get access to private properties throw this.

```<code>class Test {
    private _document: any;
}

const myDynamicProp = '....';

Object.defineProperty(Test.prototype, myDynamicProp , {
      get: function(this: Test) {
        return this._document[myDynamicProp];  // no access to private  and protected field
      }
  });
</code>```

Can anyone suggest some docs where this moment is clarified ?

答:
will not get access to private properties throw this

Only methods / functions explicitly in the class body will get access to private fields. Allowing external extensions to get it from this would be similar to allowing external classes to get it from instances and is hence not allowed.

More

Your should use a getter instead of defineProperty :

```<code>class Test {
    private _document: any;
    get foo() { return this._document }
}
</code>```

Body:
Not sure, is it a bug or feature, but if i provide an explicit 'this' parameter
to a function, i will not get access to private properties throw this.

class Test {
    private _document: any;
}

const myDynamicProp = '....';

Object.defineProperty(Test.prototype, myDynamicProp , {
      get: function(this: Test) {
        return this._document[myDynamicProp];  // no access to private  and protected field
      }
  });

Can anyone suggest some docs where this moment is clarified ?

Body:
will not get access to private properties throw this

Only methods / functions explicitly in the class body will get access to private fields. Allowing external extensions to get it from this would be similar to allowing external classes to get it from instances and is hence not allowed.

More

Your should use a getter instead of defineProperty :

class Test {
    private _document: any;
    get foo() { return this._document }
}


问:
HttpConfiguration missing assembly
I am building a site using MVC4. I couldn't even begin that I am having a strange error. This is my code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace MyProject
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
</code>```

The error message: The type or name of the assembly 'HttpConfiguration' does not exist in the namespace 'System.Web.Http' (are you missing a using directive or an assembly reference?)

It also doesn't recognize the readonly field RouteParameter. It occurs to me that it may have something to do with the version, my System.Web dll is version 4.0.0.0.

Another additional piece of information is that when I type "using System.Web.   ", Intellisense DOES recognize the .Http dll

HOWEVER, in the code, it does not recognize any of its parameters.

答:
I encountered this error when cloning an MVC 4.0 application which previously worked for me. My problem was that the Microsoft.Net.Http NuGet package wasn't restoring properly. I solved it from the NuGet console:

Update-Package -reinstall Microsoft.Net.Http

Title: HttpConfiguration missing assembly

Body:
I am building a site using MVC4. I couldn't even begin that I am having a strange error. This is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace MyProject
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

The error message: The type or name of the assembly 'HttpConfiguration' does not exist in the namespace 'System.Web.Http' (are you missing a using directive or an assembly reference?)

It also doesn't recognize the readonly field RouteParameter. It occurs to me that it may have something to do with the version, my System.Web dll is version 4.0.0.0.

Another additional piece of information is that when I type "using System.Web.   ", Intellisense DOES recognize the .Http dll

HOWEVER, in the code, it does not recognize any of its parameters.


问:
Globally changing default style in Primefaces
How should I change and apply changes to the default style of primefaces globally and only once?

```<code>.ui-widget,.ui-widget .ui-widget {
    font-size: 90% !important;
}
</code>```

Currently, I am embedding this CSS snippet in the head of every XHTML page.

```<code><head>
    <style type="text/css">
        .ui-widget,.ui-widget .ui-widget {
            font-size: 90% !important;
        }
    </style>
</head>
</code>```

答:
This works fine.</p>

```<code>.ui-g {
    font-size: 13px;
}
</code>```

Body:
How should I change and apply changes to the default style of primefaces globally and only once?

.ui-widget,.ui-widget .ui-widget {
    font-size: 90% !important;
}

Currently, I am embedding this CSS snippet in the head of every XHTML page.

Body:
This works fine.

.ui-g {
    font-size: 13px;
}


问:
getLastKnownLocation returning NULL
I had just got this to work but when I turned off my Wifi to see if I could get a more accurate location using my GPS it's now bringing me a NullPointer error and I can't see why.

The below code gets called first;

```<code> public void onConnected(Bundle dataBundle) {
        connected = true;
        //Request an update from the location client to get current Location details
        mLocationClient.requestLocationUpdates(mLocationRequest,this);
        Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
    }
</code>```

Which then entails this method being called

```<code>public void onLocationChanged(android.location.Location location) {
        // Report to the UI that the location was updated
        String msg = "Updated Location: " +
                Double.toString(location.getLatitude()) + "," +
                Double.toString(location.getLongitude());
        if(tmp != location.getLatitude())
        {
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        }
        tmp = location.getLatitude();
    }
</code>```

You can see I have 2 toasts there and they come back fine with the actual GPS coordinates but when I call the below code it crashes out on the new location line getLastKnownLocation

```<code>public String getLocation()
    {
        // Get the location manager
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, false);
        android.location.Location location = locationManager.getLastKnownLocation(bestProvider);
        Double lat,lon;
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        try {
            lat = location.getLatitude ();
            lon = location.getLongitude ();
            Toast.makeText(this,""+lat.toString()+"-"+lon.toString(),Toast.LENGTH_SHORT).show();
            return new LatLng(lat, lon).toString();
        }
        catch (NullPointerException e){
            Toast.makeText(this,"HELL-NO",Toast.LENGTH_SHORT).show();
            Log.e("HELL-NO","n",e);
            e.printStackTrace();
            return null;
        }
    }
</code>```

I just don't get why when I try to retrieve the location, which seems to have been retrieved in the onLocationChanged method, it just comes up with a nullpointer.

答:
try this code:</p>

```<code>LocationManager mLocationManager;
Location myLocation = getLastKnownLocation();

private Location getLastKnownLocation() {
    mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = mLocationManager.getLastKnownLocation(provider);
        if (l == null) {
            continue;
        }
        if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
            // Found best last known location: %s", l);
            bestLocation = l;
        }
    }
    return bestLocation;
}
</code>```

Title: getLastKnownLocation returning NULL

Body:
I had just got this to work but when I turned off my Wifi to see if I could get a more accurate location using my GPS it's now bringing me a NullPointer error and I can't see why.

The below code gets called first;

 public void onConnected(Bundle dataBundle) {
        connected = true;
        //Request an update from the location client to get current Location details
        mLocationClient.requestLocationUpdates(mLocationRequest,this);
        Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
    }

Which then entails this method being called

public void onLocationChanged(android.location.Location location) {
        // Report to the UI that the location was updated
        String msg = "Updated Location: " +
                Double.toString(location.getLatitude()) + "," +
                Double.toString(location.getLongitude());
        if(tmp != location.getLatitude())
        {
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        }
        tmp = location.getLatitude();
    }

You can see I have 2 toasts there and they come back fine with the actual GPS coordinates but when I call the below code it crashes out on the new location line getLastKnownLocation

public String getLocation()
    {
        // Get the location manager
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, false);
        android.location.Location location = locationManager.getLastKnownLocation(bestProvider);
        Double lat,lon;
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        try {
            lat = location.getLatitude ();
            lon = location.getLongitude ();
            Toast.makeText(this,""+lat.toString()+"-"+lon.toString(),Toast.LENGTH_SHORT).show();
            return new LatLng(lat, lon).toString();
        }
        catch (NullPointerException e){
            Toast.makeText(this,"HELL-NO",Toast.LENGTH_SHORT).show();
            Log.e("HELL-NO","n",e);
            e.printStackTrace();
            return null;
        }
    }

I just don't get why when I try to retrieve the location, which seems to have been retrieved in the onLocationChanged method, it just comes up with a nullpointer.

Body:
try this code:

LocationManager mLocationManager;
Location myLocation = getLastKnownLocation();

private Location getLastKnownLocation() {
    mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = mLocationManager.getLastKnownLocation(provider);
        if (l == null) {
            continue;
        }
        if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
            // Found best last known location: %s", l);
            bestLocation = l;
        }
    }
    return bestLocation;
}


问:
How to set useMongoClient (Mongoose 4.11.0)?
This is the code I use to connect to my database:

```<code>private connectDatabase(databaseUri: string): Promise<Mongoose.Connection> {
    return Mongoose.connect(databaseUri).then(() => {
        debug('Connected to MongoDB at %O', databaseUri);
        return Mongoose.connection;
    });
}
</code>```

Today I updated Mongoose to version 4.11.0 and I got this warning when running my tests:

```<code>(node:4138) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0,
use `openUri()` instead, or set the `useMongoClient` option if using `connect()`
or `createConnection()`
</code>```

I can't find any information on how to "set useMongoClient".

Do you guys know how to?

答:
According to the mongoose documentation, this is how useMongoClient can be set.

function connectDatabase(databaseUri){
    var promise = mongoose.connect('mongodb://localhost/myapp', {
        useMongoClient: true,
    });
    return promise;
}
```

Body:
This is the code I use to connect to my database:

private connectDatabase(databaseUri: string): Promise<Mongoose.Connection> {
    return Mongoose.connect(databaseUri).then(() => {
        debug('Connected to MongoDB at %O', databaseUri);
        return Mongoose.connection;
    });
}

Today I updated Mongoose to version 4.11.0 and I got this warning when running my tests:

(node:4138) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0,
use `openUri()` instead, or set the `useMongoClient` option if using `connect()`
or `createConnection()`

I can't find any information on how to "set useMongoClient".

Do you guys know how to?


问:
Friendly name on COM port in Java?
I working on a project where I have to get access to at COM port. I'm at the moment using winjcom to get access and to list the connected devices. My problem is that I would like to have the friendly names displayed instead of just COM3, COM4 and so on.

I found a thread

Getting device/driver information related to a COM port?

which can get the friendly name, but this is based on the face that i know the PID, VID and device ID. I would like to get it on all connected devices.

Hope you guys can help me. :)

答:
This code uses the windows dll setupapi through JNA to get the description of the COM port :</p>

```<code>final SetupApi2 setupApi = SetupApi2.INSTANCE;
int SPDRP_FRIENDLYNAME = 12;

WinNT.HANDLE handle = setupApi.SetupDiGetClassDevsA(null, null, null, SetupApi.DIGCF_ALLCLASSES);

SetupApi.SP_DEVINFO_DATA devInfo = new SetupApi.SP_DEVINFO_DATA();
int indice = 0;

while (setupApi.SetupDiEnumDeviceInfo (handle, indice, devInfo)
    ) {
        char[] windowText1 = new char[255];
    IntByReference flag = new IntByReference(0);

    IntByReference PropertyRegDataType = new IntByReference();
    byte[] descripcionByte = new byte[255];

    if ((setupApi.SetupDiGetDeviceInstanceIdA(handle, devInfo, windowText1, windowText1.length, flag))) {
        if ((setupApi.SetupDiGetDeviceRegistryPropertyA(handle, devInfo, SPDRP_FRIENDLYNAME, PropertyRegDataType, descripcionByte, descripcionByte.length, flag))) {
            String descripcionString = Native.toString(descripcionByte);
            System.out.println(descripcionString);
        }
    }
    indice++;
}

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.platform.win32.Guid.GUID;
import com.sun.jna.platform.win32.SetupApi;
import com.sun.jna.platform.win32.SetupApi.SP_DEVICE_INTERFACE_DATA;
import com.sun.jna.platform.win32.SetupApi.SP_DEVINFO_DATA;
import com.sun.jna.platform.win32.WinBase;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.ptr.IntByReference;
import java.util.Arrays;
import java.util.List;

public interface SetupApi2 extends Library {

SetupApi2 INSTANCE = (SetupApi2) Native.loadLibrary("setupapi", SetupApi2.class);

public static class HDEVINFO extends WinNT.HANDLE {
}

public static class SP_DRVINFO_DATA extends Structure {

    public SP_DRVINFO_DATA() {
        DriverDate = new WinBase.FILETIME();
    }
    public int cbSize;
    public int DriverType;
    public int Reserved;
    public char[] Description = new char[255];
    public char[] MfgName = new char[255];
    public char[] ProviderName = new char[255];
    public WinBase.FILETIME DriverDate;
    public int DriverVersion;

    protected List getFieldOrder() {
        return Arrays.asList("cbSize",
                "DriverType",
                "Reserved",
                "Description",
                "MfgName",
                "ProviderName",
                "DriverDate",
                "DriverVersion");
    }
}

public static class SP_DEVICE_INTERFACE_DETAIL_DATA extends Structure {

    public static class ByReference extends SP_DEVINFO_DATA implements Structure.ByReference {

        public ByReference() {
        }

        public ByReference(Pointer memory) {
            super(memory);
        }
    }

    public SP_DEVICE_INTERFACE_DETAIL_DATA() {
        cbSize = size();
        setAlignType(Structure.ALIGN_NONE);
    }

    public SP_DEVICE_INTERFACE_DETAIL_DATA(int size) {
        cbSize = size();
        devicePath = new char[size];
        setAlignType(Structure.ALIGN_NONE);
    }

    public SP_DEVICE_INTERFACE_DETAIL_DATA(Pointer memory) {
        super(memory);
        read();
    }

    /**
     * The size, in bytes, of the SP_DEVINFO_DATA structure.
     */
    public int cbSize;

    public char[] devicePath = new char[1];

    protected List getFieldOrder() {
        return Arrays.asList("cbSize",
                "devicePath");
    }
}

public static int DIGCF_DEFAULT = 0x00000001;
public static int DIGCF_PRESENT = 0x00000002;
public static int DIGCF_ALLCLASSES = 0x00000004;
public static int DIGCF_PROFILE = 0x00000008;
public static int DIGCF_DEVICEINTERFACE = 0x00000010;
public static int SPDRP_DRIVER = 0x00000009;
public static int SPDRP_INSTALL_STATE = 0x00000022;

WinNT.HANDLE SetupDiGetClassDevsA(GUID Guid, String Enumerator, WinDef.HWND Parent, int Flags);

boolean SetupDiEnumDeviceInfo(WinNT.HANDLE DeviceInfoSet, int MemberIndex, SP_DEVINFO_DATA DeviceInfoData);

int SetupDiEnumDeviceInterfaces(HDEVINFO DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, GUID Guid, int MemberIndex, SP_DEVICE_INTERFACE_DATA DeviceInterfaceData);

int SetupDiGetDeviceInterfaceDetail(HDEVINFO DeviceInfoSet, SP_DEVICE_INTERFACE_DATA DeviceInterfaceData, SP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData, int DeviceInterfaceDetailDataSize, IntByReference RequiredSize, SP_DEVINFO_DATA DeviceInfoData);

int SetupDiDestroyDeviceInfoList(HDEVINFO DeviceInfoSet);

boolean SetupDiGetDeviceInstanceIdA(WinNT.HANDLE DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, char[] DeviceId, int DeviceInstanceIdSize, IntByReference RequiredSize);

boolean SetupDiClassNameFromGuid(GUID Guid, char[] ClassName, int ClassNameSize, IntByReference RequiredSize);

boolean SetupDiGetSelectedDriver(HDEVINFO DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, SP_DRVINFO_DATA DriverInfoData);

boolean SetupDiClassGuidsFromName(String ClassName, GUID[] ClassGuidList, int ClassGuidListSize, IntByReference RequiredSize);

boolean SetupDiGetDeviceRegistryPropertyA(WinNT.HANDLE DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, int Property, IntByReference PropertyRegDataType, byte[] PropertyBuffer, int PropertyBufferSize, IntByReference RequiredSize);
}
</code>```

Title: Friendly name on COM port in Java?

Body:
This code uses the windows dll setupapi through JNA to get the description of the COM port :

final SetupApi2 setupApi = SetupApi2.INSTANCE;
int SPDRP_FRIENDLYNAME = 12;

WinNT.HANDLE handle = setupApi.SetupDiGetClassDevsA(null, null, null, SetupApi.DIGCF_ALLCLASSES);

SetupApi.SP_DEVINFO_DATA devInfo = new SetupApi.SP_DEVINFO_DATA();
int indice = 0;

while (setupApi.SetupDiEnumDeviceInfo (handle, indice, devInfo)
    ) {
        char[] windowText1 = new char[255];
    IntByReference flag = new IntByReference(0);

    IntByReference PropertyRegDataType = new IntByReference();
    byte[] descripcionByte = new byte[255];

    if ((setupApi.SetupDiGetDeviceInstanceIdA(handle, devInfo, windowText1, windowText1.length, flag))) {
        if ((setupApi.SetupDiGetDeviceRegistryPropertyA(handle, devInfo, SPDRP_FRIENDLYNAME, PropertyRegDataType, descripcionByte, descripcionByte.length, flag))) {
            String descripcionString = Native.toString(descripcionByte);
            System.out.println(descripcionString);
        }
    }
    indice++;
}

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.platform.win32.Guid.GUID;
import com.sun.jna.platform.win32.SetupApi;
import com.sun.jna.platform.win32.SetupApi.SP_DEVICE_INTERFACE_DATA;
import com.sun.jna.platform.win32.SetupApi.SP_DEVINFO_DATA;
import com.sun.jna.platform.win32.WinBase;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.ptr.IntByReference;
import java.util.Arrays;
import java.util.List;

public interface SetupApi2 extends Library {

SetupApi2 INSTANCE = (SetupApi2) Native.loadLibrary("setupapi", SetupApi2.class);

public static class HDEVINFO extends WinNT.HANDLE {
}

public static class SP_DRVINFO_DATA extends Structure {

    public SP_DRVINFO_DATA() {
        DriverDate = new WinBase.FILETIME();
    }
    public int cbSize;
    public int DriverType;
    public int Reserved;
    public char[] Description = new char[255];
    public char[] MfgName = new char[255];
    public char[] ProviderName = new char[255];
    public WinBase.FILETIME DriverDate;
    public int DriverVersion;

    protected List getFieldOrder() {
        return Arrays.asList("cbSize",
                "DriverType",
                "Reserved",
                "Description",
                "MfgName",
                "ProviderName",
                "DriverDate",
                "DriverVersion");
    }
}

public static class SP_DEVICE_INTERFACE_DETAIL_DATA extends Structure {

    public static class ByReference extends SP_DEVINFO_DATA implements Structure.ByReference {

        public ByReference() {
        }

        public ByReference(Pointer memory) {
            super(memory);
        }
    }

    public SP_DEVICE_INTERFACE_DETAIL_DATA() {
        cbSize = size();
        setAlignType(Structure.ALIGN_NONE);
    }

    public SP_DEVICE_INTERFACE_DETAIL_DATA(int size) {
        cbSize = size();
        devicePath = new char[size];
        setAlignType(Structure.ALIGN_NONE);
    }

    public SP_DEVICE_INTERFACE_DETAIL_DATA(Pointer memory) {
        super(memory);
        read();
    }

    /**
     * The size, in bytes, of the SP_DEVINFO_DATA structure.
     */
    public int cbSize;

    public char[] devicePath = new char[1];

    protected List getFieldOrder() {
        return Arrays.asList("cbSize",
                "devicePath");
    }
}

public static int DIGCF_DEFAULT = 0x00000001;
public static int DIGCF_PRESENT = 0x00000002;
public static int DIGCF_ALLCLASSES = 0x00000004;
public static int DIGCF_PROFILE = 0x00000008;
public static int DIGCF_DEVICEINTERFACE = 0x00000010;
public static int SPDRP_DRIVER = 0x00000009;
public static int SPDRP_INSTALL_STATE = 0x00000022;

WinNT.HANDLE SetupDiGetClassDevsA(GUID Guid, String Enumerator, WinDef.HWND Parent, int Flags);

boolean SetupDiEnumDeviceInfo(WinNT.HANDLE DeviceInfoSet, int MemberIndex, SP_DEVINFO_DATA DeviceInfoData);

int SetupDiEnumDeviceInterfaces(HDEVINFO DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, GUID Guid, int MemberIndex, SP_DEVICE_INTERFACE_DATA DeviceInterfaceData);

int SetupDiGetDeviceInterfaceDetail(HDEVINFO DeviceInfoSet, SP_DEVICE_INTERFACE_DATA DeviceInterfaceData, SP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData, int DeviceInterfaceDetailDataSize, IntByReference RequiredSize, SP_DEVINFO_DATA DeviceInfoData);

int SetupDiDestroyDeviceInfoList(HDEVINFO DeviceInfoSet);

boolean SetupDiGetDeviceInstanceIdA(WinNT.HANDLE DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, char[] DeviceId, int DeviceInstanceIdSize, IntByReference RequiredSize);

boolean SetupDiClassNameFromGuid(GUID Guid, char[] ClassName, int ClassNameSize, IntByReference RequiredSize);

boolean SetupDiGetSelectedDriver(HDEVINFO DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, SP_DRVINFO_DATA DriverInfoData);

boolean SetupDiClassGuidsFromName(String ClassName, GUID[] ClassGuidList, int ClassGuidListSize, IntByReference RequiredSize);

boolean SetupDiGetDeviceRegistryPropertyA(WinNT.HANDLE DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, int Property, IntByReference PropertyRegDataType, byte[] PropertyBuffer, int PropertyBufferSize, IntByReference RequiredSize);
}


问:
Cordova LocalStorage doesn't work
Do I have to install a plugin in Android platform? I cannot find anything for a plugin in the Cordova documentation. </p>

```<code>function save(){
    window.localStorage.setItem("key", "value");
    var keyname = window.localStorage.key(i);
    var value = window.localStorage.getItem("key");
    alert (value);
}
</code>```

答:
Dario, since you are using LocalStorage there is no plugin required. I am not sure about your statement:

window.localStorage.key(i);

Where is i set?

I have a UTIL class I use with Getter / Setter. Here is the js for that. Hope this helps.

```<code>var util = function () {
    return {
        //-----------------------------------
        set: function (key, value) {
            localStorage.setItem(key, JSON.stringify(value));
        },
        //-----------------------------------
        get: function (key, defaultVal) {
            var value = JSON.parse(localStorage.getItem(key));
            if (value === null) value = defaultVal;
            return value;
        },
  }; //End Return

}(); //End Closure

//Sample Set
util.set("downloadFlag", 1);

//Sample Get (with a default value 0 if null is found)
var fileDownloadedFlag = util.get("downloadFlag", 0);
</code>```

Title: Cordova LocalStorage doesn't work

Body:
Do I have to install a plugin in Android platform? I cannot find anything for a plugin in the Cordova documentation.

function save(){
    window.localStorage.setItem("key", "value");
    var keyname = window.localStorage.key(i);
    var value = window.localStorage.getItem("key");
    alert (value);
}

Body:
Dario, since you are using LocalStorage there is no plugin required. I am not sure about your statement:

window.localStorage.key(i);

Where is i set?

I have a UTIL class I use with Getter / Setter. Here is the js for that. Hope this helps.

var util = function () {
    return {
        //-----------------------------------
        set: function (key, value) {
            localStorage.setItem(key, JSON.stringify(value));
        },
        //-----------------------------------
        get: function (key, defaultVal) {
            var value = JSON.parse(localStorage.getItem(key));
            if (value === null) value = defaultVal;
            return value;
        },
  }; //End Return

}(); //End Closure

//Sample Set
util.set("downloadFlag", 1);

//Sample Get (with a default value 0 if null is found)
var fileDownloadedFlag = util.get("downloadFlag", 0);


问:
Can't write/read an array of class objects to a file
I have a class User with 3 parameters: id, pass, active

I want to write an array of User objects to a file but it is not work.

Sometimes it is work but after that I can read only these parameters: id, active.

The parameter pass gives me: nothing, some characters or one character(almost 'a').

The class:

```<code>class User {
    int id;
    char *pass;
    bool active;
public:
    User() {
        id = -1;
        pass = NULL;
        active = 0;
    }
    User(int id, char * pass, bool active = 1) {
        this->id = id;

        if (pass) delete[] pass;
        this->pass = new char[strlen(pass)];
        memcpy(this->pass, pass, strlen(this->pass));

        this->active = active;
    }

    void set_id(int id) {
        this->id = id;
    }
    void set_active(bool active) {
        this->active = active;
    }
    void set_pass(char *pass) {
        this->pass = new char[strlen(pass)];
        memcpy(this->pass, pass, strlen(this->pass));
    }

    int get_id() {
        return id;
    }
    char *get_pass() {
        return pass;
    }
    bool get_active() {
        return active;
    }
};
</code>```

It is my array:

```<code>User *users = new User[999999]; int size_ = 0;
</code>```

Main:

```<code>int main() {

    fstream r_user("user.txt", ios::binary | ios::in);
    if (!r_user) {
        r_user.close();
        char pass[100];
        cerr << "You don't have any user, please create user" << endl;
        cout << "User pass: "; cin >> pass;
        users[0].set_id(0);
        users[0].set_pass(pass);
        users[0].set_active(1);
        size_++;
        cout << users[0].get_pass();
        fstream w_user("user.txt", ios::binary | ios::out);
        w_user.write(reinterpret_cast<char *>(users), size_ * sizeof(User));
        w_user.close();
    }
    else {
        r_user.seekg(0, r_user.end);
        size_ = r_user.tellg();
        r_user.seekg(0, r_user.beg);
        size_ = size_ / sizeof(users);
        r_user.read(reinterpret_cast<char *>(users),  99999 * sizeof(User));
        r_user.close();
        cout << users[0].get_pass();
    }
    return 0;
}
</code>```

The file is not empty.

答:
Your code suffers two critical bug in the way you handle the storage of the pass.

You use:

```<code>    this->pass = new char[strlen(pass)];
    memcpy(this->pass, pass, strlen(this->pass));
</code>```

Note that any string is NULL byte terminated, so the size of the data you want to copy are strlen(pass)+1. Eg: strlen("abcedf") == 6 but you need 7 bytes to store it.

Consequences can be dramatic: when trying to read the string, the software will hit other chunks of memory concatenated to this region, and will read an erroneous string (because no NULL byte stops the string reading). Over time, with more functions, this small error may leak memory into files, might cause a crash or write NULL bytes in an off-by-one fashion, functions stop working properly and everything goes downhill... Sounds like hell uh?

```<code>    this->pass = new char[strlen(pass) + 1];
    memcpy(this->pass, pass, strlen(this->pass) + 1);
</code>```

Or, more elegant:

```<code>    this->pass = new char[strlen(pass) + 1];
    this->pass = strcpy(this->pass, pass);
</code>```

Or more elegant and safer:

```<code>    this->pass = strdup(pass);
</code>```

You also might want to use a unique private function for this kind of management, actually this sensitive part is duplicated in your code.

And hash the pass maybe? :-) Go for Bcrypt if you want something serious for the job: https://github.com/rg3/bcrypt

I also see that you use a pointer for that pass stuff. So you save the pointer, but not the pointed data.

When loading the value of the pointer, nothing is there in memory, or if something is there it's certainly not your pass (which have never been saved). You must use a static buffer to store that pass, and ensure that your class will stay POD (Plain Old Data).

With the use of hashed passwords, your final buffer will have a deterministic size. Eg:

```<code>char bcrypt_password[64];
</code>```

instead of:

```<code>char *pass;
</code>```

But then beware your allocation:

```<code> new User[999999];
</code>```

will eat up fair chunks of memory.

I would be you, I would go for a serialization of your object, and the integration of import() export() methods. A basic CSV serialization would allow for later DB imports / exports.

Body:
I have a class User with 3 parameters: id, pass, active

I want to write an array of User objects to a file but it is not work.

Sometimes it is work but after that I can read only these parameters: id, active.

The parameter pass gives me: nothing, some characters or one character(almost 'a').

The class:

class User {
    int id;
    char *pass;
    bool active;
public:
    User() {
        id = -1;
        pass = NULL;
        active = 0;
    }
    User(int id, char * pass, bool active = 1) {
        this->id = id;

        if (pass) delete[] pass;
        this->pass = new char[strlen(pass)];
        memcpy(this->pass, pass, strlen(this->pass));

        this->active = active;
    }

    void set_id(int id) {
        this->id = id;
    }
    void set_active(bool active) {
        this->active = active;
    }
    void set_pass(char *pass) {
        this->pass = new char[strlen(pass)];
        memcpy(this->pass, pass, strlen(this->pass));
    }

    int get_id() {
        return id;
    }
    char *get_pass() {
        return pass;
    }
    bool get_active() {
        return active;
    }
};

It is my array:

User *users = new User[999999]; int size_ = 0;

Main:

int main() {

    fstream r_user("user.txt", ios::binary | ios::in);
    if (!r_user) {
        r_user.close();
        char pass[100];
        cerr << "You don't have any user, please create user" << endl;
        cout << "User pass: "; cin >> pass;
        users[0].set_id(0);
        users[0].set_pass(pass);
        users[0].set_active(1);
        size_++;
        cout << users[0].get_pass();
        fstream w_user("user.txt", ios::binary | ios::out);
        w_user.write(reinterpret_cast<char *>(users), size_ * sizeof(User));
        w_user.close();
    }
    else {
        r_user.seekg(0, r_user.end);
        size_ = r_user.tellg();
        r_user.seekg(0, r_user.beg);
        size_ = size_ / sizeof(users);
        r_user.read(reinterpret_cast<char *>(users),  99999 * sizeof(User));
        r_user.close();
        cout << users[0].get_pass();
    }
    return 0;
}

The file is not empty.

Body:
Your code suffers two critical bug in the way you handle the storage of the pass.

You use:

    this->pass = new char[strlen(pass)];
    memcpy(this->pass, pass, strlen(this->pass));

Note that any string is NULL byte terminated, so the size of the data you want to copy are strlen(pass)+1. Eg: strlen("abcedf") == 6 but you need 7 bytes to store it.

Consequences can be dramatic: when trying to read the string, the software will hit other chunks of memory concatenated to this region, and will read an erroneous string (because no NULL byte stops the string reading). Over time, with more functions, this small error may leak memory into files, might cause a crash or write NULL bytes in an off-by-one fashion, functions stop working properly and everything goes downhill... Sounds like hell uh?

    this->pass = new char[strlen(pass) + 1];
    memcpy(this->pass, pass, strlen(this->pass) + 1);

Or, more elegant:

    this->pass = new char[strlen(pass) + 1];
    this->pass = strcpy(this->pass, pass);

Or more elegant and safer:

    this->pass = strdup(pass);

You also might want to use a unique private function for this kind of management, actually this sensitive part is duplicated in your code.

And hash the pass maybe? :-) Go for Bcrypt if you want something serious for the job: https://github.com/rg3/bcrypt

I also see that you use a pointer for that pass stuff. So you save the pointer, but not the pointed data.

When loading the value of the pointer, nothing is there in memory, or if something is there it's certainly not your pass (which have never been saved). You must use a static buffer to store that pass, and ensure that your class will stay POD (Plain Old Data).

With the use of hashed passwords, your final buffer will have a deterministic size. Eg:

char bcrypt_password[64];

instead of:

char *pass;

But then beware your allocation:

 new User[999999];

will eat up fair chunks of memory.

I would be you, I would go for a serialization of your object, and the integration of import() export() methods. A basic CSV serialization would allow for later DB imports / exports.


问:
I am trying to run older VC++ code in 2010VC++ I am getting error C387 error
```<code>this->InitButton->Location = System::Drawing::Point(24, 8);
this->InitButton->Name = S"InitButton";
this->InitButton->Size = System::Drawing::Size(184, 24);
this->InitButton->TabIndex = 0;
this->InitButton->Text = S"Initialize NMC Network";

// this give an error
this->InitButton->Click += new System::EventHandler(this, InitButton_Click);
</code>```

答: In addition to Hans's answer concerning the correct way to get a pointer-to-member for delegate construction, C++/CLI does not use the S prefix on managed strings.</p>

ContentLicense: CC BY-SA 2.5


答:
This could work:</p>

```<code>first_sent, second_sent = list(class_sent.values())[:2]
</code>```

Title: Get first and second values in dictionary in CPython 3.6

Body:
Now that dictionaries are ordered in python 3.6, it must be the case that there is a way to get the first and second values of a dictionary in only two lines.  Right now, I have to use 7 lines to accomplish this:

for key, value in class_sent.items():
    i += 1
    if i == 1:
        first_sent = value
    elif i == 2:
        second_sent = value

I also tried:

first_sent = next(iter(class_sent))
    second_sent = next(iter(class_sent))

But in that case the second_sent is equal to the first_sent. If anyone knows how to obtain the first and second values in a dictionary in as few lines as possible I would seriously appreciate it.

Body:
This could work:

first_sent, second_sent = list(class_sent.values())[:2]


问:
How to structure model that is broken into database as 36 tables?
I have over 1 billion domain name records which, instead of putting them all in a single table, I decided to break them up into 36 tables (same db structure for each table).

There is a table based on the first character of the domain name (ex tables: domains_a... domains_z).

How can I create a single Domain model in rails that automatically switches between these tables seamlessly based on the character specified?

答:
You can't: you have to write your own logic to deal with that. Rails would need to know your business logic and analyze the SQL query to find out which table to pick and can't do that by default, you need to write that code by yourself.

However there is a trick that will make it extremely easier for you. What about handling this on the database level? I've checked and all major databases support updatable views.

So, create a new view, name it domains and make sure it creates a union of all your domain tables (from a to z), then createa model:

```<code>class Domain
  self.table_name = "your_view_name"
end
</code>```

This would do the trick for read side. Now based on the database you are using, you might be able to solve also the write problem in this way (with triggers and similar DB functionalities), otherwise, you need to write your own code for the write part, which will probably need to run raw queries.

As an alternative, you can deal with this at Ruby level by creating all the models (DomainA, DomainB, etc.) manually or with a generator and then creating a common class that acts as an interface. Or, you can create those models with some metaprogramming and again have a common class which work as an interface.

Body:
You can't: you have to write your own logic to deal with that. Rails would need to know your business logic and analyze the SQL query to find out which table to pick and can't do that by default, you need to write that code by yourself.

However there is a trick that will make it extremely easier for you. What about handling this on the database level? I've checked and all major databases support updatable views.

So, create a new view, name it domains and make sure it creates a union of all your domain tables (from a to z), then createa model:

class Domain
  self.table_name = "your_view_name"
end

This would do the trick for read side. Now based on the database you are using, you might be able to solve also the write problem in this way (with triggers and similar DB functionalities), otherwise, you need to write your own code for the write part, which will probably need to run raw queries.

As an alternative, you can deal with this at Ruby level by creating all the models (DomainA, DomainB, etc.) manually or with a generator and then creating a common class that acts as an interface. Or, you can create those models with some metaprogramming and again have a common class which work as an interface.


问:
App search API validation tool gives request time out
I am working with universal app links. I had put my apple-app-site-association on my server root https://www.example.net/

It works fine for all links except  https://www.portal.example.net/

When i validate this link in https://search.developer.apple.com/appsearch-validation-tool it gives fetch request timeout.

Note : In portal we redirect page to website homepage (https://www.example.net/)

答:
This is expected, due to the design of the Universal Links specification.

Here's why: https://www.example.net/ and https://www.portal.example.net/ are completely different subdomains of https://example.net/.

The Universal Links specification says each subdomain must be verified with its own apple-app-site-association file, which means a file hosted at https://www.example.net/apple-app-site-association will not work for any link on https://www.portal.example.net/. Redirects are not followed.

To fix this, simply host a file at https://www.portal.example.net/apple-app-site-association with no redirects.


问:
Javascript innerHTML method returning wrong value
I'm looking for some support with this math's project I'm doing. Basically I've created four boxes, and populated one with the correct answer. When I click on the correct answer, the if statement doesn't run; it always shows as wrong.

I include a snippet, if someone can see something glaringly wrong then I'd appreciate a response.

I'm only trying it with box 1 to see if it works, and the correct answer does populate in 1 of the 4 boxes, however it always says it's the wrong answer, even when correct answer is in box1.

```<code>document.getElementById("box1").onclick = function() {
  if (playing == true) {
    if (this.innerHTML == correctAnswer) {
      score++;
      document.getElementById("scorevalue").innerHTML = score;
      hide("wrong");
      show("correct");
      setTimeout(function() {
        hide("correct");
      }, 1000);
    } else {
      hide("correct");
      show("wrong");
      setTimeout(function() {
        hide("wrong");
      }, 1000);
    }
  }
}
</code>```

答:
Instead of comparing two values with ==, try === in your if-statements.
Example: if (playing === true) {

Body:
I'm looking for some support with this math's project I'm doing. Basically I've created four boxes, and populated one with the correct answer. When I click on the correct answer, the if statement doesn't run; it always shows as wrong.

I include a snippet, if someone can see something glaringly wrong then I'd appreciate a response.

I'm only trying it with box 1 to see if it works, and the correct answer does populate in 1 of the 4 boxes, however it always says it's the wrong answer, even when correct answer is in box1.

document.getElementById("box1").onclick = function() {
  if (playing == true) {
    if (this.innerHTML == correctAnswer) {
      score++;
      document.getElementById("scorevalue").innerHTML = score;
      hide("wrong");
      show("correct");
      setTimeout(function() {
        hide("correct");
      }, 1000);
    } else {
      hide("correct");
      show("wrong");
      setTimeout(function() {
        hide("wrong");
      }, 1000);
    }
  }
}


问:
Multiple Submit Form Without Reload
I was just wondering if its possible to have a loop of submit forms and then submit from any of these submit forms without refreshing/reloading the entire page.

The reason why I wanna know is because, I am currently working on a website and what I wanna do is for users to be able to press like if they like a picture/message (like a tweet on twitter och an image on instagram) but as of right now, when you press the like button, it refreshes the entire page if I do a simple @using (html.beginform("","")) but if I use jquery, then it only works on the last form (the one at the top)

```<code>$(document).ready(function () {
    $("#submit-buttons").on('click', function () {
        var id = $('#submit-buttons').val();
        $.ajax({
            url: "/Profile/Like",
            type: "POST",
            data: { id: id }
        })
        .done(function (partialViewResult) {
            $("body").html(partialViewResult);
            window.location.href = "/Profile/Index";
        });
    });
});

<button id="submit-buttons" name="id" value="@item.Id" type="submit"></button>
</code>```

submit-buttons is the like buttons, and what it does is, it takes the value (an id) and passes it to a controller and then inserts it to a database. but there are several of these buttons but only 1 works (the one that was looped last). what have I done wrong? :/

Please help.
Thanks!

答:
I'm having a little trouble understanding your question, but I think that using a $(this) selector and type=submit would help it work.

```<code>$(document).ready(function () {
    $("#submit-buttons").on('click', function () {
        var id = $(this).val();
        $.ajax({
            url: "/Profile/Like",
            type: "POST",
            data: { id: id }
        })
        .done(function (partialViewResult) {
            $("body").html(partialViewResult);
            window.location.href = "/Profile/Index";
        });
    });
});

<button id="submit-buttons" name="id" value="@item.Id" type="button"></button>
</code>```

Title: Multiple Submit Form Without Reload

Body:
I was just wondering if its possible to have a loop of submit forms and then submit from any of these submit forms without refreshing/reloading the entire page.

The reason why I wanna know is because, I am currently working on a website and what I wanna do is for users to be able to press like if they like a picture/message (like a tweet on twitter och an image on instagram) but as of right now, when you press the like button, it refreshes the entire page if I do a simple @using (html.beginform("","")) but if I use jquery, then it only works on the last form (the one at the top)

$(document).ready(function () {
    $("#submit-buttons").on('click', function () {
        var id = $('#submit-buttons').val();
        $.ajax({
            url: "/Profile/Like",
            type: "POST",
            data: { id: id }
        })
        .done(function (partialViewResult) {
            $("body").html(partialViewResult);
            window.location.href = "/Profile/Index";
        });
    });
});

<button id="submit-buttons" name="id" value="@item.Id" type="submit"></button>

submit-buttons is the like buttons, and what it does is, it takes the value (an id) and passes it to a controller and then inserts it to a database. but there are several of these buttons but only 1 works (the one that was looped last). what have I done wrong? :/

Please help.
Thanks!

Body:
I'm having a little trouble understanding your question, but I think that using a $(this) selector and type=submit would help it work.

$(document).ready(function () {
    $("#submit-buttons").on('click', function () {
        var id = $(this).val();
        $.ajax({
            url: "/Profile/Like",
            type: "POST",
            data: { id: id }
        })
        .done(function (partialViewResult) {
            $("body").html(partialViewResult);
            window.location.href = "/Profile/Index";
        });
    });
});

<button id="submit-buttons" name="id" value="@item.Id" type="button"></button>


问:
docker saved image, how to run?
I have a testlink docker image running (named 'otechlabs/testlink').

Question 1: How do I get the original url from which I downloaded it (I can't remember) ? I would like to see the instructions about how to run the container.

It's running so fine that I saved a commit of it to run in another machine.

Question 2: Should I remember the run parameters(I can't remember)?

The container was created around 3 months ago.

Question 3: Instead of save/load, should I export/import?

Since I don't remember how to run the image, then I guess I should skip this step, perhaps (someway) copying the image to just start it in another host.

答:
Q1: If you did a 'docker pull' the image id contains the url; if the id does not contain a domain name, then it is by default dockerhub repository

Q2:  (as mentioned by Samual) if you still have a container saved run 'docker inspect ' to display the startup param's

Q3: if you modified the container you can 'commmit' the changes, and you can also change the tag: 'docker tag old_tag new_tag'

To help move it around, you could change he tag to gcr.io/project-id/new_tag:version and push it to google's container registry (free 30 day trail, may be free beyond that if you keep resource usage low) in your project 'project-id'

Title: docker saved image, how to run?


问:
mxCellEditor: strip CSS styling before pasting text
I would like to copy/paste text from MS Excel into my mxGraph editor in order to label nodes and edges.

Problem:
The copied cell content from Excel comes with a lot of CSS styling, so for example it looks like this:

```<code><!--table
{mso-displayed-decimal-separator:"\,";
mso-displayed-thousand-separator:\00A0;}
@page
{margin:.75in .24in .75in .24in;
mso-header-margin:.31in;
...
-->

Actual cell string
</code>```

I would like to strip all the styling and only insert the raw text. In MS Word this behaviour is known as "Match Destination Formatting".

I am aware I can disable HTML labels completely using

```<code>mxGraph.prototype.htmlLabels = false;
</code>```

However, I still want the labels to wrap which seems to require HTML labels.

What is the best approach to intercept the paste event and cleanup the string before it gets inserted as label?

答:
This answer is not related to mxGraph. My practical answer would be to use the "raw" pasting.

Ctrl + C = Copy the content

Ctlr + Shift + V = Paste only the text content (without formatting)

Take a look at this.

Body:
I would like to copy/paste text from MS Excel into my mxGraph editor in order to label nodes and edges.

Problem:
The copied cell content from Excel comes with a lot of CSS styling, so for example it looks like this:

Actual cell string

I would like to strip all the styling and only insert the raw text. In MS Word this behaviour is known as "Match Destination Formatting".

I am aware I can disable HTML labels completely using

mxGraph.prototype.htmlLabels = false;

However, I still want the labels to wrap which seems to require HTML labels.

What is the best approach to intercept the paste event and cleanup the string before it gets inserted as label?

ContentLicense: CC BY-SA 4.0


问:
HTML Search element styling
I´m trying to build a search element together with a button, something like:

Except that I need to change the background color of the search icon (blue, gray, whatever...).

Here is my code so far and the result:

.searchWrap {
  position: absolute;
  border: thin solid #f2f2f2;
  border-radius: 5px;
  top: 5px;
  left: 5px;
}

.searchTerm {
  float: left;
  border-style: none;
  padding: 5px;
  height: 20px;
  outline: none;
}

.searchButton {
  right: -50px;
  width: 30px;
  height: 20px;
  border: 1px solid #f2f2f2;
  background: #f2f2f2;
  border-radius: 5px;
  text-align: center;
  color: #ccc;
  vertical-align: middle;
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div className="searchWrap">
  <input type="text" className="searchTerm" placeholder="Search..." />
  <button type="submit" className="searchButton">
          <Icon name='search' />
       </button>
</div></code>```

I'm using React. Here is my result so far:

The external border is rounded, ok, that's what I need, but the separation between the searchTerm and the searchButton is also rounded, and I need a plain separator here, something like:

答:
Can you use bootstrap? Relatively simple, and once you have it, modify the css the way you want it.

https://v4-alpha.getbootstrap.com/components/input-group/#button-addons

Title: HTML Search element styling

Body:
I´m trying to build a search element together with a button, something like:

Except that I need to change the background color of the search icon (blue, gray, whatever...).

Here is my code so far and the result:

.searchWrap {
  position: absolute;
  border: thin solid #f2f2f2;
  border-radius: 5px;
  top: 5px;
  left: 5px;
}

.searchTerm {
  float: left;
  border-style: none;
  padding: 5px;
  height: 20px;
  outline: none;
}

.searchButton {
  right: -50px;
  width: 30px;
  height: 20px;
  border: 1px solid #f2f2f2;
  background: #f2f2f2;
  border-radius: 5px;
  text-align: center;
  color: #ccc;
  vertical-align: middle;
  cursor: pointer;
}

  <input type="text" className="searchTerm" placeholder="Search..." />
  <button type="submit" className="searchButton">
          <Icon name='search' />
       </button>

I'm using React. Here is my result so far:

The external border is rounded, ok, that's what I need, but the separation between the searchTerm and the searchButton is also rounded, and I need a plain separator here, something like:


问:
C++: Efficient way to check if elements in a vector are greater than elements in another having same indices?
I have a vector < vector <int> > like so:

```<code>v = {{1,2,3}, {4,2,1}, {3,1,1}....}}
</code>```

All v's elements like v[0], v[1], v[2]... have the same size. There may be duplicate elements.

What I am trying to do is to find and delete vectors (like v[2]) that are "majorized" by another vector (like v[1]), i.e. all elements of v[1] are greater than/equal to the respective elements(in order of indices) in v[2].

A naive way of doing this would be to loop thorough v and compare each vector with another vector and further compare each element with another vector's element.

But I feel there must a better way to do this without getting O(n^3) in the number of elements of all the vectors in v.

If multiple vectors are equal, I need only one of them (i.e delete all except one). A random choice would be sufficient.

Any thoughts or ideas are appreciated!

答: This is called the maxima of a point set.  For two and three dimensions, this can be solved in O(n log n) time.  For more than three dimensions, this can be solved in O(n(log n)^(d − 3)  log log n) time.  For random points, a linear expected time algorithm is available.  </p>

Body:
I have a vector < vector <int> > like so:

v = {{1,2,3}, {4,2,1}, {3,1,1}....}}

All v's elements like v[0], v[1], v[2]... have the same size. There may be duplicate elements.

What I am trying to do is to find and delete vectors (like v[2]) that are "majorized" by another vector (like v[1]), i.e. all elements of v[1] are greater than/equal to the respective elements(in order of indices) in v[2].

A naive way of doing this would be to loop thorough v and compare each vector with another vector and further compare each element with another vector's element.

But I feel there must a better way to do this without getting O(n^3) in the number of elements of all the vectors in v.

If multiple vectors are equal, I need only one of them (i.e delete all except one). A random choice would be sufficient.

Any thoughts or ideas are appreciated!


答:
fstream only dumps the raw data so it only works for regular variables.

pass is char*, so it is storing the pointer address instead of the string value.

You need custom serialization for your class.
Add methods to your User class to Load() and Save() so you can handle the pass variable. They should accept the fstream buffer so they can read/write to it.

Title: Can't write/read an array of class objects to a file


问:
JQuery: Why does parent().parent.parent() work but parents(selector) doesnt?
I've been working with jQuery and tried to add a class to a parent element that was 3 steps up the DOM tree. I didn't get it to work with "parents('selector')" but with "parent().parent().parent()".
Could anyone of you help me out and explain why this isn't working?

function activeNav() {

        var nav_list_content = $('.nav_list_content');
        var nav_sub_list_content = $('.nav_sub_list_content');
        var CountNavSubListElements = nav_sub_list_content.length;
        var CountNavListElements = nav_list_content.length;

         for(var c = 0; c<CountNavListElements; c++){
             if(nav_list_content.eq(c).attr("href") == window.location.href){

                nav_list_content.eq(c).addClass('active_nav_link');
               break;
            }
         }

         for(var c = 0; c<CountNavSubListElements; c++){
             if(nav_sub_list_content.eq(c).attr("href") == window.location.href){

                nav_sub_list_content.eq(c).parent().parent().parent().addClass('active_nav_link'); /*Does work*/

              nav_sub_list_content.eq(c).parents('.nav_list_content').addClass('active_nav_link');  /*Doesn't work*/

               break;
            }
         }

   }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="prime_nav">
            <div id="mobile_menu_button">&#9776</div>
            <div id="nav_wrapper">
                <img id="logo" src="Logo.png">
                <ul id="nav_list" class="nos">
                    <li class="nav_list_element">Home</li><!--
                 --><li class="nav_list_element">Page</li><!--
                 --><li class="nav_list_element">
                        Page
                        <ul id="nav_sub_list">
                            <li class="nav_sub_list_element">Page</li>
                            <li class="nav_sub_list_element">Page</li>
                        </ul>
                    </li><!--
                 --><li class="nav_list_element">Page</li><!--
                 --><li class="nav_list_element">Page</li>
                </ul>
            </div>
 </nav></code>```

I'm sorry for so much code. But I appreciate your help.

答:
nav_sub_list_content.eq(c).parent().parent().parent() is selecting the .nav_list_element element. You are passing .nav_list_content to the parents() function, which won't work because that is the class of the element you are tying to find the parent of.

This:

nav_sub_list_content.eq(c).parents('.nav_list_content').addClass('active_nav_link');

Should be:

nav_sub_list_content.eq(c).parents(".nav_list_element").addClass('active_nav_link');

Body:
I've been working with jQuery and tried to add a class to a parent element that was 3 steps up the DOM tree. I didn't get it to work with "parents('selector')" but with "parent().parent().parent()".
Could anyone of you help me out and explain why this isn't working?

function activeNav() {

        var nav_list_content = $('.nav_list_content');
        var nav_sub_list_content = $('.nav_sub_list_content');
        var CountNavSubListElements = nav_sub_list_content.length;
        var CountNavListElements = nav_list_content.length;

         for(var c = 0; c<CountNavListElements; c++){
             if(nav_list_content.eq(c).attr("href") == window.location.href){

                nav_list_content.eq(c).addClass('active_nav_link');
               break;
            }
         }

         for(var c = 0; c<CountNavSubListElements; c++){
             if(nav_sub_list_content.eq(c).attr("href") == window.location.href){

                nav_sub_list_content.eq(c).parent().parent().parent().addClass('active_nav_link'); /*Does work*/

              nav_sub_list_content.eq(c).parents('.nav_list_content').addClass('active_nav_link');  /*Doesn't work*/

               break;
            }
         }

   }

&#9776

Home

Page

                        Page

Page

Page

Page

Page

I'm sorry for so much code. But I appreciate your help.