答:
I think the problem when you get user with usernaem, after that you get another user, please use firt getted user and everything should work.</p>

```<code>public function loginSubmit() {

    $user = User::where('username', Input::get('username'))->first();
    if (!$user) {
        $validator->messages()->add('username', 'Invalid login or password.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

 //   $user = User::where('is_disabled', 0)->first(); //why you get one more user here you should use $user above. , remove this line
    if ($user->is_disabled == 1) {
        $validator->messages()->add('username', 'User not found.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $user->last_login = \Carbon\Carbon::now();
    $user->save();
    Session::put('user', ['user_id' => $user->user_id]);

    return Redirect::to('/');
}
</code>```

Title: Restrict login if user is disabled in Laravel not working quite well

Body:
I think the problem when you get user with usernaem, after that you get another user, please use firt getted user and everything should work.

public function loginSubmit() {

    $user = User::where('username', Input::get('username'))->first();
    if (!$user) {
        $validator->messages()->add('username', 'Invalid login or password.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

 //   $user = User::where('is_disabled', 0)->first(); //why you get one more user here you should use $user above. , remove this line
    if ($user->is_disabled == 1) {
        $validator->messages()->add('username', 'User not found.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $user->last_login = \Carbon\Carbon::now();
    $user->save();
    Session::put('user', ['user_id' => $user->user_id]);

    return Redirect::to('/');
}


来源: stackexchange

问:
How to tell Electron packager to use my custom electron config file?
I successfully run my Angular 2 app via electron from app root folder. I build the app into dist folder by running:

```<code>ng build --env=prod
</code>```

and then I just run:

```<code>electron electron.conf.js
</code>```

Where in electron.conf.js I run local webserver to serve files from dist

```<code>connect().use(serveStatic(__dirname + '/dist')).listen(8997, function(){
    console.log('Webserver for electron is running on port 8997...');
});
mainWindow.loadURL('http://localhost:8997');
</code>```

I need this approach because I use gapi.js which will not initialize from file:/// protocol and needs http(s).

This works well, but I struggle to successfully launch the electron app when I package it as Windows .exe file. When I make the exe package as following (from app root dir):

```<code>electron-packager . MyAppName --platform=win32 --arch=x64
</code>```

and then launch the MyApp.exe, it fails with:

```<code>Cannot find module MyApp/resources/app/index.js
</code>```

It seems like electron running via electron-packager is trying serve the app via default file:// protocol (while all the files are actually in MyApp/resources/app/dist/index.js and should be served via http).

How can I tell electron-packager to use my electron.conf.js which will launch my local webserver?

答:
so, the whole trick is to add index.js file to the root project directory and the index.js is meant to inlude the electron app conf, e.g.:

```<code>const electron = require('electron')
var app = electron.app;
app.on('ready', function () {
    mainWindow = new BrowserWindow({ width: 1200, height: 900 });
    mainWindow.loadURL('my-url-here');
})
</code>```

after bunding the app with electron-packager, this index.js is copied to resources/app/index.js and used as electron load config when the .exe is launched.

ContentLicense: CC BY-SA 3.0

Body:
I successfully run my Angular 2 app via electron from app root folder. I build the app into dist folder by running:

ng build --env=prod

and then I just run:

electron electron.conf.js

Where in electron.conf.js I run local webserver to serve files from dist

connect().use(serveStatic(__dirname + '/dist')).listen(8997, function(){
    console.log('Webserver for electron is running on port 8997...');
});
mainWindow.loadURL('http://localhost:8997');

I need this approach because I use gapi.js which will not initialize from file:/// protocol and needs http(s).

This works well, but I struggle to successfully launch the electron app when I package it as Windows .exe file. When I make the exe package as following (from app root dir):

electron-packager . MyAppName --platform=win32 --arch=x64

and then launch the MyApp.exe, it fails with:

Cannot find module MyApp/resources/app/index.js

It seems like electron running via electron-packager is trying serve the app via default file:// protocol (while all the files are actually in MyApp/resources/app/dist/index.js and should be served via http).

How can I tell electron-packager to use my electron.conf.js which will launch my local webserver?

Body:
so, the whole trick is to add index.js file to the root project directory and the index.js is meant to inlude the electron app conf, e.g.:

const electron = require('electron')
var app = electron.app;
app.on('ready', function () {
    mainWindow = new BrowserWindow({ width: 1200, height: 900 });
    mainWindow.loadURL('my-url-here');
})

after bunding the app with electron-packager, this index.js is copied to resources/app/index.js and used as electron load config when the .exe is launched.


问:
How to send Firebase message to specific application in project?
I have a doubt based on firebase. It allows to add multiple application for a single project. I have added App1, App2 and App3. How can I send a  notification to App1 alone? Server key is the same for those 3 apps.</p>

答:
In the Notifications panel in the Firebase Console, you can send a notification message to a specific app. But there is no support for such targeting in the Firebase Cloud Messaging API.

You can easily emulate the behavior though, by defining a specific property for each of your apps: /topics/apps-app1, /topics/apps-app2, etc. Then have each app subscribe to its own topic and you can target the users of each app with a single FCM server key.


问:
Send Mail Function is not working in laravel 5.3
I have a send mail function in CommonHelper like

```<code>   public static function send_plain_email($data){
   $contact_email = CommonHelper::$admin_info['contact_email'];
   $data['subject']= 'contact us';

  Mail::send('emails.'.'plain_email', $data, function($message) use ($data , $contact_email) {
    $message->from($data['email']);
    $message->subject($data['subject']);
    $message->to($contact_email);
    if(!empty($attachment)){
      $message->attach($attachment);
    }
  });
}
</code>```

The data array is coming in this function but Mail::send function giving the following error

```<code> {
 "success": false,
 "message": "Undefined variable: data"
 }
</code>```

Which part of the code i am missing here ? any ideas ?

答:
check if your blade file have the blade naming extension at the back as follow: file_name.blade.php

Before that i forgot add .blade file extension behind the file name which show as file_name.php it could not detect any variable been sent to the blade.

To display specific data use the following format: {{ $merchant->name }}

Hope this help.

Body:
I have a send mail function in CommonHelper like

   public static function send_plain_email($data){
   $contact_email = CommonHelper::$admin_info['contact_email'];
   $data['subject']= 'contact us';

  Mail::send('emails.'.'plain_email', $data, function($message) use ($data , $contact_email) {
    $message->from($data['email']);
    $message->subject($data['subject']);
    $message->to($contact_email);
    if(!empty($attachment)){
      $message->attach($attachment);
    }
  });
}

The data array is coming in this function but Mail::send function giving the following error

 {
 "success": false,
 "message": "Undefined variable: data"
 }

Which part of the code i am missing here ? any ideas ?


问:
How to know when dd has finished
I have a issue with the dd comand. I use it in a while like this:

```<code>while c=$(dd count=1000 bs=1 2>/dev/null) ;do

    echo -n "$c" > /dev/ttyO5
done < $FILE
</code>```

And it works like charm, the only problem is that once the file is read completely, it doesnt stop the while, it stays there stalled. How could I make the while to stop once the dd read all the file?

BTW: Note my machine is embed linux, it doesnt have all the comands and tools as a normal ubuntu machine would have.

Thanks

Output dd --version

```<code>BusyBox v1.20.2 (MUSE) multi-call binary.

Usage: dd [if=FILE] [of=FILE] [bs=N] [count=N] [skip=N]
        [seek=N]

Copy a file with converting and formatting

        if=FILE         Read from FILE instead of stdin
        of=FILE         Write to FILE instead of stdout
        bs=N            Read and write N bytes at a time
        count=N         Copy only N input blocks
        skip=N          Skip N input blocks
        seek=N          Skip N output blocks

Numbers may be suffixed by c (x1), w (x2), b (x512), kD (x1000), k (x1024),
MD (x1000000), M (x1048576), GD (x1000000000) or G (x1073741824)
</code>```

答:
Note

'\0' will be lost after assigning to a variable.

'\\' may keep its special meaning depending on version of echo : try echo '\n'

Status can be retrieved reading from stderr

```<code>dd count=1000 bs=1 </dev/null
0+0 records in
0+0 records out
</code>```

So

```<code>while
    c=$(dd ... 2>errorfile);
    read line <errorfile;   # read the first line of error
    [[ $line != 0+0* ]];    # break while if line begins with 0+0
do
    ...
done
</code>```

It's slightly different from checking from length of c

```<code>c=$(dd count=1 bs=1 </dev/null)
echo "${#c}"

c=$(dd count=1 bs=1 <<<$'\0')
echo "${#c}"
</code>```

because in the last case a NUL character was read whereas in the previous no character were read.

EDIT: following demonstrates that it works but is very slow :

```<code>for x in {{0..9},{a..f}}{{0..9},{a..f}}; do printf "\x$x"; done |
while
    c=$(dd count=1 bs=1 2>errfile;echo .); c=${c%.}
    read line <errfile
    [[ $line != 0+0* ]]
do
    if [[ $c = '' ]]; then printf "\0"; else echo -n -E "$c"; fi
done | od -c
</code>```

Title: How to know when dd has finished

Body:
I have a issue with the dd comand. I use it in a while like this:

while c=$(dd count=1000 bs=1 2>/dev/null) ;do

    echo -n "$c" > /dev/ttyO5
done < $FILE

And it works like charm, the only problem is that once the file is read completely, it doesnt stop the while, it stays there stalled. How could I make the while to stop once the dd read all the file?

BTW: Note my machine is embed linux, it doesnt have all the comands and tools as a normal ubuntu machine would have.

Thanks

Output dd --version

BusyBox v1.20.2 (MUSE) multi-call binary.

Usage: dd [if=FILE] [of=FILE] [bs=N] [count=N] [skip=N]
        [seek=N]

Copy a file with converting and formatting

        if=FILE         Read from FILE instead of stdin
        of=FILE         Write to FILE instead of stdout
        bs=N            Read and write N bytes at a time
        count=N         Copy only N input blocks
        skip=N          Skip N input blocks
        seek=N          Skip N output blocks

Numbers may be suffixed by c (x1), w (x2), b (x512), kD (x1000), k (x1024),
MD (x1000000), M (x1048576), GD (x1000000000) or G (x1073741824)

Body:
Note

'\0' will be lost after assigning to a variable.

'\\' may keep its special meaning depending on version of echo : try echo '\n'

Status can be retrieved reading from stderr

dd count=1000 bs=1 </dev/null
0+0 records in
0+0 records out

So

while
    c=$(dd ... 2>errorfile);
    read line <errorfile;   # read the first line of error
    [[ $line != 0+0* ]];    # break while if line begins with 0+0
do
    ...
done

It's slightly different from checking from length of c

c=$(dd count=1 bs=1 </dev/null)
echo "${#c}"

c=$(dd count=1 bs=1 <<<$'\0')
echo "${#c}"

because in the last case a NUL character was read whereas in the previous no character were read.

EDIT: following demonstrates that it works but is very slow :

for x in {{0..9},{a..f}}{{0..9},{a..f}}; do printf "\x$x"; done |
while
    c=$(dd count=1 bs=1 2>errfile;echo .); c=${c%.}
    read line <errfile
    [[ $line != 0+0* ]]
do
    if [[ $c = '' ]]; then printf "\0"; else echo -n -E "$c"; fi
done | od -c


问:
String array initialization as constructor parameter
In Java, it is completely legal to initialize a String array in the following way:

```<code>String[] s = {"FOO", "BAR"};
</code>```

However, when trying to instantiate a class that takes a String array as a parameter, the following piece of code is NOT allowed:

```<code>Test t = new Test({"test"});
</code>```

But this works again:

```<code>Test t = new Test(new String[] {"test"});
</code>```

Can someone explain why this is?

答:
```<code>String[] s = {"FOO", "BAR"};
</code>```

this is allowed at declaration time only

You can't

```<code>String[] s;
s={"FOO", "BAR"};
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In Java, it is completely legal to initialize a String array in the following way:

String[] s = {"FOO", "BAR"};

However, when trying to instantiate a class that takes a String array as a parameter, the following piece of code is NOT allowed:

Test t = new Test({"test"});

But this works again:

Test t = new Test(new String[] {"test"});

Can someone explain why this is?

Body:
String[] s = {"FOO", "BAR"};

this is allowed at declaration time only

You can't

String[] s;
s={"FOO", "BAR"};


问:
How to do a real-time dashboard with charting
I want to create a dashboard for a bespoke web service we have so that we can monitor usage on a real-time basis. Something similar to the couchbase dashboard if you have seen that. If not, its basically a line graph that scrolls right to left with time along the bottom of the graph and usage on the y-axis.

To minimise data bandwidth I am assuming there is a way to pass just the changed data to update a graph rather than sending a new image/vector each time. And this would get drawn with a javascript charting library.

What I am unclear on is how to get the data from the server. Is the normal approach to have the javascript code poll the server using AJAX every second (if you are after second by second updates) or is some other method used?

I used PHP for the back end and HTML/JS for the client end.

And does anyone have any examples or links that could be helpful.

答:
For getting the data from the backend, I think you can call it using Ajax, reload each second using setInterval(), making something looks like:

```<code>setInterval(function() {
   $.ajax({
        url: url of your backend server,
        type: 'GET',
        success: function (data) {
           //data returned from the server, use it to draw your chart
        }
      });
}, 1000); // recall ajax every second
</code>```

Body:
For getting the data from the backend, I think you can call it using Ajax, reload each second using setInterval(), making something looks like:

setInterval(function() {
   $.ajax({
        url: url of your backend server,
        type: 'GET',
        success: function (data) {
           //data returned from the server, use it to draw your chart
        }
      });
}, 1000); // recall ajax every second


问:
Firebase, Digits Authentication Error, Activity Destroyed issue
I am trying to login via Firebase and facing a weird issue. I can successfully login on all devices except some Samsung devices. While Debugging I found issue at:

```<code>package com.apponative.committeeapp.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.apponative.committeeapp.R;
import com.apponative.committeeapp.datamodles.User;
import com.apponative.committeeapp.firebase.FireBaseDbHandler;
import com.apponative.committeeapp.utils.CommitteeCallBack;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.digits.sdk.android.AuthCallback;
import com.digits.sdk.android.AuthConfig;
import com.digits.sdk.android.Digits;
import com.digits.sdk.android.DigitsException;
import com.digits.sdk.android.DigitsSession;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class SplashActivity extends Activity
        implements CommitteeCallBack.FireBaseAuthCallBack, GoogleApiClient.OnConnectionFailedListener, AuthCallback {

    private int screenTag;
    private User user;
    private ImageView progressBar;

    // Firebase

    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    AuthConfig.Builder builder = new AuthConfig.Builder();
    AuthConfig authConfig;

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

        fireBaseDigitsAuth();
    }

    void fireBaseDigitsAuth() {

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

                if (firebaseAuth.getCurrentUser() != null) {

                }
            }
        };

        mAuth = FirebaseAuth.getInstance();
        builder.withAuthCallBack(this);
        authConfig = builder.build();

        if (mAuth.getCurrentUser() != null) {
            FireBaseDbHandler.getDbHandler(this).userProfileCheck(mAuth.getCurrentUser().getEmail().split("@")[0]);
        } else {
            Digits.authenticate(authConfig);
        }
    }

    public void signUpNewUser(final String email, String password) {
        mAuth.createUserWithEmailAndPassword(email + getString(R.string.firebase_domain), password)
                .addOnCompleteListener(SplashActivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            FireBaseDbHandler.getDbHandler(SplashActivity.this).userProfileCheck(email);
                        }
                    }
                });
    }

    public void signInExistingUser(final String email, final String password) {
        mAuth.signInWithEmailAndPassword(email + getString(R.string.firebase_domain), password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (!task.isSuccessful()) {
                            signUpNewUser(email, password);
                        } else {
                            FireBaseDbHandler.getDbHandler(SplashActivity.this).userProfileCheck(email);
                        }
                    }
                });
    }

    void startMainActivity(int itemId, User user) {
//        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//        if (user != null) {
//            intent.putExtra("userId", user.getUserId());
//            intent.putExtra("userName", user.getUsername());
//        }
//        intent.putExtra("itemId", itemId);
//        startActivity(intent);
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
      //  finish();
    }

    @Override
    public void SignInSuccess(User user) {
        progressBar.setVisibility(View.GONE);
        this.user = user;
        this.screenTag = R.string.tag_home;
         startMainActivity(screenTag, user);
    }

    @Override
    public void NewUserRegisteration() {
        progressBar.setVisibility(View.GONE);
        this.user = null;
        this.screenTag = R.string.tag_setprofile;
        startMainActivity(screenTag, user);
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void success(DigitsSession session, String phoneNumber) {
        signInExistingUser(phoneNumber, phoneNumber);
    }

    @Override
    public void failure(DigitsException error) {
        error.printStackTrace();
    }
}
</code>```

It throws error as below:

```<code>Process: com.apponative.committeeapp, PID: 28641
                                                                             java.lang.IllegalStateException: Activity has been destroyed
                                                                                at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1455)
                                                                                at android.app.BackStackRecord.commitInternal(BackStackRecord.java:687)
                                                                                at android.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:667)
                                                                                at com.google.android.gms.internal.zzaay.zzt(Unknown Source)
                                                                                at com.google.android.gms.internal.zzaaw.zzc(Unknown Source)
                                                                                at com.google.android.gms.internal.zzaaw.zzs(Unknown Source)
                                                                                at com.google.android.gms.tasks.zzh$zza.zzw(Unknown Source)
                                                                                at com.google.android.gms.tasks.zzh.addOnCompleteListener(Unknown Source)
                                                                                at com.apponative.committeeapp.ui.SplashActivity.signInExistingUser(SplashActivity.java:115)
                                                                                at com.apponative.committeeapp.ui.SplashActivity.success(SplashActivity.java:209)
                                                                                at com.digits.sdk.android.WeakAuthCallback.success(WeakAuthCallback.java:32)
                                                                                at com.digits.sdk.android.LoginResultReceiver.onReceiveResult(LoginResultReceiver.java:64)
                                                                                at android.os.ResultReceiver$MyResultReceiver.send(ResultReceiver.java:59)
                                                                                at android.os.ResultReceiver.send(ResultReceiver.java:93)
                                                                                at com.digits.sdk.android.DigitsControllerImpl$1.run(DigitsControllerImpl.java:178)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7325)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
</code>```

I am not switching any fragment, it is a simple activity. I am confirming mobile number via Twitter Digits sdk prior to login. It works fine. I get crash only once right after confirmation via Digits. Relaunching app that does not send Digits confirmation runs smooth.

I wonder if Digits is doing some trouble with that. While debugging I have found that Twitter Digits startPhoneNumberActivity
with flags Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP. What I assume these flags are destroying previous activity.

I have already tried following with this activity but no use:

```<code>android:persistent="true"
android:noHistory="false"
</code>```

Build.gradle:

```<code>buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
    maven { url 'https://maven.fabric.io/public' }
    maven { url "https://jitpack.io" }
}

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.---------"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        configurations.all {
            resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
        }

        dexOptions {
            javaMaxHeapSize "4g"
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        targetCompatibility JavaVersion.VERSION_1_7
        sourceCompatibility JavaVersion.VERSION_1_7
    }
}

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.digits.sdk.android:digits:2.0.6@aar') {
        transitive = true;
    }
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.google.firebase:firebase-auth:10.0.1'
    compile 'com.google.firebase:firebase-database:10.0.1'
    compile 'com.android.support:design:25.3.1'

    compile 'com.google.firebase:firebase-storage:10.0.1'

    compile 'com.firebaseui:firebase-ui-storage:1.1.1'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
        transitive = true;
    }
    compile 'com.android.support:multidex:1.0.1'
}

apply plugin: 'com.google.gms.google-services'
</code>```

答:
FLAG_ACTIVITY_CLEAR_TOP is the problem here which kills the activity.

calling the Fabric.with(this, new TwitterCore(authConfig), new Digits()); in the onCreate() activity method can solve the problem for you.

Body:
I am trying to login via Firebase and facing a weird issue. I can successfully login on all devices except some Samsung devices. While Debugging I found issue at:

package com.apponative.committeeapp.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.apponative.committeeapp.R;
import com.apponative.committeeapp.datamodles.User;
import com.apponative.committeeapp.firebase.FireBaseDbHandler;
import com.apponative.committeeapp.utils.CommitteeCallBack;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.digits.sdk.android.AuthCallback;
import com.digits.sdk.android.AuthConfig;
import com.digits.sdk.android.Digits;
import com.digits.sdk.android.DigitsException;
import com.digits.sdk.android.DigitsSession;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class SplashActivity extends Activity
        implements CommitteeCallBack.FireBaseAuthCallBack, GoogleApiClient.OnConnectionFailedListener, AuthCallback {

    private int screenTag;
    private User user;
    private ImageView progressBar;

    // Firebase

    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    AuthConfig.Builder builder = new AuthConfig.Builder();
    AuthConfig authConfig;

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

        fireBaseDigitsAuth();
    }

    void fireBaseDigitsAuth() {

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

                if (firebaseAuth.getCurrentUser() != null) {

                }
            }
        };

        mAuth = FirebaseAuth.getInstance();
        builder.withAuthCallBack(this);
        authConfig = builder.build();

        if (mAuth.getCurrentUser() != null) {
            FireBaseDbHandler.getDbHandler(this).userProfileCheck(mAuth.getCurrentUser().getEmail().split("@")[0]);
        } else {
            Digits.authenticate(authConfig);
        }
    }

    public void signUpNewUser(final String email, String password) {
        mAuth.createUserWithEmailAndPassword(email + getString(R.string.firebase_domain), password)
                .addOnCompleteListener(SplashActivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            FireBaseDbHandler.getDbHandler(SplashActivity.this).userProfileCheck(email);
                        }
                    }
                });
    }

    public void signInExistingUser(final String email, final String password) {
        mAuth.signInWithEmailAndPassword(email + getString(R.string.firebase_domain), password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (!task.isSuccessful()) {
                            signUpNewUser(email, password);
                        } else {
                            FireBaseDbHandler.getDbHandler(SplashActivity.this).userProfileCheck(email);
                        }
                    }
                });
    }

    void startMainActivity(int itemId, User user) {
//        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//        if (user != null) {
//            intent.putExtra("userId", user.getUserId());
//            intent.putExtra("userName", user.getUsername());
//        }
//        intent.putExtra("itemId", itemId);
//        startActivity(intent);
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
      //  finish();
    }

    @Override
    public void SignInSuccess(User user) {
        progressBar.setVisibility(View.GONE);
        this.user = user;
        this.screenTag = R.string.tag_home;
         startMainActivity(screenTag, user);
    }

    @Override
    public void NewUserRegisteration() {
        progressBar.setVisibility(View.GONE);
        this.user = null;
        this.screenTag = R.string.tag_setprofile;
        startMainActivity(screenTag, user);
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void success(DigitsSession session, String phoneNumber) {
        signInExistingUser(phoneNumber, phoneNumber);
    }

    @Override
    public void failure(DigitsException error) {
        error.printStackTrace();
    }
}

It throws error as below:

Process: com.apponative.committeeapp, PID: 28641
                                                                             java.lang.IllegalStateException: Activity has been destroyed
                                                                                at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1455)
                                                                                at android.app.BackStackRecord.commitInternal(BackStackRecord.java:687)
                                                                                at android.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:667)
                                                                                at com.google.android.gms.internal.zzaay.zzt(Unknown Source)
                                                                                at com.google.android.gms.internal.zzaaw.zzc(Unknown Source)
                                                                                at com.google.android.gms.internal.zzaaw.zzs(Unknown Source)
                                                                                at com.google.android.gms.tasks.zzh$zza.zzw(Unknown Source)
                                                                                at com.google.android.gms.tasks.zzh.addOnCompleteListener(Unknown Source)
                                                                                at com.apponative.committeeapp.ui.SplashActivity.signInExistingUser(SplashActivity.java:115)
                                                                                at com.apponative.committeeapp.ui.SplashActivity.success(SplashActivity.java:209)
                                                                                at com.digits.sdk.android.WeakAuthCallback.success(WeakAuthCallback.java:32)
                                                                                at com.digits.sdk.android.LoginResultReceiver.onReceiveResult(LoginResultReceiver.java:64)
                                                                                at android.os.ResultReceiver$MyResultReceiver.send(ResultReceiver.java:59)
                                                                                at android.os.ResultReceiver.send(ResultReceiver.java:93)
                                                                                at com.digits.sdk.android.DigitsControllerImpl$1.run(DigitsControllerImpl.java:178)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7325)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

I am not switching any fragment, it is a simple activity. I am confirming mobile number via Twitter Digits sdk prior to login. It works fine. I get crash only once right after confirmation via Digits. Relaunching app that does not send Digits confirmation runs smooth.

I wonder if Digits is doing some trouble with that. While debugging I have found that Twitter Digits startPhoneNumberActivity
with flags Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP. What I assume these flags are destroying previous activity.

I have already tried following with this activity but no use:

android:persistent="true"
android:noHistory="false"

Build.gradle:

buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
    maven { url 'https://maven.fabric.io/public' }
    maven { url "https://jitpack.io" }
}

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.---------"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        configurations.all {
            resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
        }

        dexOptions {
            javaMaxHeapSize "4g"
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        targetCompatibility JavaVersion.VERSION_1_7
        sourceCompatibility JavaVersion.VERSION_1_7
    }
}

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.digits.sdk.android:digits:2.0.6@aar') {
        transitive = true;
    }
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.google.firebase:firebase-auth:10.0.1'
    compile 'com.google.firebase:firebase-database:10.0.1'
    compile 'com.android.support:design:25.3.1'

    compile 'com.google.firebase:firebase-storage:10.0.1'

    compile 'com.firebaseui:firebase-ui-storage:1.1.1'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
        transitive = true;
    }
    compile 'com.android.support:multidex:1.0.1'
}

apply plugin: 'com.google.gms.google-services'


问:
Weighted accuracy for image segmentation using FCN
I have built a FCN for image segmentation. The object to be segmented is only very few pixels relatively to the image size (1024x1024). This results in that the accuracy is very high, even if I only train with 10 images instead of 18000 (my full training set).

My approach to solve this is to use some kind of weighted accuracy, so that the accuracy actually say something about the performance of identifying the small object (now it gets high accuracy since so many pixels are not the object and by not classifying anything the accuracy still gets high).

How do I decide the weight, anybody with some experience?

答:
You can use infogain loss layer for a "weighted" loss.

The infogain loss is a generalization of the cross entropy loss commonly used. It is defined using a weight matrix H (of size L-by-L, where L is the number of classes):

```<code>L(p) = -H log(p)
</code>```

Where p is a vector of class probabilities.

You can find more details on this loss here.

Body:
You can use infogain loss layer for a "weighted" loss.

The infogain loss is a generalization of the cross entropy loss commonly used. It is defined using a weight matrix H (of size L-by-L, where L is the number of classes):

L(p) = -H log(p)

Where p is a vector of class probabilities.

You can find more details on this loss here.


问:
PHP count cell data based on name
I've been doing a manual report for a while  on some data from a form and it's got quite excessive with the amount of data i'm getting now, it was 50 entries at first and now its over 500 so I need to find an easier way to manage it. I thought that a PHP program may make this easier.

Basically i have data like below, I need to sort by user and count how many leads each user has.

Columns

Username | Lead Source

Pete M, Lead 1

Fiona L, Lead 2

bare in mind that this csv file is quite large, I was wondering if anyone had a easier way to resolve this than me doing a manual excel formula.

many thanks,

答:
I realise the question was regarding PHP but as I suggested VBScript I thought the following might be useful if you were to opt for vbscript to format the reports. Years ago I had to format a report that would often take over an hour and as the source data changed would need to be run again - so I used vbscript and cut the time down to minutes ( the vb was far more complicated than this )

I know the formatting below looks odd, there is no block comment in vbscript so a single quote is used. Anyway, hope it may give you a starting point.

I think I would be tempted to use a Scripting Dictionary to maintain the count of leads for each user found. Useful guide to scripting dictionary

```<code>OPTION EXPLICIT
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8

'
Const XLS_SOURCEFILE="C:\data\spreadsheet.xls"

call processxls( 1, 2, XLS_SOURCEFILE, "Sheet1")

'
' the general idea is that you supply a column index ( iKeyCol )
' and so long as there is something in that cell for each row
' the script will run ( until it hits an empty cell )
'
' the `iKeyRow` is the row to start on - if you have column headers etc
' then after that row perhaps
'
' If you set the 3rd parameter to NULL when calling the sub you will be prompted to browse for the file to use.
'
'
'
'
Sub processxls( iKeyCol, iKeyRow, filename, sheetname )
    Dim oExcel
    Dim oXLWrkBook
    Dim oXLSheet

    Dim strFilename
    Dim r: r = iKeyRow

    '*** Get the source file ***
    strFilename=getfile( filename )

    '*** Abandon if no sourcefile ***
    If( strFilename=FALSE ) Then
        Call KillObjects()
        MsgBox "Cancelled"
        Exit Sub
    End If

    '*** Create the excel object ***
    Set oExcel = CreateObject("Excel.Application")
    oExcel.Visible = True
    oExcel.DisplayAlerts = True

    Set oXLWrkBook = oExcel.Workbooks.Open(strFilename)
    Set oXLSheet = oXLWrkBook.Worksheets(sheetname)

    oXLSheet.Activate

    Do While oXLSheet.Cells( r, iKeyCol ).value <> ""
        On Error Resume Next

        '*** here is where you process your data in whatever manner you need
        data=oXLSheet.Cells( r, iKeyCol ).value

        ' increment row counter - otherwise boom!
        r=r+1
    loop

    oXLWrkBook.Save
    oExcel.Quit

    Call KillObjects()

    MsgBox "All operations completed"
End Sub

Function getfile( explicitpath )
    if( isNull( explicitpath ) or explicitpath=false )then
        Dim oShell:Set oShell = CreateObject( "WScript.Shell" )
        If ( GetOSVersion() <= 5 ) Then
            '*** Win XP & similar ***

            Dim defaultLocalDir: defaultLocalDir = oShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Desktop"
            Set oShell = Nothing

            Set cd = CreateObject("UserAccounts.CommonDialog")
            cd.InitialDir = initialDir
            cd.Filter = "All Files|*.*"
            cd.FilterIndex = 1

            If cd.ShowOpen = True Then
                getfile = cd.FileName
            Else
                getfile = ""
            End If

            Set cd = Nothing

        Else
            '*** Vista onwards ***
            Dim oExec:Set oExec = oShell.Exec( "mshta.exe ""about: <input type=file id=file><script>file.click();new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(X.value);close();resizeTo(0,0);</script>""" )
            getfile = Replace( oExec.StdOut.ReadAll, vbCRLF, "" )
            Set oExec = Nothing
        End If
    else
        getfile=explicitpath
    end if

    Set oShell = Nothing
End Function

Function GetOSVersion()
    Dim oItem
    Dim oWMI:Set oWMI = GetObject("winmgmts:\\.\root\CIMV2")
    Dim Items:Set Items = oWMI.ExecQuery("SELECT * FROM Win32_OperatingSystem",,48)
    For Each oItem in Items
        GetOSVersion = split( oItem.Version, "." )(0)
    Next
End Function

Sub KillObjects()
    If IsObject(oExcel) Then Set oExcel=nothing
    If IsObject(oXLWrkBook) Then Set oXLWrkBook=nothing
    If IsObject(oXLSheet) Then Set oXLSheet=nothing
    If IsObject(oWMI) Then Set oWMI=nothing
End Sub
</code>```

Title: PHP count cell data based on name

Body:
I realise the question was regarding PHP but as I suggested VBScript I thought the following might be useful if you were to opt for vbscript to format the reports. Years ago I had to format a report that would often take over an hour and as the source data changed would need to be run again - so I used vbscript and cut the time down to minutes ( the vb was far more complicated than this )

I know the formatting below looks odd, there is no block comment in vbscript so a single quote is used. Anyway, hope it may give you a starting point.

I think I would be tempted to use a Scripting Dictionary to maintain the count of leads for each user found. Useful guide to scripting dictionary

OPTION EXPLICIT
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8

'
Const XLS_SOURCEFILE="C:\data\spreadsheet.xls"

call processxls( 1, 2, XLS_SOURCEFILE, "Sheet1")

'
' the general idea is that you supply a column index ( iKeyCol )
' and so long as there is something in that cell for each row
' the script will run ( until it hits an empty cell )
'
' the `iKeyRow` is the row to start on - if you have column headers etc
' then after that row perhaps
'
' If you set the 3rd parameter to NULL when calling the sub you will be prompted to browse for the file to use.
'
'
'
'
Sub processxls( iKeyCol, iKeyRow, filename, sheetname )
    Dim oExcel
    Dim oXLWrkBook
    Dim oXLSheet

    Dim strFilename
    Dim r: r = iKeyRow

    '*** Get the source file ***
    strFilename=getfile( filename )

    '*** Abandon if no sourcefile ***
    If( strFilename=FALSE ) Then
        Call KillObjects()
        MsgBox "Cancelled"
        Exit Sub
    End If

    '*** Create the excel object ***
    Set oExcel = CreateObject("Excel.Application")
    oExcel.Visible = True
    oExcel.DisplayAlerts = True

    Set oXLWrkBook = oExcel.Workbooks.Open(strFilename)
    Set oXLSheet = oXLWrkBook.Worksheets(sheetname)

    oXLSheet.Activate

    Do While oXLSheet.Cells( r, iKeyCol ).value <> ""
        On Error Resume Next

        '*** here is where you process your data in whatever manner you need
        data=oXLSheet.Cells( r, iKeyCol ).value

        ' increment row counter - otherwise boom!
        r=r+1
    loop

    oXLWrkBook.Save
    oExcel.Quit

    Call KillObjects()

    MsgBox "All operations completed"
End Sub

Function getfile( explicitpath )
    if( isNull( explicitpath ) or explicitpath=false )then
        Dim oShell:Set oShell = CreateObject( "WScript.Shell" )
        If ( GetOSVersion() <= 5 ) Then
            '*** Win XP & similar ***

            Dim defaultLocalDir: defaultLocalDir = oShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Desktop"
            Set oShell = Nothing

            Set cd = CreateObject("UserAccounts.CommonDialog")
            cd.InitialDir = initialDir
            cd.Filter = "All Files|*.*"
            cd.FilterIndex = 1

            If cd.ShowOpen = True Then
                getfile = cd.FileName
            Else
                getfile = ""
            End If

            Set cd = Nothing

        Else
            '*** Vista onwards ***
            Dim oExec:Set oExec = oShell.Exec( "mshta.exe ""about: <input type=file id=file><script>file.click();new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(X.value);close();resizeTo(0,0);</script>""" )
            getfile = Replace( oExec.StdOut.ReadAll, vbCRLF, "" )
            Set oExec = Nothing
        End If
    else
        getfile=explicitpath
    end if

    Set oShell = Nothing
End Function

Function GetOSVersion()
    Dim oItem
    Dim oWMI:Set oWMI = GetObject("winmgmts:\\.\root\CIMV2")
    Dim Items:Set Items = oWMI.ExecQuery("SELECT * FROM Win32_OperatingSystem",,48)
    For Each oItem in Items
        GetOSVersion = split( oItem.Version, "." )(0)
    Next
End Function

Sub KillObjects()
    If IsObject(oExcel) Then Set oExcel=nothing
    If IsObject(oXLWrkBook) Then Set oXLWrkBook=nothing
    If IsObject(oXLSheet) Then Set oXLSheet=nothing
    If IsObject(oWMI) Then Set oWMI=nothing
End Sub


问:
c/c++ - How to write an array of boolean value into a text file?
I have a very big array of boolean values, and I want to write it to a .txt file.

I tried fwrite() and when I use cat command to print the output .txt file, it print some strange symbols on the screen.

I want it to show as 0 and 1. How to do that?

```<code>bool* tmp = new bool[size]; // tmp has actual values in it, this is just used to show what are tmp and size
FILE* f = fopen("result.txt", "wb");
        for (int i=0; i<size; i++) {
                fwrite(tmp, sizeof(bool), num_sample_per_point, f);
                fwrite("\n", sizeof(char), 1, f); // insert new line
        }
        fclose(f);
</code>```

Also, I've thought about converting those values to int values, but is that too costy because the size of the array is quite big.

答:
If you want to save human readable data to a file, open it for text:

```<code>FILE* f = fopen("result.txt", "wt");
//                              ^-----
</code>```

otherwise it's written as binary.
 You will then need to consider the specifics of what you write. If you want a 1 or 0 for a boolean, you need to write code for this.

Body:
I have a very big array of boolean values, and I want to write it to a .txt file.

I tried fwrite() and when I use cat command to print the output .txt file, it print some strange symbols on the screen.

I want it to show as 0 and 1. How to do that?

bool* tmp = new bool[size]; // tmp has actual values in it, this is just used to show what are tmp and size
FILE* f = fopen("result.txt", "wb");
        for (int i=0; i<size; i++) {
                fwrite(tmp, sizeof(bool), num_sample_per_point, f);
                fwrite("\n", sizeof(char), 1, f); // insert new line
        }
        fclose(f);

Also, I've thought about converting those values to int values, but is that too costy because the size of the array is quite big.

Body:
If you want to save human readable data to a file, open it for text:

FILE* f = fopen("result.txt", "wt");
//                              ^-----

otherwise it's written as binary.
 You will then need to consider the specifics of what you write. If you want a 1 or 0 for a boolean, you need to write code for this.


问:
Angular 2 Routing ERROR in Cannot use "in" operator to search for "providers" in null
I am testing the Lazy Router version with Angular.

I implemented for every component with the following parts:

```<code>in componentone.component.ts
@Component({...})
export class ComponentOne ...

in componentone.module.ts
@NgModule({..., imports: [componentOneRoutes]})
export default class ComponentOneModule

in componentone.routes.ts
const routes = [ {path: '', component: ComponentOne} ]
export default RouterModule.forChild(routes);
</code>```

In my appcomponent.ts

```<code>@Component({})
export class AppComponent {
   // for displaying the content in url in the app.component.html
   navs = [ {url: '', content: 'Component 1'},... ]
}
</code>```

In app.routes.ts

```<code>const routes = [ {path: "", loadChildren:
"app/componentone/componentone.module"} ]

export default RouterModule.forRoot(routes);
</code>```

Then in app.module.ts import the app.routes.ts

```<code>@NgModule({imports:[appRoutes,...]})
</code>```

I receive the following Error:
    ERROR in Cannot use "in" operator to search for "providers" in null.

My providers section is empty because i have no services only the routing part in the import array.

I am using angular 4 and angular-cli 1.0.0

答:
The below setup and files gives me the same error no matter what I change to match any of the solutions currently offered.

Current Setup

```<code>@angular/cli: 1.1.0
node: 6.9.1
os: darwin x64
@angular/animations: 4.1.3
@angular/common: 4.1.3
@angular/compiler: 4.1.3
@angular/core: 4.1.3
@angular/forms: 4.1.3
@angular/http: 4.1.3
@angular/material: 2.0.0-beta.3
@angular/platform-browser: 4.1.3
@angular/platform-browser-dynamic: 4.1.3
@angular/router: 4.1.3
@angular/cli: 1.1.0
@angular/compiler-cli: 4.1.3
</code>```

Account Module - To be lazy Loaded

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { ACCOUNT_COMPONENTS } from './components/index';
import { ACCOUNT_CONTAINER } from './containers/index';
import { routes } from './account.routes';

@NgModule({
  imports: [
  routes,
  CommonModule,
],
exports: [
  ...ACCOUNT_CONTAINER,
  ...ACCOUNT_COMPONENTS
],
declarations: [
  ...ACCOUNT_CONTAINER,
  ...ACCOUNT_COMPONENTS
],
 providers: [],
})
export class AccountModule { }
</code>```

Account Routing

```<code>import { Route, RouterModule } from '@angular/router';
import { AccountComponent } from     './containers/account/account.component';

const accountRoutes: Route[] = [
  { path: '',
    component: AccountComponent
  }
];

export const routes =  RouterModule.forChild(accountRoutes);
</code>```

Main Routing File

```<code>import { AccountComponent } from   './account/containers/account/account.component';
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const appRoutes: Routes = [
  {
    path: '',
    children: [
      {
        path: '',
        loadChildren: 'app/home/home.module#HomeModule',
      },
      {
        path: 'accounts',
        loadChildren: 'app/account/account.module#AccountModule',
      },
    ]
  },
  { path: '404-page', loadChildren: 'app/404-page/404-   page.module#PageNotFoundModule' },
  { path: '**', redirectTo: '404-page' }

];

export const routes: ModuleWithProviders = RouterModule.forRoot(appRoutes);
</code>```

APP Module

```<code>import { LayoutModule } from './layout/layout.module';
import { RunbookEffects } from './core/effects/runbook.effects';
import { AppComponent } from './app.component';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { Angular2TokenService } from 'angular2-token';
import { EffectsModule } from '@ngrx/effects';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { MaterialModule } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-    browser/animations';
import { routes } from './app.routes';

import { APP_SERVICES } from './core/services';
import { reducer } from './core/store/reducers';
import { StoreModule } from '@ngrx/store';
import { UserEffects } from './core/effects/user.effects';
import { AccountEffects } from './core/effects/account.effects';
import { ProjectEffects } from './core/effects/project.effects';

@NgModule({
  declarations: [
    AppComponent
   ],
  imports: [
    routes,
    MaterialModule,
    LayoutModule,
    BrowserAnimationsModule,
    BrowserModule,
    FormsModule,
    HttpModule,

   StoreModule.provideStore(reducer),
   StoreDevtoolsModule.instrumentOnlyWithExtension({
     maxAge: 5
   }),

    EffectsModule.run(UserEffects),
    EffectsModule.run(AccountEffects),
    EffectsModule.run(ProjectEffects),
    EffectsModule.run(RunbookEffects)
  ],
  providers: [
    Angular2TokenService,
    APP_SERVICES
  ],
  exports: [
  ],
 bootstrap: [AppComponent]
</code>```

})

Body:
I am testing the Lazy Router version with Angular.

I implemented for every component with the following parts:

in componentone.component.ts
@Component({...})
export class ComponentOne ...

in componentone.module.ts
@NgModule({..., imports: [componentOneRoutes]})
export default class ComponentOneModule

in componentone.routes.ts
const routes = [ {path: '', component: ComponentOne} ]
export default RouterModule.forChild(routes);

In my appcomponent.ts

@Component({})
export class AppComponent {
   // for displaying the content in url in the app.component.html
   navs = [ {url: '', content: 'Component 1'},... ]
}

In app.routes.ts

const routes = [ {path: "", loadChildren:
"app/componentone/componentone.module"} ]

export default RouterModule.forRoot(routes);

Then in app.module.ts import the app.routes.ts

@NgModule({imports:[appRoutes,...]})

I receive the following Error:
    ERROR in Cannot use "in" operator to search for "providers" in null.

My providers section is empty because i have no services only the routing part in the import array.

I am using angular 4 and angular-cli 1.0.0

Body:
The below setup and files gives me the same error no matter what I change to match any of the solutions currently offered.

Current Setup

@angular/cli: 1.1.0
node: 6.9.1
os: darwin x64
@angular/animations: 4.1.3
@angular/common: 4.1.3
@angular/compiler: 4.1.3
@angular/core: 4.1.3
@angular/forms: 4.1.3
@angular/http: 4.1.3
@angular/material: 2.0.0-beta.3
@angular/platform-browser: 4.1.3
@angular/platform-browser-dynamic: 4.1.3
@angular/router: 4.1.3
@angular/cli: 1.1.0
@angular/compiler-cli: 4.1.3

Account Module - To be lazy Loaded

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { ACCOUNT_COMPONENTS } from './components/index';
import { ACCOUNT_CONTAINER } from './containers/index';
import { routes } from './account.routes';

@NgModule({
  imports: [
  routes,
  CommonModule,
],
exports: [
  ...ACCOUNT_CONTAINER,
  ...ACCOUNT_COMPONENTS
],
declarations: [
  ...ACCOUNT_CONTAINER,
  ...ACCOUNT_COMPONENTS
],
 providers: [],
})
export class AccountModule { }

Account Routing

import { Route, RouterModule } from '@angular/router';
import { AccountComponent } from     './containers/account/account.component';

const accountRoutes: Route[] = [
  { path: '',
    component: AccountComponent
  }
];

export const routes =  RouterModule.forChild(accountRoutes);

Main Routing File

import { AccountComponent } from   './account/containers/account/account.component';
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const appRoutes: Routes = [
  {
    path: '',
    children: [
      {
        path: '',
        loadChildren: 'app/home/home.module#HomeModule',
      },
      {
        path: 'accounts',
        loadChildren: 'app/account/account.module#AccountModule',
      },
    ]
  },
  { path: '404-page', loadChildren: 'app/404-page/404-   page.module#PageNotFoundModule' },
  { path: '**', redirectTo: '404-page' }

];

export const routes: ModuleWithProviders = RouterModule.forRoot(appRoutes);

APP Module

import { LayoutModule } from './layout/layout.module';
import { RunbookEffects } from './core/effects/runbook.effects';
import { AppComponent } from './app.component';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { Angular2TokenService } from 'angular2-token';
import { EffectsModule } from '@ngrx/effects';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { MaterialModule } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-    browser/animations';
import { routes } from './app.routes';

import { APP_SERVICES } from './core/services';
import { reducer } from './core/store/reducers';
import { StoreModule } from '@ngrx/store';
import { UserEffects } from './core/effects/user.effects';
import { AccountEffects } from './core/effects/account.effects';
import { ProjectEffects } from './core/effects/project.effects';

@NgModule({
  declarations: [
    AppComponent
   ],
  imports: [
    routes,
    MaterialModule,
    LayoutModule,
    BrowserAnimationsModule,
    BrowserModule,
    FormsModule,
    HttpModule,

   StoreModule.provideStore(reducer),
   StoreDevtoolsModule.instrumentOnlyWithExtension({
     maxAge: 5
   }),

    EffectsModule.run(UserEffects),
    EffectsModule.run(AccountEffects),
    EffectsModule.run(ProjectEffects),
    EffectsModule.run(RunbookEffects)
  ],
  providers: [
    Angular2TokenService,
    APP_SERVICES
  ],
  exports: [
  ],
 bootstrap: [AppComponent]

})


问:
Adding extra Zero's dynamically to Integer in fixed lenght format
I need to display a sql column Amount in a format of 15 Integers and 3 decimal places (18 length).

Add extra zero's dynamically to complete the length 18

Decimal(.) will also be replaced by a Zero

For Example :

$2,494.60 will be displayed as 000000002494060

Is it possible to achieve it using SQL ?

Body:
declare @amount numeric(15,3) = 2949.60
select Right('000000000000000' + replace(cast(@amount as varchar(15)),'.','0'),15)


问:
react-ntaive-admob showing test ad banner why not original ad on emulator ?
I have used React-native-admob to show google ads in my react-native application. My code for ad is given below.

```<code><View style={{width:slideWidth,height:60}}>
<AdMobBanner
 bannerSize="fullBanner"
 adUnitID="some-unit-id"
 testDeviceID="EMULATOR"

 didFailToReceiveAdWithError={this.bannerError}/>
</View>
</code>```

it is showing me this test banner

why it is so ? why it is not showing me original ad ?

答:
It's because you've written

```<code>testDeviceID="EMULATOR"
</code>```

Remove this line and your ads will show.

Note: In development its not recommended to test with real ads as you may accidently click on them. Better to check if it works and then revert back to test mode.

Body:
I have used React-native-admob to show google ads in my react-native application. My code for ad is given below.

<View style={{width:slideWidth,height:60}}>
<AdMobBanner
 bannerSize="fullBanner"
 adUnitID="some-unit-id"
 testDeviceID="EMULATOR"

 didFailToReceiveAdWithError={this.bannerError}/>
</View>

it is showing me this test banner

why it is so ? why it is not showing me original ad ?

Body:
It's because you've written

testDeviceID="EMULATOR"

Remove this line and your ads will show.

Note: In development its not recommended to test with real ads as you may accidently click on them. Better to check if it works and then revert back to test mode.


问:
swig/python: object does not support indexing
Given this set of files:

foo.h:

```<code>#pragma once

#include <stdio.h>

template <class T0> class Foo {
  public:
    T0 m[3];

    Foo(const T0 &a, const T0 &b, const T0 &c) {
        m[0] = a;
        m[1] = b;
        m[2] = c;
    }
    void info() { printf("%d %d %d\n", m[0], m[1], m[2]); }
    // T0 &operator[](int id) { return ((T0 *)m)[id]; }
};
</code>```

foo.cpp:

```<code>#include "foo.h"
</code>```

foo.i (Attempt1):

```<code>%module foo

%{
#include "foo.h"
%}

%include "foo.h"

%template(intFoo) Foo<int>;

%extend Foo{
    T0& __getitem__(int id) { return ((T0 *)m)[id]; }
}
</code>```

setup.py:

```<code>import os
import sys
from setuptools import setup, Extension

foo_module = Extension('_foo',
                           sources=[
                               'foo.i',
                               'foo.cpp'
                           ],
                           swig_opts=['-c++', '-py3', '-builtin'],
                           include_dirs=['.']
                           )

setup(name='foo',
      version='0.1',
      platforms=['Windows', 'Linux'],
      ext_modules=[foo_module],
      py_modules=["foo"],
      )
</code>```

test.py:

```<code>from foo import intFoo

a = intFoo(10,20,30)
print(dir(a))
a.info()
print(a[2])
</code>```

I build the extension running:

```<code>python setup.py build_ext --force -i
</code>```

but when i try to run test.py i'll get:

```<code>TypeError: 'foo.intFoo' object does not support indexing
</code>```

The statement extend in foo.i is the answer suggested on any other SO related threads, that means I'm using it incorrectly here. Could anyone explain how to fix this so when i run test.py is able to use the [] operator succesfully?

Another attempts:

Attempt2:

```<code>%module foo

%{
#include "foo.h"
%}

%include "foo.h"

%template(intFoo) Foo<int>;

%extend intFoo{
    T0& __getitem__(int id) { return ((T0 *)m)[id]; }
}
</code>```

Throws this error TypeError: 'foo.intFoo' object does not support indexing

Attempt3

```<code>%module foo

%{
#include "foo.h"
%}

%include "foo.h"

%extend Foo{
    T0& __getitem__(int id) { return ((T0 *)m)[id]; }
}

%template(intFoo) Foo<int>;
</code>```

Throws this error foo_wrap.cpp(3808): error C2065: 'm': undeclared identifier

答:
(Throughout this example I'm working with your first version of foo.i)

First up the %extend you've got needs to be specified before the %template directive to have any effect.

Once we fix that we now get a compiler error from your %extend code:

```<code>foo_wrap.cpp: In function 'int& Foo_Sl_int_Sg____getitem__(Foo<int>*, int)':
foo_wrap.cpp:3705:85: error: 'm' was not declared in this scope
</code>```

This happens because the methods you add with %extend aren't really members of the class you're adding them to. To access m in this context we need to refer to it with $self->m instead. SWIG will replace $self with the appropriate variable for us. (It's worth a quick peek at the generated code to understand how this works)

One useful tip when debugging typemaps or extensions is to search for the code you wrote in the generated output from SWIG - if it's not there then it isn't being applied how you thought.

So once we fix the error about m not being declared we have another problem because you've compiled with -builtin:

In [1]: import foo

In [2]: f=foo.intFoo(1,2,3)

In [3]: f[0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-e71eec16918d> in <module>()
----> 1 f[0]

TypeError: 'intFoo' object does not support indexing

In [4]: f.__getitem__(0)
Out[4]: <Swig Object of type 'int *' at 0xa8807d40>
```

<p>Even though you've added <code>__getitem__</code>, indexing with <code>f[n]</code> still doesn't work. That's happening because with pure C-API classes in Python operator overloading doesn't work the same way. You've added a <code>__getitem__</code> method successfully, but Python is looking in the builtin type's slots (specifically mp_subscript) for a way to perform the operation. So we need to fix that too. With that done a working foo.i looks like:</p>

```%module foo

%{
#include "foo.h"
%}

%feature("python:slot", "mp_subscript", functype="binaryfunc") Foo::__getitem__;

%include "foo.h"

%extend Foo{
    T0& __getitem__(int id) { return ((T0 *)$self->m)[id]; }
}

%template(intFoo) Foo<int>;
```

<p>So now we can do what you want:</p>

<pre class="lang-none prettyprint-override"><code>In [1]: import foo

In [2]: f=foo.intFoo(1,2,3)

In [3]: f[0]
Out[3]: <Swig Object of type 'int *' at 0xb4024100>
</code>```

(You don't actually have to call it __getitem__ any more, because the function gets registered in the slots, it should be possible to call the operator[] without %extend at all for instance)

Finally you probably want to change the return type to const T0&, or write a Python type to proxy objects for non-const int reference better.

Body:
Given this set of files:

foo.h:

#pragma once

#include <stdio.h>

template <class T0> class Foo {
  public:
    T0 m[3];

    Foo(const T0 &a, const T0 &b, const T0 &c) {
        m[0] = a;
        m[1] = b;
        m[2] = c;
    }
    void info() { printf("%d %d %d\n", m[0], m[1], m[2]); }
    // T0 &operator[](int id) { return ((T0 *)m)[id]; }
};

foo.cpp:

#include "foo.h"

foo.i (Attempt1):

%module foo

%{
#include "foo.h"
%}

%include "foo.h"

%template(intFoo) Foo<int>;

%extend Foo{
    T0& __getitem__(int id) { return ((T0 *)m)[id]; }
}

setup.py:

import os
import sys
from setuptools import setup, Extension

foo_module = Extension('_foo',
                           sources=[
                               'foo.i',
                               'foo.cpp'
                           ],
                           swig_opts=['-c++', '-py3', '-builtin'],
                           include_dirs=['.']
                           )

setup(name='foo',
      version='0.1',
      platforms=['Windows', 'Linux'],
      ext_modules=[foo_module],
      py_modules=["foo"],
      )

test.py:

from foo import intFoo

a = intFoo(10,20,30)
print(dir(a))
a.info()
print(a[2])

I build the extension running:

python setup.py build_ext --force -i

but when i try to run test.py i'll get:

TypeError: 'foo.intFoo' object does not support indexing

The statement extend in foo.i is the answer suggested on any other SO related threads, that means I'm using it incorrectly here. Could anyone explain how to fix this so when i run test.py is able to use the [] operator succesfully?

Another attempts:

Attempt2:

%module foo

%{
#include "foo.h"
%}

%include "foo.h"

%template(intFoo) Foo<int>;

%extend intFoo{
    T0& __getitem__(int id) { return ((T0 *)m)[id]; }
}

Throws this error TypeError: 'foo.intFoo' object does not support indexing

Attempt3

%module foo

%{
#include "foo.h"
%}

%include "foo.h"

%extend Foo{
    T0& __getitem__(int id) { return ((T0 *)m)[id]; }
}

%template(intFoo) Foo<int>;

Throws this error foo_wrap.cpp(3808): error C2065: 'm': undeclared identifier

Body:
(Throughout this example I'm working with your first version of foo.i)

First up the %extend you've got needs to be specified before the %template directive to have any effect.

Once we fix that we now get a compiler error from your %extend code:

foo_wrap.cpp: In function 'int& Foo_Sl_int_Sg____getitem__(Foo<int>*, int)':
foo_wrap.cpp:3705:85: error: 'm' was not declared in this scope

This happens because the methods you add with %extend aren't really members of the class you're adding them to. To access m in this context we need to refer to it with $self->m instead. SWIG will replace $self with the appropriate variable for us. (It's worth a quick peek at the generated code to understand how this works)

One useful tip when debugging typemaps or extensions is to search for the code you wrote in the generated output from SWIG - if it's not there then it isn't being applied how you thought.

So once we fix the error about m not being declared we have another problem because you've compiled with -builtin:

In [1]: import foo

In [2]: f=foo.intFoo(1,2,3)

In [3]: f[0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-e71eec16918d> in <module>()
----> 1 f[0]

TypeError: 'intFoo' object does not support indexing

In [4]: f.__getitem__(0)
Out[4]: <Swig Object of type 'int *' at 0xa8807d40>

Even though you've added __getitem__, indexing with f[n] still doesn't work. That's happening because with pure C-API classes in Python operator overloading doesn't work the same way. You've added a __getitem__ method successfully, but Python is looking in the builtin type's slots (specifically mp_subscript) for a way to perform the operation. So we need to fix that too. With that done a working foo.i looks like:

%module foo

%{
#include "foo.h"
%}

%feature("python:slot", "mp_subscript", functype="binaryfunc") Foo::__getitem__;

%include "foo.h"

%extend Foo{
    T0& __getitem__(int id) { return ((T0 *)$self->m)[id]; }
}

%template(intFoo) Foo<int>;

So now we can do what you want:

In [1]: import foo

In [2]: f=foo.intFoo(1,2,3)

In [3]: f[0]
Out[3]: <Swig Object of type 'int *' at 0xb4024100>

(You don't actually have to call it __getitem__ any more, because the function gets registered in the slots, it should be possible to call the operator[] without %extend at all for instance)

Finally you probably want to change the return type to const T0&, or write a Python type to proxy objects for non-const int reference better.


问:
run .jar on .app bundle with arguments
I created a .app bundle that executes jar file. I made the app bundle the default application for a specific file type. how to pass the selected file as argument to the java program

the script that I am using:

```<code>on run (input, parameters)
  set p to POSIX path of (path to me)
  do shell script java -jar" & p & "/Contents/Java/MyFile.jar'
end run
</code>```

答:
you can use "selection" to get the path of the selected file, and use POSIX to get the right representation:</p>

```<code>tell application "Finder"
    set filePath to POSIX path of (selection as text)
end tell
</code>```

Title: run .jar on .app bundle with arguments

Body:
I created a .app bundle that executes jar file. I made the app bundle the default application for a specific file type. how to pass the selected file as argument to the java program

the script that I am using:

on run (input, parameters)
  set p to POSIX path of (path to me)
  do shell script java -jar" & p & "/Contents/Java/MyFile.jar'
end run

Body:
you can use "selection" to get the path of the selected file, and use POSIX to get the right representation:

tell application "Finder"
    set filePath to POSIX path of (selection as text)
end tell


问:
Products is not showing up on Magento2 subcategory
I installed a fresh magento2, and top categories are working, but for sub-category, there is no product showing up in frontend even thought I assigned products to these sub-categories.

It's always said "We can't find products matching the selection."

Where can I find the code in Magento 2 that's responsible for displaying products so I can diagnose this in a programatic manner?

答:
This is due to reindexing issue.

app\code\Modules\Catalog\etc\di.xml

```<code><?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Model\Indexer\Category\Product\Action\Full" type="Modules\Catalog\Model\Indexer\Category\Product\Action\Full" />
</config>
</code>```

app\code\Modules\Catalog\Model\Indexer\Category\Product\Action\Full.php

```<code><?php
namespace Modules\Catalog\Model\Indexer\Category\Product\Action;

/**
 * Class AbstractAction
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/

class Full extends \Magento\Catalog\Model\Indexer\Category\Product\Action\Full {

    public function isRangingNeeded() {
        return false; // It was "True" as default setting.
    }
}
</code>```

Then, we should run this command.

```<code>php bin/magento cache:clean
php bin/magento indexer:reindex
</code>```

Finally, we got whole 2000 products on our category page instead of previous 340 products on frontend page.
Also, the "Product category" tab on index management is just updated from date of version upgraded to current indexing date and time.

Great experience!

Hope this will help many developers and owners.

Body:
This is due to reindexing issue.

app\code\Modules\Catalog\etc\di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Model\Indexer\Category\Product\Action\Full" type="Modules\Catalog\Model\Indexer\Category\Product\Action\Full" />
</config>

app\code\Modules\Catalog\Model\Indexer\Category\Product\Action\Full.php

<?php
namespace Modules\Catalog\Model\Indexer\Category\Product\Action;

/**
 * Class AbstractAction
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/

class Full extends \Magento\Catalog\Model\Indexer\Category\Product\Action\Full {

    public function isRangingNeeded() {
        return false; // It was "True" as default setting.
    }
}

Then, we should run this command.

php bin/magento cache:clean
php bin/magento indexer:reindex

Finally, we got whole 2000 products on our category page instead of previous 340 products on frontend page.
Also, the "Product category" tab on index management is just updated from date of version upgraded to current indexing date and time.

Great experience!

Hope this will help many developers and owners.


问:
How to get an export of firebase analytics full historic data?
I have setup Firebase analytics data to BigQuery. However I received my first export today and it contains all yesterdays user statistics. That is great but I need lifetime statistics history or at least last month's data.

Do I already have access to my entire historic analytics data threw Big Query but I and I do not know how to access it? If so can you point to documentation or give a quick walk threw?

Is it even possible to get the full (or at least a longer period than a day) historic analytics data?

Bonus question: Can I directly access data that is used in Firebase analytics console? They should be feeding it with some API for some things I need aggregates would be sufficient. So is there http://analytics.firebase/data.json I could access while logged in to my Firebase account to save data to my machine?

答:
firebaser here

Firebase Analytics does not expose the historical event level data. It only exposes aggregate information.

Complete event data is only available from the moment you enabled the BigQuery connection. No data from before that time will be added to BigQuery.

The data from the analytics reports that is shown in the Firebase Console is available through the Analytics Data API. See Is there any api for dashboard analytics data?

ContentLicense: CC BY-SA 4.0


问:
Debugging test cases when they are combination of Robot framework and python selenium
Currently I'm using Eclipse with Nokia/Red plugin which allows me to write robot framework test suites. Support is Python 3.6 and Selenium for it.
My project is called "Automation" and Test suites are in .robot files.
Test suites have test cases which are called "Keywords".

Test Cases

Create New Vehicle

```<code>Create new vehicle with next ${registrationno} and ${description}
Navigate to data section
</code>```

Those "Keywords" are imported from python library and look like:

```<code>@keyword("Create new vehicle with next ${registrationno} and ${description}")
def create_new_vehicle_Simple(self,registrationno, description):
    headerPage = HeaderPage(TestCaseKeywords.driver)
    sideBarPage = headerPage.selectDaten()
    basicVehicleCreation = sideBarPage.createNewVehicle()
    basicVehicleCreation.setKennzeichen(registrationno)
    basicVehicleCreation.setBeschreibung(description)
    TestCaseKeywords.carnumber = basicVehicleCreation.save()
</code>```

The problem is that when I run test cases, in log I only get result of this whole python function, pass or failed. I can't see at which step it failed- is it at first or second step of this function.

Is there any plugin or other solution for this case to be able to see which exact python function pass or fail? (of course, workaround is to use in TC for every function a keyword but that is not what I prefer)

答:
If you need to "step into" a python defined keyword you need to use python debugger together with RED.

This can be done with any python debugger,if you like to have everything in one application, PyDev can be used with RED.

Follow below help document, if you will face any problems leave a comment here.

RED Debug with PyDev

Body:
Currently I'm using Eclipse with Nokia/Red plugin which allows me to write robot framework test suites. Support is Python 3.6 and Selenium for it.
My project is called "Automation" and Test suites are in .robot files.
Test suites have test cases which are called "Keywords".

Test Cases

Create New Vehicle

Create new vehicle with next ${registrationno} and ${description}
Navigate to data section

Those "Keywords" are imported from python library and look like:

@keyword("Create new vehicle with next ${registrationno} and ${description}")
def create_new_vehicle_Simple(self,registrationno, description):
    headerPage = HeaderPage(TestCaseKeywords.driver)
    sideBarPage = headerPage.selectDaten()
    basicVehicleCreation = sideBarPage.createNewVehicle()
    basicVehicleCreation.setKennzeichen(registrationno)
    basicVehicleCreation.setBeschreibung(description)
    TestCaseKeywords.carnumber = basicVehicleCreation.save()

The problem is that when I run test cases, in log I only get result of this whole python function, pass or failed. I can't see at which step it failed- is it at first or second step of this function.

Is there any plugin or other solution for this case to be able to see which exact python function pass or fail? (of course, workaround is to use in TC for every function a keyword but that is not what I prefer)


问:
Good pattern for redux action in callback
Supposing I have an update comment action. When a user updates comment after getting a successful result from Promise I should close comment editor. This is my sample code from my project:

```<code>export const updateComment = (comment,callBack/* ? */) => {
   return (dispatch, getState){
      api.updateComment({...comment}).then((result) => {
             /* Do something */
             callback() /* ? */
       })
    }
}
</code>```

In react component I use action like the following code:

```<code>handleUpdateComment(){
  dispatch(actions.updateComment(this.state.comment,this.closeCommentEitor)
}
</code>```

It works well but I think is not a good pattern to close comment editor. I'm looking a correct pattern to close editor without passing callBack like I did if any.

答:
When you are using redux-thunk, you can dispatch an action from another action.
What you can do is that, commentEditor have a state which you store in redux and based on that state open or close the commentEditor

```<code>export const updateComment = (comment, comment_id) => {
   return (dispatch, getState){
      api.updateComment({...comment}).then((result) => {
             /* Do something */
             dispatch({type: 'CLOSE_COMMENT_EDITOR', id: comment_id})
       })
    }
}
</code>```

After this in a reducer on this action change the state of redux store, something like

```<code>import update from 'immutability-helper'

var initialState = [{commentId: '1', commentEditorOpenStatus: false}, {commentId: '2', commentEditorOpenStatus: false}]
const reducer = (state = initialState, action) => {
     switch(action.type) {
         'CLOSE_COMMENT_EDITOR':
                  const idx = state.findIndex(obj => obj.commentId == action.id);
                  return update(state, {
                         [idx]: {
                              commentEditorOpenStatus: {
                                  $set: false
                               }
                          }
                   })
            // Other action handlers here
            default: return state
     }

}
</code>```

Body:
Supposing I have an update comment action. When a user updates comment after getting a successful result from Promise I should close comment editor. This is my sample code from my project:

export const updateComment = (comment,callBack/* ? */) => {
   return (dispatch, getState){
      api.updateComment({...comment}).then((result) => {
             /* Do something */
             callback() /* ? */
       })
    }
}

In react component I use action like the following code:

handleUpdateComment(){
  dispatch(actions.updateComment(this.state.comment,this.closeCommentEitor)
}

It works well but I think is not a good pattern to close comment editor. I'm looking a correct pattern to close editor without passing callBack like I did if any.

Body:
When you are using redux-thunk, you can dispatch an action from another action.
What you can do is that, commentEditor have a state which you store in redux and based on that state open or close the commentEditor

export const updateComment = (comment, comment_id) => {
   return (dispatch, getState){
      api.updateComment({...comment}).then((result) => {
             /* Do something */
             dispatch({type: 'CLOSE_COMMENT_EDITOR', id: comment_id})
       })
    }
}

After this in a reducer on this action change the state of redux store, something like

import update from 'immutability-helper'

var initialState = [{commentId: '1', commentEditorOpenStatus: false}, {commentId: '2', commentEditorOpenStatus: false}]
const reducer = (state = initialState, action) => {
     switch(action.type) {
         'CLOSE_COMMENT_EDITOR':
                  const idx = state.findIndex(obj => obj.commentId == action.id);
                  return update(state, {
                         [idx]: {
                              commentEditorOpenStatus: {
                                  $set: false
                               }
                          }
                   })
            // Other action handlers here
            default: return state
     }

}


问:
How to print a value with the same criteria - JavaScript
I am trying to print numbers that are divisible by 3 and 5.
For numbers divisible by 3, print out "Fizz".
For numbers divisible by 5, print out "Buzz".
For numbers divisible by both 3 and 5, print out "FizzBuzz" in
the console. Otherwise, just print out the number.

Tried these codes:

```<code>var i;

for(i = 1; i <= 20; i++){
  if(i % 3 === 0){
     console.log("Fizz");
  }else if(i % 5 === 0){
     console.log("Buzz");
 }else if(i % 3 === 0 && i % 5 === 0){
      console.log("FizzBuzz");
  }else {
   console.log(i);
}
}
</code>```

But it seems it passing out the 3rd else if...
Is there a better way to do this?

答:
Less code for same results:

for(var i = 1; i <= 20; i++) {
  var output = '';
  if(i % 3 === 0) output += 'Fizz';
  if(i % 5 === 0) output += 'Buzz';
  console.log(output.length > 0 ? output : i);
}```

Body:
I am trying to print numbers that are divisible by 3 and 5.
For numbers divisible by 3, print out "Fizz".
For numbers divisible by 5, print out "Buzz".
For numbers divisible by both 3 and 5, print out "FizzBuzz" in
the console. Otherwise, just print out the number.

Tried these codes:

var i;

for(i = 1; i <= 20; i++){
  if(i % 3 === 0){
     console.log("Fizz");
  }else if(i % 5 === 0){
     console.log("Buzz");
 }else if(i % 3 === 0 && i % 5 === 0){
      console.log("FizzBuzz");
  }else {
   console.log(i);
}
}

But it seems it passing out the 3rd else if...
Is there a better way to do this?


问:
How to implement existential quantifiers in OO programming?
It's easy to asses and implement logic formulas including universal quantifiers via (nested) foreach or for loops:

(\forall x \in X)(\forall y \in Y) (Z(x,y))

```<code>foreach (type x in X)
{
   foreach (type y in Y)
   {
      if(Z(x,y))
         return true;
      else
         return false;
   }
}
</code>```

But how can one implement the existential quantifiers in OO programming languages, especially C# (not logic programming languages)?

(\forall x \in X)(\exists y \in Y) (Z(x,y))

For example, to assess a number x whether it is even or not, we must code the following formula:

(\forall x)(\exists y) (x = y + y)

答:
There are a few problems with your question. The first is, the code snippet you provided doesn't perform what you intend it to perform:

```<code>foreach (type x in X)
{
   foreach (type y in Y)
   {
      if(Z(x,y))
         return true;
      else
         return false;
   }
}
</code>```

This will not be evaluated for all values in X nor all values in Y. Instead, the test Z(x,y) will be executed only once, on the first element x0 in X and the first element y0 in Y. Then, according to this test, both loops will break (because return exits the method).

The conventional way to do a "for all" test using loops would be something like:

```<code>foreach (var x in X)
{
   foreach (var y in Y)
   {
      if(!Z(x,y))
         return false;
   }
}
return true;
</code>```

Similarly, the conventional way to do "exists" test using loops would be:

```<code>foreach (var x in X)
{
   foreach (var y in Y)
   {
      if(Z(x,y))
         return true;
   }
}
return false;
</code>```

In C#, however, you can eliminate the need for loops using LINQ. So if you want to check whether a set of numbers X contains an even number, you can write:

```<code>return X.Any(x => x % 2 == 0);
</code>```

EDIT: to clarify, after your edit: if you want to code the "for all x in X exists y in Y such that y+y==x", you can write something like:

```<code>foreach (var x in X)
{
   if (!Y.Any(y => y+y == x))
      return false;
}
return true;
</code>```

Body:
It's easy to asses and implement logic formulas including universal quantifiers via (nested) foreach or for loops:

(\forall x \in X)(\forall y \in Y) (Z(x,y))

foreach (type x in X)
{
   foreach (type y in Y)
   {
      if(Z(x,y))
         return true;
      else
         return false;
   }
}

But how can one implement the existential quantifiers in OO programming languages, especially C# (not logic programming languages)?

(\forall x \in X)(\exists y \in Y) (Z(x,y))

For example, to assess a number x whether it is even or not, we must code the following formula:

(\forall x)(\exists y) (x = y + y)

Body:
There are a few problems with your question. The first is, the code snippet you provided doesn't perform what you intend it to perform:

foreach (type x in X)
{
   foreach (type y in Y)
   {
      if(Z(x,y))
         return true;
      else
         return false;
   }
}

This will not be evaluated for all values in X nor all values in Y. Instead, the test Z(x,y) will be executed only once, on the first element x0 in X and the first element y0 in Y. Then, according to this test, both loops will break (because return exits the method).

The conventional way to do a "for all" test using loops would be something like:

foreach (var x in X)
{
   foreach (var y in Y)
   {
      if(!Z(x,y))
         return false;
   }
}
return true;

Similarly, the conventional way to do "exists" test using loops would be:

foreach (var x in X)
{
   foreach (var y in Y)
   {
      if(Z(x,y))
         return true;
   }
}
return false;

In C#, however, you can eliminate the need for loops using LINQ. So if you want to check whether a set of numbers X contains an even number, you can write:

return X.Any(x => x % 2 == 0);

EDIT: to clarify, after your edit: if you want to code the "for all x in X exists y in Y such that y+y==x", you can write something like:

foreach (var x in X)
{
   if (!Y.Any(y => y+y == x))
      return false;
}
return true;