问:
Facebook accout kit Firebase API initialization failure
After implementing Facebook Account Kit and run project it shows  Firebase API initialization failure as

```<code>FirebaseApp: Firebase API initialization failure.
 java.lang.reflect.InvocationTargetException
 at java.lang.reflect.Method.invoke(Native Method)
 at com.google.firebase.FirebaseApp.zza(Unknown Source)
 at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
 at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
 at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
 at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
 at android.content.ContentProvider.attachInfo(ContentProvider.java:1758)
 at android.content.ContentProvider.attachInfo(ContentProvider.java:1733)
 at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
 at android.app.ActivityThread.installProvider(ActivityThread.java:5257)
 at android.app.ActivityThread.installContentProviders(ActivityThread.java:4808)
 at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4748)
 at android.app.ActivityThread.access$1700(ActivityThread.java:153)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1436)
 at android.os.Handler.dispatchMessage(Handler.java:102)
 at android.os.Looper.loop(Looper.java:154)
 at android.app.ActivityThread.main(ActivityThread.java:5529)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
</code>```

And also getting Null Pointer Exception from AccountKitController as

```<code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
 at com.facebook.accountkit.internal.Initializer.initialize(Initializer.java:101)
 at com.facebook.accountkit.internal.AccountKitController.initialize(AccountKitController.java:601)
 at com.facebook.accountkit.internal.AccountKitInitProvider.onCreate(AccountKitInitProvider.java:31)
 at android.content.ContentProvider.attachInfo(ContentProvider.java:1758)
 at android.content.ContentProvider.attachInfo(ContentProvider.java:1733)
 at android.app.ActivityThread.installProvider(ActivityThread.java:5257)
 at android.app.ActivityThread.installContentProviders(ActivityThread.java:4808)
 at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4748)
 at android.app.ActivityThread.access$1700(ActivityThread.java:153)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1436)
 at android.os.Handler.dispatchMessage(Handler.java:102)
 at android.os.Looper.loop(Looper.java:154)
 at android.app.ActivityThread.main(ActivityThread.java:5529)
 at java.lang.reflect.Method.invoke(Native Method)
</code>```

Using Account kit gradle as

```<code>compile 'com.facebook.android:account-kit-sdk:4.27.0'
</code>```

And Firebase Gradle as

```<code>compile 'com.google.firebase:firebase-messaging:11.0.4'
</code>```

Note : Removing Account Kit from project its working fine i.e. there is no Firebase API initialization failure. issue. Therefore it's sure that there is conflict in firebase and Account kit SDK (:

答:
For NullPointerException exception it seems that, Application is not initialized first, Content Providers are initialized before it.
And in Facebook account kit SDK's code it was trying to get my application context.

Now the problem was, I did implement method getApplicationContext() in application class that is getting application shared variable but that variable was setting globally and Facebook Account Kit sdk code getting Null application context.

Solution : setting shared variable in onCreate method instead of setting globally it resolved the problem of Unable to get provider.

And For Mixing issue, Account Kit SDK use 11.0.1 version for play services gradle and in my project I am having 11.0.4 that is actually not the issue because on compile time gradle takes latest gradle but In my project I am not referring below gradle which Facebook Account Kit SDK is using.

```<code>compile 'com.google.android.gms:play-services-auth-api-phone:11.0.1'
</code>```

Solution : I have added above gradle with version 11.0.4 and the mixing gradle issue has been resolved.

```<code>compile 'com.google.android.gms:play-services-auth-api-phone:11.0.4'
</code>```

And as suggested by @astryk if I exclude play-services-auth-api-phone module then  gradle mixing error is not showing but it is not including that module becasue in AccountKitActivity on next button click my application crashes as

```<code>Crash Report Thread:main Exception:java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/auth/api/phone/SmsRetriever;
at com.facebook.accountkit.internal.PhoneLoginController.createSmsToken(PhoneLoginController.java:250)
at com.facebook.accountkit.internal.PhoneLoginController.logIn(PhoneLoginController.java:188)
at com.facebook.accountkit.internal.LoginManager.logInWithPhoneNumber(LoginManager.java:372)
at com.facebook.accountkit.internal.AccountKitController.logInWithPhoneNumber(AccountKitController.java:631)
at com.facebook.accountkit.ui.PhoneLoginFlowManager.logInWithPhoneNumber(PhoneLoginFlowManager.java:57)
at com.facebook.accountkit.ui.ActivityPhoneHandler.onPhoneLoginComplete(ActivityPhoneHandler.java:189)
at com.facebook.accountkit.ui.AccountKitActivity$1.onReceive(AccountKitActivity.java:176)
at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:297)
at android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)
at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:116)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.auth.api.phone.SmsRetriever" on path: DexPathList[[zip file "/data/app/com.myapp-1/base.apk"],nativeLibraryDirectories=[/data/app/com.myappList item -1/lib/arm64, /vendor/lib64, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
... 16 more
Suppressed: java.lang.ClassNotFoundException: com.google.android.gms.auth.api.phone.SmsRetriever
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 17 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available`
</code>```

Body:
After implementing Facebook Account Kit and run project it shows  Firebase API initialization failure as

FirebaseApp: Firebase API initialization failure.
 java.lang.reflect.InvocationTargetException
 at java.lang.reflect.Method.invoke(Native Method)
 at com.google.firebase.FirebaseApp.zza(Unknown Source)
 at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
 at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
 at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
 at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
 at android.content.ContentProvider.attachInfo(ContentProvider.java:1758)
 at android.content.ContentProvider.attachInfo(ContentProvider.java:1733)
 at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
 at android.app.ActivityThread.installProvider(ActivityThread.java:5257)
 at android.app.ActivityThread.installContentProviders(ActivityThread.java:4808)
 at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4748)
 at android.app.ActivityThread.access$1700(ActivityThread.java:153)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1436)
 at android.os.Handler.dispatchMessage(Handler.java:102)
 at android.os.Looper.loop(Looper.java:154)
 at android.app.ActivityThread.main(ActivityThread.java:5529)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)

And also getting Null Pointer Exception from AccountKitController as

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
 at com.facebook.accountkit.internal.Initializer.initialize(Initializer.java:101)
 at com.facebook.accountkit.internal.AccountKitController.initialize(AccountKitController.java:601)
 at com.facebook.accountkit.internal.AccountKitInitProvider.onCreate(AccountKitInitProvider.java:31)
 at android.content.ContentProvider.attachInfo(ContentProvider.java:1758)
 at android.content.ContentProvider.attachInfo(ContentProvider.java:1733)
 at android.app.ActivityThread.installProvider(ActivityThread.java:5257)
 at android.app.ActivityThread.installContentProviders(ActivityThread.java:4808)
 at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4748)
 at android.app.ActivityThread.access$1700(ActivityThread.java:153)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1436)
 at android.os.Handler.dispatchMessage(Handler.java:102)
 at android.os.Looper.loop(Looper.java:154)
 at android.app.ActivityThread.main(ActivityThread.java:5529)
 at java.lang.reflect.Method.invoke(Native Method)

Using Account kit gradle as

compile 'com.facebook.android:account-kit-sdk:4.27.0'

And Firebase Gradle as

compile 'com.google.firebase:firebase-messaging:11.0.4'

Note : Removing Account Kit from project its working fine i.e. there is no Firebase API initialization failure. issue. Therefore it's sure that there is conflict in firebase and Account kit SDK (:

Body:
For NullPointerException exception it seems that, Application is not initialized first, Content Providers are initialized before it.
And in Facebook account kit SDK's code it was trying to get my application context.

Now the problem was, I did implement method getApplicationContext() in application class that is getting application shared variable but that variable was setting globally and Facebook Account Kit sdk code getting Null application context.

Solution : setting shared variable in onCreate method instead of setting globally it resolved the problem of Unable to get provider.

And For Mixing issue, Account Kit SDK use 11.0.1 version for play services gradle and in my project I am having 11.0.4 that is actually not the issue because on compile time gradle takes latest gradle but In my project I am not referring below gradle which Facebook Account Kit SDK is using.

compile 'com.google.android.gms:play-services-auth-api-phone:11.0.1'

Solution : I have added above gradle with version 11.0.4 and the mixing gradle issue has been resolved.

compile 'com.google.android.gms:play-services-auth-api-phone:11.0.4'

And as suggested by @astryk if I exclude play-services-auth-api-phone module then  gradle mixing error is not showing but it is not including that module becasue in AccountKitActivity on next button click my application crashes as

Crash Report Thread:main Exception:java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/auth/api/phone/SmsRetriever;
at com.facebook.accountkit.internal.PhoneLoginController.createSmsToken(PhoneLoginController.java:250)
at com.facebook.accountkit.internal.PhoneLoginController.logIn(PhoneLoginController.java:188)
at com.facebook.accountkit.internal.LoginManager.logInWithPhoneNumber(LoginManager.java:372)
at com.facebook.accountkit.internal.AccountKitController.logInWithPhoneNumber(AccountKitController.java:631)
at com.facebook.accountkit.ui.PhoneLoginFlowManager.logInWithPhoneNumber(PhoneLoginFlowManager.java:57)
at com.facebook.accountkit.ui.ActivityPhoneHandler.onPhoneLoginComplete(ActivityPhoneHandler.java:189)
at com.facebook.accountkit.ui.AccountKitActivity$1.onReceive(AccountKitActivity.java:176)
at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:297)
at android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)
at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:116)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.auth.api.phone.SmsRetriever" on path: DexPathList[[zip file "/data/app/com.myapp-1/base.apk"],nativeLibraryDirectories=[/data/app/com.myappList item -1/lib/arm64, /vendor/lib64, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
... 16 more
Suppressed: java.lang.ClassNotFoundException: com.google.android.gms.auth.api.phone.SmsRetriever
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 17 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available`


来源: stackexchange

问:
Inline email image shown in production not development
I am sending html emails through the action mailer and something strange occur: an inline image does appear on the email sent from the production deploy but not from local develomment.

professionnel_mailer.rb

```<code>class ProfessionnelMailer < ApplicationMailer

    layout 'professionnelmailer'

    def notification(professionnel)
        attachments.inline['image200.png'] = File.read("#{Rails.root}/app/assets/images/image200.png")
        @professionnel = professionnel
        mail(to: @professionnel.email, subject: "You have received a notification !")
    end
end
</code>```

notification.html.erb

```<code><%= image_tag(attachments['image200.png'].url)%>
<h1>Hello <%= @professionnel.first_name %> !</h1>
</code>```

Of course image200.png is present locally and remotely. And email is received in both cases, then my Amazon AWS SES setup is corrrect in both environments.. Not very sure where it breaks..

答:
For Rails >= 4.2 to preview images you should create initializer:</p>

```<code># config/initializer/preview_interceptors.rb
ActionMailer::Base.register_preview_interceptor(ActionMailer::InlinePreviewInterceptor)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am sending html emails through the action mailer and something strange occur: an inline image does appear on the email sent from the production deploy but not from local develomment.

professionnel_mailer.rb

class ProfessionnelMailer < ApplicationMailer

    layout 'professionnelmailer'

    def notification(professionnel)
        attachments.inline['image200.png'] = File.read("#{Rails.root}/app/assets/images/image200.png")
        @professionnel = professionnel
        mail(to: @professionnel.email, subject: "You have received a notification !")
    end
end

notification.html.erb

<%= image_tag(attachments['image200.png'].url)%>

Hello <%= @professionnel.first_name %> !

Of course image200.png is present locally and remotely. And email is received in both cases, then my Amazon AWS SES setup is corrrect in both environments.. Not very sure where it breaks..

Body:
For Rails >= 4.2 to preview images you should create initializer:

# config/initializer/preview_interceptors.rb
ActionMailer::Base.register_preview_interceptor(ActionMailer::InlinePreviewInterceptor)


问:
Cannot resolve symbol R and can't solve it

I tried to solve this by trying solutions suggested in other questions but stil not able to get it. *
In the console I'am getting this message

Information:Gradle tasks [:app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]
Error:No resource identifier found for attribute 'roundIcon' in package 'android'
Error:No resource identifier found for attribute 'roundIcon' in package 'android'
Error:Execution failed for task ':app:processDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt
  Information:BUILD FAILED
  Information:Total time: 6.496 secs
  Information:3 errors
  Information:0 warnings
  Information:See complete output in console

and my build.gradle

```<code>android {
    compileSdkVersion 24
    buildToolsVersion '25.0.0'
    defaultConfig {
        applicationId smth
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.1'
    }
}

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.android.support:design:24.2.0'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.github.bumptech.glide:glide:3.6.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
</code>```

And for my MainActivity.java

```<code>import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

and for the manifest.xml

```<code>android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</code>```

答:
roundIcon is attributes in Android 8.0 (Oreo). If you want use roundIcon then so must change minSdkVersion and targetSdkVersion up to 25 in your app build.gradle.
And if you want support old version whose will need remove android:roundIcon and use android:icon for old version.
fix roundIcon in android 8.0

Body:
I tried to solve this by trying solutions suggested in other questions but stil not able to get it. *
In the console I'am getting this message

Information:Gradle tasks [:app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]
Error:No resource identifier found for attribute 'roundIcon' in package 'android'
Error:No resource identifier found for attribute 'roundIcon' in package 'android'
Error:Execution failed for task ':app:processDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt
  Information:BUILD FAILED
  Information:Total time: 6.496 secs
  Information:3 errors
  Information:0 warnings
  Information:See complete output in console

and my build.gradle

android {
    compileSdkVersion 24
    buildToolsVersion '25.0.0'
    defaultConfig {
        applicationId smth
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.1'
    }
}

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.android.support:design:24.2.0'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.github.bumptech.glide:glide:3.6.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

And for my MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

and for the manifest.xml

android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


问:
Printing from nested dictionary
How to print either 1 specific value, or a select key2 values for all key1 from a nested dictionary? The lines in my code display nothing.

Foe example, how to print (a single value):

```<code>Canon-PS-G7-X-Mark-II`
</code>```

or (select key2 values for all key1):

```<code>Canon-PS-G7-X-Mark-II
Nikon-D5
Sony-alpha9
</code>```

The dictionary (part of it) and code

```<code>config = {
    'g7': {},
    'd5': {},
    'a9': {},
}
config['g7']['cam_name'] = ('Canon-PS-G7-X-Mark-II')
config['d5']['cam_name'] = ('Nikon-D5')
config['a9']['cam_name'] = ('Sony-alpha9')

camtype = """
1 camera:
(config['g7']['cam_name'])

all cameras
(config[.]['cam_name'])

"""
print(camtype)
</code>```

答:
try below code:

```<code>config = {
'g7': {},
'd5': {},
'a9': {},
}
config['g7']['cam_name'] = ('Canon-PS-G7-X-Mark-II')
config['d5']['cam_name'] = ('Nikon-D5')
config['a9']['cam_name'] = ('Sony-alpha9')
camtype = """
1 camera:
({0})

all cameras
({1})

"""
single_camera = config['g7']['cam_name']
all_camera = ', '.join([config[k]['cam_name'] for k in config])
print(camtype.format(single_camera, all_camera))
</code>```

output:

```<code>1 camera:
(Canon-PS-G7-X-Mark-II)

all cameras
(['Canon-PS-G7-X-Mark-II', 'Nikon-D5', 'Sony-alpha9'])
</code>```

Title: Printing from nested dictionary

Body:
How to print either 1 specific value, or a select key2 values for all key1 from a nested dictionary? The lines in my code display nothing.

Foe example, how to print (a single value):

Canon-PS-G7-X-Mark-II`

or (select key2 values for all key1):

Canon-PS-G7-X-Mark-II
Nikon-D5
Sony-alpha9

The dictionary (part of it) and code

config = {
    'g7': {},
    'd5': {},
    'a9': {},
}
config['g7']['cam_name'] = ('Canon-PS-G7-X-Mark-II')
config['d5']['cam_name'] = ('Nikon-D5')
config['a9']['cam_name'] = ('Sony-alpha9')

camtype = """
1 camera:
(config['g7']['cam_name'])

all cameras
(config[.]['cam_name'])

"""
print(camtype)

Body:
try below code:

config = {
'g7': {},
'd5': {},
'a9': {},
}
config['g7']['cam_name'] = ('Canon-PS-G7-X-Mark-II')
config['d5']['cam_name'] = ('Nikon-D5')
config['a9']['cam_name'] = ('Sony-alpha9')
camtype = """
1 camera:
({0})

all cameras
({1})

"""
single_camera = config['g7']['cam_name']
all_camera = ', '.join([config[k]['cam_name'] for k in config])
print(camtype.format(single_camera, all_camera))

output:

1 camera:
(Canon-PS-G7-X-Mark-II)

all cameras
(['Canon-PS-G7-X-Mark-II', 'Nikon-D5', 'Sony-alpha9'])


问:
See what changed inside TextArea with on change listener
I need a textbox, where everytime the text changes, I know what exactly has changed. I'm currently using a JQuery's listener for changes in my input element, and what I do is:

When the text changes

Get the text from the box a1 and compare to what I have in box a2.

If there are changes, log them into output textarea

Here is a Sample https://codepen.io/nikolaevra/pen/eeWWbo

I'm currently using the following diff library https://github.com/kpdecker/jsdiff, and it has O(NM) efficiency, which is a lot.

Is there a way to get the exact change that was made to the textarea using JQuery or anything like that? For example, if I had test in both a1 and a2 and then changed a1 to be testing, I want to see ing as the change that was made.

EDIT:
I tried playing around with the method a little bit and this is one problem that I found. When I run diff = "testing".replace("test",''); => ing just as required, but when I try diff = "testing a potato cannon".replace("testing potato cannon",''); => testing a potato cannon, where I only changed one character. This is a lot of overhead that I wanted to avoid. In that case, I would only want to know where the value has been changed and what it has been changed to. Not the entire tail of the string.

答:
i hope this code will help you

This is the original text:

    <textarea id="a1" rows="4" cols="50" type="text"></textarea>

Change Text to something else here:

    <textarea id="a2" rows="4" cols="50" type="text"></textarea>

This are the changes that you made:

    <textarea rows="10" cols="100" id="output" for="title"></textarea>

```

Body:
i hope this code will help you

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
       $(document).ready(function () {
           var arr_text1 = new Array();
           var arr_text2 = new Array();
           var i=0;
           var text2nw="";
           $('#a2').on('input',function () {
               arr_text1 = $("#a1").val().split('');
               arr_text2 = $("#a2").val().split('');
               if (arr_text1[i] == arr_text2[i]) {
                              }
               else {
                   $('#output').val($("#a2").val().replace($("#a1").val(), ""));
                  // $('#output').val(text2nw);
               }
               if ($("#a2").val() != '') {
                   i++;
               }
               else {
                   i = 0;
                   $('#output').val('');
               }
           });
       });
   </script>
</head>
<body>

    <p>This is the original text:</p>
    <textarea id="a1" rows="4" cols="50" type="text"></textarea>

    <p>Change Text to something else here:</p>
    <textarea id="a2" rows="4" cols="50" type="text"></textarea>

    <p id="title">This are the changes that you made:</p>
    <textarea rows="10" cols="100" id="output" for="title"></textarea>

</body>
</html>


问:
c++ Genetic Algorithm Mutation error
I Have a problem with the mutation function within my genetic Algorithm. I can't quite see what I am doing wrong either. I've looked at this code for a while and I think the logic is correct, it's just not producing the results i want.

The problem
When i output the Binary array located in the Child Struct, If mutation has occured on any of the bits, then a random number will be changed, and not the one that should be.

for example

0000000 is the binary string

mutation has occured on the second
bit

0001000 would be the result

This section is located within the main.

```<code>for (int Child = 0; Child < ParentNumberInit; Child++)
{
    cout << endl;
    mutation(child[Child],Child);
}
</code>```

This is the mutation function

```<code>void mutation(struct Parent Child1,int childnumber)
{
    int mutation; // will be the random number generated

    cout << endl << "Child " << (childnumber+1) << endl;

    //loop through every bit in the binary string
    for (int z = 0; z < Binscale; z++)
    {
        mutation = 0;   // set mutation at 0 at the start of every loop
        mutation = rand()%100;      //create a random number

        cout << "Generated number = " << mutation << endl;

        //if variable mutation is smaller, mutation occurs
        if (mutation < MutationRate)
        {
            if(Child1.binary_code[z] == '0')
                Child1.binary_code[z] = '1';
            else if(Child1.binary_code[z] == '1')
                Child1.binary_code[z] = '0';
        }
    }
}
</code>```

It's being outputted in the main like this

```<code>    for (int childnumber = 0; childnumber < ParentNumberInit; childnumber++)
    {
        cout<<"Child "<<(childnumber+1)<<" Binary code = ";
        for (int z = 0; z < Binscale; z ++)
        {
        cout<<child[childnumber].binary_code[z];
        }
        cout<<endl;
     }
</code>```

答:
You can't throttle the multation rate this way. You need to separate the mutated bit from the probability of the mutation occuring.

```<code>for (int z = 0; z < Binscale; z++)
{
    if (rand() % 100 < MutationRate)
    {
        // flip bit
        Child1.binary_code[z] += 1;
        Child1.binary_code[z] %= 2;
    }
}
</code>```

Even simpler way to flip bit:

```<code>Child1.binary_code[z] ^= 1;
</code>```

ContentLicense: CC BY-SA 2.5

Title: c++ Genetic Algorithm Mutation error

Body:
I Have a problem with the mutation function within my genetic Algorithm. I can't quite see what I am doing wrong either. I've looked at this code for a while and I think the logic is correct, it's just not producing the results i want.

The problem
When i output the Binary array located in the Child Struct, If mutation has occured on any of the bits, then a random number will be changed, and not the one that should be.

for example

0000000 is the binary string

mutation has occured on the second
bit

0001000 would be the result

This section is located within the main.

for (int Child = 0; Child < ParentNumberInit; Child++)
{
    cout << endl;
    mutation(child[Child],Child);
}

This is the mutation function

void mutation(struct Parent Child1,int childnumber)
{
    int mutation; // will be the random number generated

    cout << endl << "Child " << (childnumber+1) << endl;

    //loop through every bit in the binary string
    for (int z = 0; z < Binscale; z++)
    {
        mutation = 0;   // set mutation at 0 at the start of every loop
        mutation = rand()%100;      //create a random number

        cout << "Generated number = " << mutation << endl;

        //if variable mutation is smaller, mutation occurs
        if (mutation < MutationRate)
        {
            if(Child1.binary_code[z] == '0')
                Child1.binary_code[z] = '1';
            else if(Child1.binary_code[z] == '1')
                Child1.binary_code[z] = '0';
        }
    }
}

It's being outputted in the main like this

    for (int childnumber = 0; childnumber < ParentNumberInit; childnumber++)
    {
        cout<<"Child "<<(childnumber+1)<<" Binary code = ";
        for (int z = 0; z < Binscale; z ++)
        {
        cout<<child[childnumber].binary_code[z];
        }
        cout<<endl;
     }

Body:
You can't throttle the multation rate this way. You need to separate the mutated bit from the probability of the mutation occuring.

for (int z = 0; z < Binscale; z++)
{
    if (rand() % 100 < MutationRate)
    {
        // flip bit
        Child1.binary_code[z] += 1;
        Child1.binary_code[z] %= 2;
    }
}

Even simpler way to flip bit:

Child1.binary_code[z] ^= 1;


问:
python selenium - selecting option from dropdown
I am attempting to use the below code to use selenium (python) to select an option from a dropdown on a webpage.

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

path_to_chromedriver = 'C:/Users/User_1/chromedriver/chromedriver'
browser = webdriver.Chrome(executable_path = path_to_chromedriver)

url = 'https://lifeinsurance.rac.com.au/rac/get-a-quote?productid=51'
browser.get(url)

wait = WebDriverWait(browser, 10)

# residence listbox
drop_down = browser.find_element_by_xpath('//*[@id="divApplicantDetails__1"]/div[8]/div/div[2]/span/span/span[1]')

browser.execute_script('arguments[0].style.display="inline";', drop_down)
wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="divApplicantDetails__1"]/div[8]/div/div[2]/span/span/span[1]')))

wait.until(EC.element_to_be_clickable((By.XPATH, r'//*[@id="ddResidentialStatusId__1_listbox"]/li[1]'))).click()
</code>```

There are occasions where it works (and an option from the dropdown is selected), but on other occasions an option from the dropdown is NOT selected (and no error raised either).

I would appreciate any feedback on how to consistently select an option from the dropdown noted in the code provided.

答:
I wouldn't try to manipulate the CSS of an element. Just approach it like a user would... click on the dropdown, click on an option. I used different locators but this worked for me.

```<code>driver.find_element_by_css_selector("span[aria-owns='ddResidentialStatusId__1_listbox']")).click()
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#ddResidentialStatusId__1_listbox > li")))
options = driver.find_elements_by_css_selector("#ddResidentialStatusId__1_listbox > li"))
options[0].click() # clicks "Australian citizen or permanent resident"
</code>```

python doesn't have visibilityOfAllElementsLocatedBy() like Java does so I had to wait for a single element, then get all of them, and then click the first one. If you really want to just click the first one, you can just do

```<code>wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#ddResidentialStatusId__1_listbox > li"))).click()
</code>```

and skip the last two lines of code. I left it as is because I'm assuming that you will want to (Jedi mind powers working on you) throw this in a function and select different options.

Body:
I am attempting to use the below code to use selenium (python) to select an option from a dropdown on a webpage.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

path_to_chromedriver = 'C:/Users/User_1/chromedriver/chromedriver'
browser = webdriver.Chrome(executable_path = path_to_chromedriver)

url = 'https://lifeinsurance.rac.com.au/rac/get-a-quote?productid=51'
browser.get(url)

wait = WebDriverWait(browser, 10)

# residence listbox
drop_down = browser.find_element_by_xpath('//*[@id="divApplicantDetails__1"]/div[8]/div/div[2]/span/span/span[1]')

browser.execute_script('arguments[0].style.display="inline";', drop_down)
wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="divApplicantDetails__1"]/div[8]/div/div[2]/span/span/span[1]')))

wait.until(EC.element_to_be_clickable((By.XPATH, r'//*[@id="ddResidentialStatusId__1_listbox"]/li[1]'))).click()

There are occasions where it works (and an option from the dropdown is selected), but on other occasions an option from the dropdown is NOT selected (and no error raised either).

I would appreciate any feedback on how to consistently select an option from the dropdown noted in the code provided.

Body:
I wouldn't try to manipulate the CSS of an element. Just approach it like a user would... click on the dropdown, click on an option. I used different locators but this worked for me.

driver.find_element_by_css_selector("span[aria-owns='ddResidentialStatusId__1_listbox']")).click()
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#ddResidentialStatusId__1_listbox > li")))
options = driver.find_elements_by_css_selector("#ddResidentialStatusId__1_listbox > li"))
options[0].click() # clicks "Australian citizen or permanent resident"

python doesn't have visibilityOfAllElementsLocatedBy() like Java does so I had to wait for a single element, then get all of them, and then click the first one. If you really want to just click the first one, you can just do

wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#ddResidentialStatusId__1_listbox > li"))).click()

and skip the last two lines of code. I left it as is because I'm assuming that you will want to (Jedi mind powers working on you) throw this in a function and select different options.


问:
md-option within md-select Angular Material 2.0.0 beta 10
Select All option for selecting all the values in md-option with in md-select. I am populating md-option by using ngFor and i am using formControl. I can see the checkboxes for all the md-option values. But I am not able to check all the checkboxes from typescript(.ts) file. How do put select all option?
I am trying control.setValue(arrayvalues); But it doesn't check the checkboxes.</p>

答:
I wrote [compareWith] = compareById(obj1, obj2) attribute for md-select in my HTML page and in the .ts file write the below method {compareById(obj1, obj2){ return obj1 = obj2.code}
}. It works for me.


问:
SpringBootTest cannot be resolved to a type
I have a simple Spring Boot project.
I'm using maven for dependency management.
The import for SpringBootTest is not recognised so I'm getting:

SpringBootTest cannot be resolved to a type

I can't figure out what the problem is with this.

Here's the pom.xml file:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.sample</groupId>
  <artifactId>SpringBootExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

答:
I faced the same trouble. I actually don't understand the actual problem as it will sound quite funny, but when I changed the version of "spring-boot-starter-parent" artifact from 1.5.8.RELEASE to 1.5.7.RELEASE, everything got back to perfect.

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.7.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
</code>```

Try and see what happens with you.

Body:
I have a simple Spring Boot project.
I'm using maven for dependency management.
The import for SpringBootTest is not recognised so I'm getting:

SpringBootTest cannot be resolved to a type

I can't figure out what the problem is with this.

Here's the pom.xml file:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.sample</groupId>
  <artifactId>SpringBootExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Body:
I faced the same trouble. I actually don't understand the actual problem as it will sound quite funny, but when I changed the version of "spring-boot-starter-parent" artifact from 1.5.8.RELEASE to 1.5.7.RELEASE, everything got back to perfect.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.7.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

Try and see what happens with you.


问:
count multiple strings in R, group by those strings
I have a data.frame like this:

```<code>Points      Assists      Steals
Player A    Player B     Player B
Player B    Player C     Player A
player C    Player C     Player A
</code>```

And I'm trying to get a data.frame output like this:

```<code>           Points     Assists      Steals
Player A    1          0            2
Player B    1          1            1
Player C    1          2            0
</code>```

As you can see, I want it to count the number of times that each player appears in each category. I'm able to do this for one column using table(), but can't figure out how to do it for multiple columns. How would I do this?

答:
We can gather into long format, get the count and spread to wide format

```<code>library(dplyr)
library(tidyr)
gather(df1) %>%
     count(key, value) %>%
     spread(key, n, fill = 0)
# A tibble: 3 x 4
#     value Assists Points Steals
#*    <chr>   <dbl>  <dbl>  <dbl>
#1 Player A       0      1      2
#2 Player B       1      1      1
#3 Player C       2      1      0
</code>```

Or we use melt with table

```<code>library(reshape2)
table(melt(as.matrix(df1))[3:2])
#         Var2
#value      Points Assists Steals
#  Player A      1       0      2
#  Player B      1       1      1
#  Player C      1       2      0
</code>```

data

```<code>df1 <- structure(list(Points = c("Player A", "Player B", "Player C"),
Assists = c("Player B", "Player C", "Player C"), Steals = c("Player B",
"Player A", "Player A")), .Names = c("Points", "Assists",
"Steals"), class = "data.frame", row.names = c(NA, -3L))
</code>```

Body:
I have a data.frame like this:

Points      Assists      Steals
Player A    Player B     Player B
Player B    Player C     Player A
player C    Player C     Player A

And I'm trying to get a data.frame output like this:

           Points     Assists      Steals
Player A    1          0            2
Player B    1          1            1
Player C    1          2            0

As you can see, I want it to count the number of times that each player appears in each category. I'm able to do this for one column using table(), but can't figure out how to do it for multiple columns. How would I do this?

Body:
We can gather into long format, get the count and spread to wide format

library(dplyr)
library(tidyr)
gather(df1) %>%
     count(key, value) %>%
     spread(key, n, fill = 0)
# A tibble: 3 x 4
#     value Assists Points Steals
#*    <chr>   <dbl>  <dbl>  <dbl>
#1 Player A       0      1      2
#2 Player B       1      1      1
#3 Player C       2      1      0

Or we use melt with table

library(reshape2)
table(melt(as.matrix(df1))[3:2])
#         Var2
#value      Points Assists Steals
#  Player A      1       0      2
#  Player B      1       1      1
#  Player C      1       2      0

data

df1 <- structure(list(Points = c("Player A", "Player B", "Player C"),
Assists = c("Player B", "Player C", "Player C"), Steals = c("Player B",
"Player A", "Player A")), .Names = c("Points", "Assists",
"Steals"), class = "data.frame", row.names = c(NA, -3L))


问:
how to separating the matching points in optical flow?
I'm using calcOpticalFlowPyrLK() function to track feature points. I'd like to separate matching only points from the results using the status vector resulted from calcOpticalFlowPyrLK().

The documentation from opencv page says,

output status vector (of unsigned chars); each element of the vector
  is set to 1 if the flow for the corresponding features has been found,
  otherwise, it is set to 0.

But when printed the status vector before implementation, I found that the status vector size is larger and 1s and 0s are scattered even after the array passes the size of feature points tracked.

If my tracked points vector size is 65, the status vector size is 100 and 1s and 0s are there even after status[64].

Will be help full if someone can help me out to get the right points only.

Thank You.

答:
In my implementation, I clear the nextPts and status vector before calcOpticalFlowPyrLK(). The size of prevPts, nextPts and status are exactly the same. If the data in status is 0, then the output flow is not valid.

```<code>vector<cv::Point2f> points_prev;
/* points_prev.push_back(some data) */
vector<cv::Point2f> points_next;
vector<uchar> status;
calcOpticalFlowPyrLK(img_prev, img_next, points_prev, points_next, status, err, winSize, 3, termcrit, 0, 0.001);
for (size_t i = 0; i < status.size(); i++)
{
    if(status.at(i) == 0)
        /*points_prev[i] is not valid*/
}
</code>```

Body:
In my implementation, I clear the nextPts and status vector before calcOpticalFlowPyrLK(). The size of prevPts, nextPts and status are exactly the same. If the data in status is 0, then the output flow is not valid.

vector<cv::Point2f> points_prev;
/* points_prev.push_back(some data) */
vector<cv::Point2f> points_next;
vector<uchar> status;
calcOpticalFlowPyrLK(img_prev, img_next, points_prev, points_next, status, err, winSize, 3, termcrit, 0, 0.001);
for (size_t i = 0; i < status.size(); i++)
{
    if(status.at(i) == 0)
        /*points_prev[i] is not valid*/
}


问:
Solution for previewing user changes and allowing rollback/commit over a period of time
I have asked a few questions today as I try to think through to the solution of a problem.

We have a complex data structure where all of the various entities are tightly interconnected, with almost all entities heavily reliant/dependant upon entities of other types.

The project is a website (MVC3, .NET 4), and all of the logic is implemented using LINQ-to-SQL (2008) in the business layer.

What we need to do is have a user "lock" the system while they make their changes (there are other reasons for this which I won't go into here that are not database related). While this user is making their changes we want to be able to show them the original state of entities which they are updating, as well as a "preview" of the changes they have made. When finished, they need to be able to rollback/commit.

We have considered these options:

Holding open a transaction for the length of time a user takes to make multiple changes stinks, so that's out.

Holding a copy of all the data in memory (or cached to disk) is an option but there is heck of a lot of it, so seems unreasonable.

Maintaining a set of secondary tables, or attempting to use session state to store changes, but this is  complex and difficult to maintain.

Using two databases, flipping between them by connection string, and using T-SQL to manage replication, putting them back in sync after commit/rollback. I.e. switching on/off, forcing snapshot, reversing direction etc.

We're a bit stumped for a solution that is relatively easy to maintain. Any suggestions?

答:
Use a set of secondary tables.

The problem is that your connection should see two versions of data while the other connections should see only one (or two, one of them being their own).

While it is possible theoretically and is implemented in Oracle using flashbacks, SQL Server does not support it natively, since it has no means to query previous versions of the records.

You can issue a query like this:

```<code>SELECT  *
FROM    mytable
AS OF TIMESTAMP
        TO_TIMESTAMP('2010-01-17')
</code>```

in Oracle but not in SQL Server.

This means that you need to implement this functionality yourself (placing the new versions of rows into your own tables).

Body:
Use a set of secondary tables.

The problem is that your connection should see two versions of data while the other connections should see only one (or two, one of them being their own).

While it is possible theoretically and is implemented in Oracle using flashbacks, SQL Server does not support it natively, since it has no means to query previous versions of the records.

You can issue a query like this:

SELECT  *
FROM    mytable
AS OF TIMESTAMP
        TO_TIMESTAMP('2010-01-17')

in Oracle but not in SQL Server.

This means that you need to implement this functionality yourself (placing the new versions of rows into your own tables).


问:
Load multiple js files all at once on ajax success - javascript
so right now I have this code. on ajax success it dynamically loads my js files. but my point here is.. is there any way where I can load them all at once without typing them one by one? by means like folder/*.js then it will load all js files inside that folder. here is my example code.

JS

```<code>$(document).ready(function() {
$(document).on("click", "a[rel=tab]", function(e) {
    // e.preventDefault();
    $e = $(e);
    pageurl = $(this).attr('href');
    $.ajax({
        url: pageurl + '?rel=tab',
        success: function(data) {

            var head = document.getElementsByTagName("head")[0];
            var jquery = document.createElement("script");
            jquery.type = "text/javascript";
            jquery.src = base_url + "/assets/bower_components/datatables.net/js/jquery.dataTables.min.js";
            head.appendChild(jquery);

            var js = document.createElement("script");
            js.type = "text/javascript";
            js.src = base_url + "/assets/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js";
            head.appendChild(js);

            var jsn = document.createElement("script");
            jsn.type = "text/javascript";
            jsn.src = base_url + "/assets/js/newscript.js";
            head.appendChild(jsn);
            jsn.onload = function() {
                $('#inside').html(data);
            }
        }
    });

    //to change the browser URL to 'pageurl'
    if (pageurl != window.location) {
        window.history.pushState({ path: pageurl }, '', pageurl);
    }
    return false;
});

$(window).bind('popstate', function() {
    $.ajax({
        url: location.pathname + '?rel=tab',
        success: function(data) {
            $('#inside').html(data);
        }
    });
});
});
</code>```

答:
Question is answered here with the following code:

```<code>const getScripts =
  resources => {
    jQuery.when.apply(
      null
      ,resources.map(
        resource =>
          $.getScript(base_url + resource)
        )
    )
;

getScripts(["url1","url2"])
.then(
  () => console.log("finished loading scripts")
  ,err => console.warn("Failed:",err)
);
</code>```

I think you need to rethink your design though, loading a bunch of scripts again. All you need is set some content through xhr (not a big fan of using xhr to request html parts) and initialize the content with script.

Instead of reloading all the scripts you should call a function that will initialize the content.

Body:
so right now I have this code. on ajax success it dynamically loads my js files. but my point here is.. is there any way where I can load them all at once without typing them one by one? by means like folder/*.js then it will load all js files inside that folder. here is my example code.

JS

$(document).ready(function() {
$(document).on("click", "a[rel=tab]", function(e) {
    // e.preventDefault();
    $e = $(e);
    pageurl = $(this).attr('href');
    $.ajax({
        url: pageurl + '?rel=tab',
        success: function(data) {

            var head = document.getElementsByTagName("head")[0];
            var jquery = document.createElement("script");
            jquery.type = "text/javascript";
            jquery.src = base_url + "/assets/bower_components/datatables.net/js/jquery.dataTables.min.js";
            head.appendChild(jquery);

            var js = document.createElement("script");
            js.type = "text/javascript";
            js.src = base_url + "/assets/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js";
            head.appendChild(js);

            var jsn = document.createElement("script");
            jsn.type = "text/javascript";
            jsn.src = base_url + "/assets/js/newscript.js";
            head.appendChild(jsn);
            jsn.onload = function() {
                $('#inside').html(data);
            }
        }
    });

    //to change the browser URL to 'pageurl'
    if (pageurl != window.location) {
        window.history.pushState({ path: pageurl }, '', pageurl);
    }
    return false;
});

$(window).bind('popstate', function() {
    $.ajax({
        url: location.pathname + '?rel=tab',
        success: function(data) {
            $('#inside').html(data);
        }
    });
});
});

Body:
Question is answered here with the following code:

const getScripts =
  resources => {
    jQuery.when.apply(
      null
      ,resources.map(
        resource =>
          $.getScript(base_url + resource)
        )
    )
;

getScripts(["url1","url2"])
.then(
  () => console.log("finished loading scripts")
  ,err => console.warn("Failed:",err)
);

I think you need to rethink your design though, loading a bunch of scripts again. All you need is set some content through xhr (not a big fan of using xhr to request html parts) and initialize the content with script.

Instead of reloading all the scripts you should call a function that will initialize the content.


问:
How to get only first 50 files from all subdirectories of a directory in Python?
I am trying to get first 50 .jpg files from different subdirectories of a particular directory. Till now, I have only succedded in getting the path name of all using the following list of commands:

```<code>import os
import os.path

for dirpath, dirnames, filenames in os.walk("."):
    for filename in [f for f in filenames if f.endswith(".jpg")]:
        print os.path.join(dirpath, filename)
</code>```

Can someone please tell as to how to extract only first 50 files from the subdirectories?

答:
Use os.listdir to list file and directories.

Use os.path.isdir to get directories.

The following code gets fullpath of 50 '.jpg's files in each subdirectories.

```<code>target_dir = os.path.abspath('.')

sub_dir_list = [os.path.join(target_dir, one_dir) for one_dir in os.listdir(target_dir) if
            os.path.isdir(os.path.join(target_dir, one_dir))]

img_file_list = []
for sub_dir in sub_dir_list:
    img_file_list.extend([one_file for one_file in os.listdir(sub_dir) if one_file.endswith('.jpg')][:50])
</code>```

Body:
I am trying to get first 50 .jpg files from different subdirectories of a particular directory. Till now, I have only succedded in getting the path name of all using the following list of commands:

import os
import os.path

for dirpath, dirnames, filenames in os.walk("."):
    for filename in [f for f in filenames if f.endswith(".jpg")]:
        print os.path.join(dirpath, filename)

Can someone please tell as to how to extract only first 50 files from the subdirectories?

Body:
Use os.listdir to list file and directories.

Use os.path.isdir to get directories.

The following code gets fullpath of 50 '.jpg's files in each subdirectories.

target_dir = os.path.abspath('.')

sub_dir_list = [os.path.join(target_dir, one_dir) for one_dir in os.listdir(target_dir) if
            os.path.isdir(os.path.join(target_dir, one_dir))]

img_file_list = []
for sub_dir in sub_dir_list:
    img_file_list.extend([one_file for one_file in os.listdir(sub_dir) if one_file.endswith('.jpg')][:50])


问:
Error when Installing Ethereum: Package 'ethereum' has no installation candidate
I am installing Ethereum on Ubuntu 17.10 following the steps in this article:
https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-2-30b3d335aa1f

But when executing the following command:

```<code>sudo apt-get install ethereum
</code>```

I get the following:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Package ethereum is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'ethereum' has no installation candidate
</code>```

答:
It seems that there is a compatibility issue with the last stable version of Ethereum and Ubuntu 17.10; and the latest unstable version could be installed with no issues:

```<code>sudo apt-get install ethereum-unstable
</code>```

However, this means that in the next stable version of Ethereum there will be no issues.

Body:
I am installing Ethereum on Ubuntu 17.10 following the steps in this article:
https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-2-30b3d335aa1f

But when executing the following command:

sudo apt-get install ethereum

I get the following:

Reading package lists... Done
Building dependency tree
Reading state information... Done
Package ethereum is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'ethereum' has no installation candidate

Body:
It seems that there is a compatibility issue with the last stable version of Ethereum and Ubuntu 17.10; and the latest unstable version could be installed with no issues:

sudo apt-get install ethereum-unstable

However, this means that in the next stable version of Ethereum there will be no issues.


问:
Call external code from JMeter webdriver sampler
I am using Webdriver sampler with JavaScript. Is it possible to use external code in a sampler? I have many samplers which use almost same code. I want to write this code in an external file and call the required methods (with appropriate arguments) in multiple samplers. If it is not possible then is there a way to call a sampler from within another sampler?</p>

答:
For example if you have foo.js file in JMeter's "bin" folder with the following function defined

```<code>    function hello() {
        WDS.log.info('Hello there')
    }
</code>```

You can just call load directive in your WebDriver Sampler code in order to import the aforementioned foo.js file lile:

```<code>load('foo.js')
</code>```

Full code:

```<code>load('foo.js') // import external file
WDS.sampleResult.sampleStart()
hello()  // call external function
WDS.browser.get('http://jmeter-plugins.org')
WDS.sampleResult.sampleEnd()
</code>```

Demo:

More information: The WebDriver Sampler: Your Top 10 Questions Answered

Body:
For example if you have foo.js file in JMeter's "bin" folder with the following function defined

    function hello() {
        WDS.log.info('Hello there')
    }

You can just call load directive in your WebDriver Sampler code in order to import the aforementioned foo.js file lile:

load('foo.js')

Full code:

load('foo.js') // import external file
WDS.sampleResult.sampleStart()
hello()  // call external function
WDS.browser.get('http://jmeter-plugins.org')
WDS.sampleResult.sampleEnd()

Demo:

More information: The WebDriver Sampler: Your Top 10 Questions Answered


问:
Minimum weight edge in all paths of a directed graph
Given a directed graph with edges having -ve or +ve weights, what is the algorithms to find the smallest weight edges of all paths from vertex s to vertes d? </p>

答: I would find all reachable from s, e.g. by depth first search. Then find all nodes that can reach d (equivalently, all nodes reachable from d in the graph with directions reversed). Now you want the smallest weight edges that start in the first set and end in the second set.</p>


问:
Why do I get "Error parsing HTTP request header" when POSTing a JSON string?
I am trying to send a POST request from browser to my server(local host). My request URL is :

```<code> http://localhost:8080/myPath/myServlet?requestData={  .......//Json String......};
</code>```

requestData is a json String (I am using GSON for the purpose.) Everything is working fine until the data in the json string exceeds a particular limit. Say, I am sending array of objects in the json string. If the number of objects in the list exceed 67 then I get following error :

```<code> AM org.apache.coyote.http11.AbstractHttp11Processor process
 INFO: Error parsing HTTP request header
 Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
</code>```

Why is this so? I am totally confused. Why does this happen and what needs to be done to fix this?
I want to understand the reason behind this, for I don't understand that after particular number of objects it suddenly stops working and I get this error in my console.

答:
I apologize for not answering questions seriously before.

1.Maybe it caused by special characters.You can get details from this url。https://bz.apache.org/bugzilla/show_bug.cgi?id=60594

solve it by：

```<code>encodeURIComponent(JSON.stringify(data))
</code>```

or change your tomcat version to 7.0.67 or lower.
According to developers's opinion, tomcat developers in the following versions set the option to allow |，{，}.
Get detail http://tomcat.apache.org/tomcat-8.0-doc/config/systemprops.html#Other

The new environment variable will be included in:
- trunk for 9.0.0.M18 onwards

8.5.x for 8.5.12 onwards

8.0.x for 8.0.42 onwards

7.0.x for 7.0.76 onwards2.

Another reason maybe that Request header is too large.You can solve this by modifying the server.xml.

```<code><Connector port="8080" maxHttpHeaderSize="8192" maxThreads="150"
    minSpareThreads="25" maxSpareThreads="75" enableLookups="false"
    redirectPort="8443" acceptCount="100" connectionTimeout="20000"
    disableUploadTimeout="true" />
</code>```

Hope it works for you！

ContentLicense: CC BY-SA 4.0

Body:
I am trying to send a POST request from browser to my server(local host). My request URL is :

 http://localhost:8080/myPath/myServlet?requestData={  .......//Json String......};

requestData is a json String (I am using GSON for the purpose.) Everything is working fine until the data in the json string exceeds a particular limit. Say, I am sending array of objects in the json string. If the number of objects in the list exceed 67 then I get following error :

 AM org.apache.coyote.http11.AbstractHttp11Processor process
 INFO: Error parsing HTTP request header
 Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.

Why is this so? I am totally confused. Why does this happen and what needs to be done to fix this?
I want to understand the reason behind this, for I don't understand that after particular number of objects it suddenly stops working and I get this error in my console.

Body:
I apologize for not answering questions seriously before.

1.Maybe it caused by special characters.You can get details from this url。https://bz.apache.org/bugzilla/show_bug.cgi?id=60594

solve it by：

encodeURIComponent(JSON.stringify(data))

or change your tomcat version to 7.0.67 or lower.
According to developers's opinion, tomcat developers in the following versions set the option to allow |，{，}.
Get detail http://tomcat.apache.org/tomcat-8.0-doc/config/systemprops.html#Other

The new environment variable will be included in:
- trunk for 9.0.0.M18 onwards

8.5.x for 8.5.12 onwards

8.0.x for 8.0.42 onwards

7.0.x for 7.0.76 onwards2.

Another reason maybe that Request header is too large.You can solve this by modifying the server.xml.

<Connector port="8080" maxHttpHeaderSize="8192" maxThreads="150"
    minSpareThreads="25" maxSpareThreads="75" enableLookups="false"
    redirectPort="8443" acceptCount="100" connectionTimeout="20000"
    disableUploadTimeout="true" />

Hope it works for you！


问:
declare variable inside or outside a loop, does it make big difference?
for example

```<code>int i, a, c, d; // these vars will only be used in while
while(bigNumber--) {
    i = doSomething();
    // **

}
</code>```

and

```<code>while(bigNumber--) {
   int i, a, b, c; // i'd like to put it here for readability
   i = doSomething();
   // **
}
</code>```

Does it make big difference in terms of performance?

答:
Yes. scope of variable i is different in both cases.

In first case, A variable i declared in a block or function. So, you can access it in the block or function.

In the second case, A variable I declared in a while loop. So, you can access it in while loop only.

Does it make big difference in terms of performance?

No, it will not matter performance-wise where you declare it.

For example 1:

```<code>int main()
{
    int i, bigNumber;

    while(bigNumber--) {
        i = 0;
    }
}
</code>```

Assembly:

```<code>main:
  push rbp
  mov rbp, rsp
.L3:
  mov eax, DWORD PTR [rbp-4]
  lea edx, [rax-1]
  mov DWORD PTR [rbp-4], edx
  test eax, eax
  setne al
  test al, al
  je .L2
  mov DWORD PTR [rbp-8], 0
  jmp .L3
.L2:
  mov eax, 0
  pop rbp
  ret
</code>```

Example 2:

```<code>int main()
{
    int bigNumber;

    while(bigNumber--) {
        int i;
        i = 0;
    }
}
</code>```

Assembly:

```<code>main:
  push rbp
  mov rbp, rsp
.L3:
  mov eax, DWORD PTR [rbp-4]
  lea edx, [rax-1]
  mov DWORD PTR [rbp-4], edx
  test eax, eax
  setne al
  test al, al
  je .L2
  mov DWORD PTR [rbp-8], 0
  jmp .L3
.L2:
  mov eax, 0
  pop rbp
  ret
</code>```

Both generate the same assembly code.

Body:
for example

int i, a, c, d; // these vars will only be used in while
while(bigNumber--) {
    i = doSomething();
    // **

}

and

while(bigNumber--) {
   int i, a, b, c; // i'd like to put it here for readability
   i = doSomething();
   // **
}

Does it make big difference in terms of performance?

Body:
Yes. scope of variable i is different in both cases.

In first case, A variable i declared in a block or function. So, you can access it in the block or function.

In the second case, A variable I declared in a while loop. So, you can access it in while loop only.

Does it make big difference in terms of performance?

No, it will not matter performance-wise where you declare it.

For example 1:

int main()
{
    int i, bigNumber;

    while(bigNumber--) {
        i = 0;
    }
}

Assembly:

main:
  push rbp
  mov rbp, rsp
.L3:
  mov eax, DWORD PTR [rbp-4]
  lea edx, [rax-1]
  mov DWORD PTR [rbp-4], edx
  test eax, eax
  setne al
  test al, al
  je .L2
  mov DWORD PTR [rbp-8], 0
  jmp .L3
.L2:
  mov eax, 0
  pop rbp
  ret

Example 2:

int main()
{
    int bigNumber;

    while(bigNumber--) {
        int i;
        i = 0;
    }
}

Assembly:

main:
  push rbp
  mov rbp, rsp
.L3:
  mov eax, DWORD PTR [rbp-4]
  lea edx, [rax-1]
  mov DWORD PTR [rbp-4], edx
  test eax, eax
  setne al
  test al, al
  je .L2
  mov DWORD PTR [rbp-8], 0
  jmp .L3
.L2:
  mov eax, 0
  pop rbp
  ret

Both generate the same assembly code.


问:
Parsing issue warning with JSON
I'm trying to read JSON data from a website. I'm using Dev C++ on Windows 10 with a mingw compiler. This is a JSON parser from a tutorial I'm trying to run in a static project:

```<code>#define CURL_STATICLIB
#include <cstdint>
#include <iostream>
#include <memory>
#include <string>
#include <sstream>

#include "curl.h"
#include "json.h"

namespace
{
    std::size_t callback(
            const char* in,
            std::size_t size,
            std::size_t num,
            std::string* out)
    {
        const std::size_t totalBytes(size * num);
        out->append(in, totalBytes);
        return totalBytes;
    }
}

int main()
{
    const std::string url("http://date.jsontest.com/");

    CURL* curl = curl_easy_init();

    // Set remote URL.
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

    // Don't bother trying IPv6, which would increase DNS resolution time.
    curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

    // Don't wait forever, time out after 10 seconds.
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);

    // Follow HTTP redirects if necessary.
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

    // Response information.
    int httpCode(0);
    // std::unique_ptr<std::string> httpData(new std::string());

    std::stringstream httpData;

    // Hook up data handling function.
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);

    // Hook up data container (will be passed as the last parameter to the
    // callback handling function).  Can be any pointer type, since it will
    // internally be passed as a void pointer.
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &httpData);

    // Run our HTTP GET command, capture the HTTP response code, and clean up.
    curl_easy_perform(curl);
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
    curl_easy_cleanup(curl);

    if (httpCode == 200)
    {
        std::cout << "\nGot successful response from " << url << std::endl;

        // Response looks good - done using Curl now.  Try to parse the results
        // and print them out.
        Json::Value jsonData;
        Json::CharReaderBuilder jsonReader;
        std::string errs;

        if (Json::parseFromStream(jsonReader, httpData, &jsonData, &errs))
            // jsonReader.parse(httpData, jsonData))
        {
            std::cout << "Successfully parsed JSON data" << std::endl;
            std::cout << "\nJSON data received:" << std::endl;
            std::cout << jsonData.toStyledString() << std::endl;

            const std::string dateString(jsonData["date"].asString());
            const std::size_t unixTimeMs(
                    jsonData["milliseconds_since_epoch"].asUInt64());
            const std::string timeString(jsonData["time"].asString());

            std::cout << "Natively parsed:" << std::endl;
            std::cout << "\tDate string: " << dateString << std::endl;
            std::cout << "\tUnix timeMs: " << unixTimeMs << std::endl;
            std::cout << "\tTime string: " << timeString << std::endl;
            std::cout << std::endl;
        }
        else
        {
            std::cout << "Could not parse HTTP data as JSON" << std::endl;
            std::cout << "HTTP data was:\n" << httpData.str() << std::endl;
            return 1;
        }
    }
    else
    {
        std::cout << "Couldn't GET from " << url << " - exiting" << std::endl;
        return 1;
    }

    return 0;
}
</code>```

And this is the error I've been getting:

[Warning] 'Reader' is deprecated  (declared at
  C:/Users/me/Downloads/jsoncpp-master/jsoncpp-master/include/json/reader.h:35):
  | Use CharReader and CharReaderBuilder instead
  [-Wdeprecated-declarations]

I figured the syntax was older, thus I swapped the object's terms for the recommended ones. Now I'm getting this error:
This was my corrected block:

```<code>Json::Value jsonData;
Json::CharReaderBuilder CharReader;

if (CharReader.parse(*httpData, jsonData))
</code>```

And this is the new error:

error: 'class Json::CharReaderBuilder' has no member named 'parse'
           if (CharReader.parse(*httpData, jsonData))

The above code corrects this. The particular issue has been corrected.
However, due to a library issue, this is my new errors when compiling.

```<code>g++.exe main.o -o CurlProject1.exe -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -L"C:/Users/me/Downloads/curl-7.56.1-win64-mingw/lib" -static-libgcc -L"C:/Users/me/Downloads/curl-7.56.1-win64-mingw/lib" ../../Downloads/curl-7.56.1-win64-mingw/lib/libcurl.a ../../Downloads/curl-7.56.1-win64-mingw/lib/libcurl.dll.a

main.o:main.cpp:(.text+0x207): undefined reference to `Json::Value::Value(Json::ValueType)'
main.o:main.cpp:(.text+0x213): undefined reference to `Json::CharReaderBuilder::CharReaderBuilder()'
main.o:main.cpp:(.text+0x242): undefined reference to `Json::parseFromStream(Json::CharReader::Factory const&, std::istream&, Json::Value*, std::string*)'
main.o:main.cpp:(.text+0x2a1): undefined reference to `Json::Value::toStyledString() const'
main.o:main.cpp:(.text+0x2e8): undefined reference to `Json::Value::operator[](char const*)'
</code>```

答:
Try this:

```<code>#include <sstream>

...

    std::stringstream httpData;
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &httpData);

...

        Json::Value jsonData;
        Json::CharReaderBuilder jsonReader;
        std::string errs;
        if (Json::parseFromStream(jsonReader, httpData, &jsonData, &errs))
...

            std::cout << "HTTP data was:\n" << httpData.str() << std::endl;
</code>```

The complete code:

```<code>#define CURL_STATICLIB
#include <cstdint>
#include <iostream>
#include <memory>
#include <string>
#include <sstream>

#include "curl.h"
#include "json.h"

namespace
{
    std::size_t callback(
            const char* in,
            std::size_t size,
            std::size_t num,
            char* out)
    {
        std::string data(in, (std::size_t) size * num);
        *((std::stringstream*) out) << data;
        return size * num;
    }
}

int main()
{
    const std::string url("http://date.jsontest.com/");

    CURL* curl = curl_easy_init();

    // Set remote URL.
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

    // Don't bother trying IPv6, which would increase DNS resolution time.
    curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

    // Don't wait forever, time out after 10 seconds.
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);

    // Follow HTTP redirects if necessary.
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

    // Response information.
    int httpCode(0);
    // std::unique_ptr<std::string> httpData(new std::string());

    std::stringstream httpData;

    // Hook up data handling function.
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);

    // Hook up data container (will be passed as the last parameter to the
    // callback handling function).  Can be any pointer type, since it will
    // internally be passed as a void pointer.
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &httpData);

    // Run our HTTP GET command, capture the HTTP response code, and clean up.
    curl_easy_perform(curl);
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
    curl_easy_cleanup(curl);

    if (httpCode == 200)
    {
        std::cout << "\nGot successful response from " << url << std::endl;

        // Response looks good - done using Curl now.  Try to parse the results
        // and print them out.
        Json::Value jsonData;
        Json::CharReaderBuilder jsonReader;
        std::string errs;

        if (Json::parseFromStream(jsonReader, httpData, &jsonData, &errs))
            // jsonReader.parse(httpData, jsonData))
        {
            std::cout << "Successfully parsed JSON data" << std::endl;
            std::cout << "\nJSON data received:" << std::endl;
            std::cout << jsonData.toStyledString() << std::endl;

            const std::string dateString(jsonData["date"].asString());
            const std::size_t unixTimeMs(
                    jsonData["milliseconds_since_epoch"].asUInt64());
            const std::string timeString(jsonData["time"].asString());

            std::cout << "Natively parsed:" << std::endl;
            std::cout << "\tDate string: " << dateString << std::endl;
            std::cout << "\tUnix timeMs: " << unixTimeMs << std::endl;
            std::cout << "\tTime string: " << timeString << std::endl;
            std::cout << std::endl;
        }
        else
        {
            std::cout << "Could not parse HTTP data as JSON" << std::endl;
            std::cout << "HTTP data was:\n" << httpData.str() << std::endl;
            return 1;
        }
    }
    else
    {
        std::cout << "Couldn't GET from " << url << " - exiting" << std::endl;
        return 1;
    }

    return 0;
}
</code>```

Results:

```<code>Got successful response from http://date.jsontest.com/
Successfully parsed JSON data

JSON data received:
{
    "date" : "11-14-2017",
    "milliseconds_since_epoch" : 1510699420942,
    "time" : "10:43:40 PM"
}

Natively parsed:
    Date string: 11-14-2017
    Unix timeMs: 1510699420942
    Time string: 10:43:40 PM
</code>```

Title: Parsing issue warning with JSON

Body:
I'm trying to read JSON data from a website. I'm using Dev C++ on Windows 10 with a mingw compiler. This is a JSON parser from a tutorial I'm trying to run in a static project:

#define CURL_STATICLIB
#include <cstdint>
#include <iostream>
#include <memory>
#include <string>
#include <sstream>

#include "curl.h"
#include "json.h"

namespace
{
    std::size_t callback(
            const char* in,
            std::size_t size,
            std::size_t num,
            std::string* out)
    {
        const std::size_t totalBytes(size * num);
        out->append(in, totalBytes);
        return totalBytes;
    }
}

int main()
{
    const std::string url("http://date.jsontest.com/");

    CURL* curl = curl_easy_init();

    // Set remote URL.
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

    // Don't bother trying IPv6, which would increase DNS resolution time.
    curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

    // Don't wait forever, time out after 10 seconds.
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);

    // Follow HTTP redirects if necessary.
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

    // Response information.
    int httpCode(0);
    // std::unique_ptr<std::string> httpData(new std::string());

    std::stringstream httpData;

    // Hook up data handling function.
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);

    // Hook up data container (will be passed as the last parameter to the
    // callback handling function).  Can be any pointer type, since it will
    // internally be passed as a void pointer.
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &httpData);

    // Run our HTTP GET command, capture the HTTP response code, and clean up.
    curl_easy_perform(curl);
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
    curl_easy_cleanup(curl);

    if (httpCode == 200)
    {
        std::cout << "\nGot successful response from " << url << std::endl;

        // Response looks good - done using Curl now.  Try to parse the results
        // and print them out.
        Json::Value jsonData;
        Json::CharReaderBuilder jsonReader;
        std::string errs;

        if (Json::parseFromStream(jsonReader, httpData, &jsonData, &errs))
            // jsonReader.parse(httpData, jsonData))
        {
            std::cout << "Successfully parsed JSON data" << std::endl;
            std::cout << "\nJSON data received:" << std::endl;
            std::cout << jsonData.toStyledString() << std::endl;

            const std::string dateString(jsonData["date"].asString());
            const std::size_t unixTimeMs(
                    jsonData["milliseconds_since_epoch"].asUInt64());
            const std::string timeString(jsonData["time"].asString());

            std::cout << "Natively parsed:" << std::endl;
            std::cout << "\tDate string: " << dateString << std::endl;
            std::cout << "\tUnix timeMs: " << unixTimeMs << std::endl;
            std::cout << "\tTime string: " << timeString << std::endl;
            std::cout << std::endl;
        }
        else
        {
            std::cout << "Could not parse HTTP data as JSON" << std::endl;
            std::cout << "HTTP data was:\n" << httpData.str() << std::endl;
            return 1;
        }
    }
    else
    {
        std::cout << "Couldn't GET from " << url << " - exiting" << std::endl;
        return 1;
    }

    return 0;
}

And this is the error I've been getting:

[Warning] 'Reader' is deprecated  (declared at
  C:/Users/me/Downloads/jsoncpp-master/jsoncpp-master/include/json/reader.h:35):
  | Use CharReader and CharReaderBuilder instead
  [-Wdeprecated-declarations]

I figured the syntax was older, thus I swapped the object's terms for the recommended ones. Now I'm getting this error:
This was my corrected block:

Json::Value jsonData;
Json::CharReaderBuilder CharReader;

if (CharReader.parse(*httpData, jsonData))

And this is the new error:

error: 'class Json::CharReaderBuilder' has no member named 'parse'
           if (CharReader.parse(*httpData, jsonData))

The above code corrects this. The particular issue has been corrected.
However, due to a library issue, this is my new errors when compiling.

g++.exe main.o -o CurlProject1.exe -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -L"C:/Users/me/Downloads/curl-7.56.1-win64-mingw/lib" -static-libgcc -L"C:/Users/me/Downloads/curl-7.56.1-win64-mingw/lib" ../../Downloads/curl-7.56.1-win64-mingw/lib/libcurl.a ../../Downloads/curl-7.56.1-win64-mingw/lib/libcurl.dll.a

main.o:main.cpp:(.text+0x207): undefined reference to `Json::Value::Value(Json::ValueType)'
main.o:main.cpp:(.text+0x213): undefined reference to `Json::CharReaderBuilder::CharReaderBuilder()'
main.o:main.cpp:(.text+0x242): undefined reference to `Json::parseFromStream(Json::CharReader::Factory const&, std::istream&, Json::Value*, std::string*)'
main.o:main.cpp:(.text+0x2a1): undefined reference to `Json::Value::toStyledString() const'
main.o:main.cpp:(.text+0x2e8): undefined reference to `Json::Value::operator[](char const*)'

Body:
Try this:

#include <sstream>

...

    std::stringstream httpData;
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &httpData);

...

        Json::Value jsonData;
        Json::CharReaderBuilder jsonReader;
        std::string errs;
        if (Json::parseFromStream(jsonReader, httpData, &jsonData, &errs))
...

            std::cout << "HTTP data was:\n" << httpData.str() << std::endl;

The complete code:

#define CURL_STATICLIB
#include <cstdint>
#include <iostream>
#include <memory>
#include <string>
#include <sstream>

#include "curl.h"
#include "json.h"

namespace
{
    std::size_t callback(
            const char* in,
            std::size_t size,
            std::size_t num,
            char* out)
    {
        std::string data(in, (std::size_t) size * num);
        *((std::stringstream*) out) << data;
        return size * num;
    }
}

int main()
{
    const std::string url("http://date.jsontest.com/");

    CURL* curl = curl_easy_init();

    // Set remote URL.
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

    // Don't bother trying IPv6, which would increase DNS resolution time.
    curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

    // Don't wait forever, time out after 10 seconds.
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);

    // Follow HTTP redirects if necessary.
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

    // Response information.
    int httpCode(0);
    // std::unique_ptr<std::string> httpData(new std::string());

    std::stringstream httpData;

    // Hook up data handling function.
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);

    // Hook up data container (will be passed as the last parameter to the
    // callback handling function).  Can be any pointer type, since it will
    // internally be passed as a void pointer.
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &httpData);

    // Run our HTTP GET command, capture the HTTP response code, and clean up.
    curl_easy_perform(curl);
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
    curl_easy_cleanup(curl);

    if (httpCode == 200)
    {
        std::cout << "\nGot successful response from " << url << std::endl;

        // Response looks good - done using Curl now.  Try to parse the results
        // and print them out.
        Json::Value jsonData;
        Json::CharReaderBuilder jsonReader;
        std::string errs;

        if (Json::parseFromStream(jsonReader, httpData, &jsonData, &errs))
            // jsonReader.parse(httpData, jsonData))
        {
            std::cout << "Successfully parsed JSON data" << std::endl;
            std::cout << "\nJSON data received:" << std::endl;
            std::cout << jsonData.toStyledString() << std::endl;

            const std::string dateString(jsonData["date"].asString());
            const std::size_t unixTimeMs(
                    jsonData["milliseconds_since_epoch"].asUInt64());
            const std::string timeString(jsonData["time"].asString());

            std::cout << "Natively parsed:" << std::endl;
            std::cout << "\tDate string: " << dateString << std::endl;
            std::cout << "\tUnix timeMs: " << unixTimeMs << std::endl;
            std::cout << "\tTime string: " << timeString << std::endl;
            std::cout << std::endl;
        }
        else
        {
            std::cout << "Could not parse HTTP data as JSON" << std::endl;
            std::cout << "HTTP data was:\n" << httpData.str() << std::endl;
            return 1;
        }
    }
    else
    {
        std::cout << "Couldn't GET from " << url << " - exiting" << std::endl;
        return 1;
    }

    return 0;
}

Results:

Got successful response from http://date.jsontest.com/
Successfully parsed JSON data

JSON data received:
{
    "date" : "11-14-2017",
    "milliseconds_since_epoch" : 1510699420942,
    "time" : "10:43:40 PM"
}

Natively parsed:
    Date string: 11-14-2017
    Unix timeMs: 1510699420942
    Time string: 10:43:40 PM


问:
CodeIgniter removing index.php from url
My current urls look like this [mysite]index.php/[rest of the slug].

I want to strip index.php from these urls.

mod_rewrite is enabled on my apache2 server. In config, $config['index_page'] = '';

My codeignitor root .htaccess file contains,

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
</code>```

But still it is not working. Where am I going wrong?

答:
Well these all answers are good but for a newbie(which is do first time) these are confusing. There are other htaccess files which is reside in controller but we have to edit or add the htaccess in main project folder.

This is your codeigniter folder, where file resides like application,system,assets,uploads etc.

```<code>Your_project_folder/
application/
assets/
cgi-bin/
system/
.htaccess---->(Edit this file if not exist than create it)
index.php
</code>```

Change this file as written below:

```<code><IfModule mod_rewrite.c>
  RewriteEngine On
  # !IMPORTANT! Set your RewriteBase here and don't forget trailing and leading
  #  slashes.
  # If your page resides at http://www.example.com/mypage/test1
  # then use RewriteBase /mypage/test1/
  # Otherwise /
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
  # If we don't have mod_rewrite installed, all 404's
  # can be sent to index.php, and everything works as normal.
  # Submitted by: Anand Pandey
  ErrorDocument 404 /index.php
</IfModule>
</code>```

and yes of course you need to change two lines of code in the application/config/config.php

```<code>//find the below code
$config['index_page'] = "index.php";
$config['uri_protocol'] ="AUTO"
//replace with the below code
$config['index_page'] = "";
$config['uri_protocol'] = "REQUEST_URI";
</code>```

Title: CodeIgniter removing index.php from url

Body:
My current urls look like this [mysite]index.php/[rest of the slug].

I want to strip index.php from these urls.

mod_rewrite is enabled on my apache2 server. In config, $config['index_page'] = '';

My codeignitor root .htaccess file contains,

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]

But still it is not working. Where am I going wrong?

Body:
Well these all answers are good but for a newbie(which is do first time) these are confusing. There are other htaccess files which is reside in controller but we have to edit or add the htaccess in main project folder.

This is your codeigniter folder, where file resides like application,system,assets,uploads etc.

Your_project_folder/
application/
assets/
cgi-bin/
system/
.htaccess---->(Edit this file if not exist than create it)
index.php

Change this file as written below:

<IfModule mod_rewrite.c>
  RewriteEngine On
  # !IMPORTANT! Set your RewriteBase here and don't forget trailing and leading
  #  slashes.
  # If your page resides at http://www.example.com/mypage/test1
  # then use RewriteBase /mypage/test1/
  # Otherwise /
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
  # If we don't have mod_rewrite installed, all 404's
  # can be sent to index.php, and everything works as normal.
  # Submitted by: Anand Pandey
  ErrorDocument 404 /index.php
</IfModule>

and yes of course you need to change two lines of code in the application/config/config.php

//find the below code
$config['index_page'] = "index.php";
$config['uri_protocol'] ="AUTO"
//replace with the below code
$config['index_page'] = "";
$config['uri_protocol'] = "REQUEST_URI";


问:
Better way to secure REST resources in Spring?
I have a RESTful service that exposes resources like /user/{id}

Now, the user can provide the credentials, get the token and access the resource. However, once authenticated, the user can access the resources for any id.

Meaning, user1 can access the URIs like /user/1 as well as user/2 and so on. I ended up using a Principal in the controller methods and started checking the id of the Principal with the id the user is trying to access.

Further, the user has multiple resources associated with it. Say, user1 owns res1 and res2, user2 owns res3 and res4. These can be accessed via /user/1/res/2. I need a way where I can prevent /user/1/res/3 as res3 is owned by user1 and not user2.

But I believe that this problem is very common and I am not really convinced with my solution.

Is there a better way to deal with this problem?

Thanks

答:
You should not be exposing resourse /user/{id} at all if you all user can do is access only their own ID.
If I understand correctly, just exposing /user is enough, find ID of user from Principal or session etc and return result.

If you really want to do it, you can have custom implementation of @PreAuthorize. Got this code from a blog.

```<code>@PreAuthorize("isUsersRes(#id)")
@RequestMapping(method = RequestMethod.GET, value = "/users/{id}")
public UsersfindById(@PathVariable long id) {
return Users.findOne(id);
}
</code>```

public class CustomMethodSecurityExpressionRoot
  extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {

```<code>public CustomMethodSecurityExpressionRoot(Authentication authentication) {
    super(authentication);
}
</code>```

And implemenation of isUsersRes

```<code>public class CustomMethodSecurityExpressionRoot
extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {
public boolean isMember(Long OrganizationId) {
 //user logic
}
</code>```

Check complete blog here

Body:
You should not be exposing resourse /user/{id} at all if you all user can do is access only their own ID.
If I understand correctly, just exposing /user is enough, find ID of user from Principal or session etc and return result.

If you really want to do it, you can have custom implementation of @PreAuthorize. Got this code from a blog.

@PreAuthorize("isUsersRes(#id)")
@RequestMapping(method = RequestMethod.GET, value = "/users/{id}")
public UsersfindById(@PathVariable long id) {
return Users.findOne(id);
}

public class CustomMethodSecurityExpressionRoot
  extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {

public CustomMethodSecurityExpressionRoot(Authentication authentication) {
    super(authentication);
}

And implemenation of isUsersRes

public class CustomMethodSecurityExpressionRoot
extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {
public boolean isMember(Long OrganizationId) {
 //user logic
}

Check complete blog here