问:
Waiting for document created in trigger in android app
I have an android app using firebase. When the user registers I have a trigger on firebase that creates a document in a collection with the default data for the user.

This is the code of the function used as a trigger on firebase:

```<code>    exports.sendWelcomeEmail = functions.auth.user().onCreate((user) =>
    {
        var userCoinsCol = db.collection('user_data');
        userCoinsCol.doc(user.uid).set({
            coins : 100, // some another information for user you could save it here.
            active: true,
            completedRewards: 0
        })
        .then(() => {
            console.log("done");
            return;
        })
        .catch((err) =>
        {
            console.log("Error creating data for just created user. => "+err);
            return;
        });
    });
</code>```

All this works perfectly. The problem is that after registering, I need the user data and it seems sometimes when the user registers it is not ready for the app to use in the next activity.

So, my question is, is there any way for the android app to wait for the trigger to create that document before moving to the next activity that will use that user data?

As you can guess this only happens firt time the user registers. Later if the user wants to use the app again everything works ok because the user data was created just after user registered.

Edit: After a bit of playing I have come with this solution, but it seems not too performant because it can receive a lot of documents. I just add it for reference:

```<code>public void CreateAccount()
{

    if(!TextUtils.isEmpty(emailreg.getText()) && !TextUtils.isEmpty(passreg.getText()))
    {
        mAuth.createUserWithEmailAndPassword(emailreg.getText().toString(), passreg.getText().toString())
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
        {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task)
            {

                progressBar.setVisibility(View.INVISIBLE);

                if (task.isSuccessful())
                {
                    // Sign in success, update UI with the signed-in user's information
                    final FirebaseUser user = mAuth.getCurrentUser();

                    // ----> Start waiting for the user_data document to be created and go to the next activity
                    FirebaseFirestore db = FirebaseFirestore.getInstance();
                    final EventListener<QuerySnapshot> listener = new EventListener<QuerySnapshot>() {
                        @Override
                        public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
                            List<DocumentSnapshot> documents = queryDocumentSnapshots.getDocuments();

                            boolean found = false;
                            for(DocumentSnapshot ds : documents)
                            {
                                if(ds.getId().equals(user.getUid()))
                                {
                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class); // Call the AppIntro java class
                                    startActivity(intent);
                                }

                            }
                        }
                    };

                    db.collection("user_data").addSnapshotListener(listener);

                } else
                {
                    // If sign in fails, display a message to the user.

                    Toast.makeText(LoginActivity.this, getString(R.string.tryagain), Toast.LENGTH_SHORT).show();

                }

                // ...
            }
        });

    }else
    {
        Toast.makeText(LoginActivity.this, getString(R.string.tryagain), Toast.LENGTH_SHORT).show();
        progressBar.setVisibility(View.INVISIBLE);

    }

}
</code>```

答:
So, my question is, is there any way for the android app to wait for the trigger to create that document before going forward to the next activity that will create that user data?

Of course it is, by adding a complete listener. This means that you can go further only when the data is written successfully to the database. When you are using DocumentReference's set() method, the object that is returned is of type Task, so you can simply use addOnCompleteListener().

```<code>yourDocumentRef.set(yourObject).addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        if (task.isSuccessful()) {
            //Do what you need to do
        }
    }
});
</code>```

Edit:

If the user document is added to the Cloud Firestore database via Coud Functions, you can either change the logic of your app and create the user document client side along with Security Rules which are mandatory so your users cannot play with the data. Or you attach a snapshot listener to verify the data in realtime. Once the document is created, go ahead with logic.

Body:
I have an android app using firebase. When the user registers I have a trigger on firebase that creates a document in a collection with the default data for the user.

This is the code of the function used as a trigger on firebase:

    exports.sendWelcomeEmail = functions.auth.user().onCreate((user) =>
    {
        var userCoinsCol = db.collection('user_data');
        userCoinsCol.doc(user.uid).set({
            coins : 100, // some another information for user you could save it here.
            active: true,
            completedRewards: 0
        })
        .then(() => {
            console.log("done");
            return;
        })
        .catch((err) =>
        {
            console.log("Error creating data for just created user. => "+err);
            return;
        });
    });

All this works perfectly. The problem is that after registering, I need the user data and it seems sometimes when the user registers it is not ready for the app to use in the next activity.

So, my question is, is there any way for the android app to wait for the trigger to create that document before moving to the next activity that will use that user data?

As you can guess this only happens firt time the user registers. Later if the user wants to use the app again everything works ok because the user data was created just after user registered.

Edit: After a bit of playing I have come with this solution, but it seems not too performant because it can receive a lot of documents. I just add it for reference:

public void CreateAccount()
{

    if(!TextUtils.isEmpty(emailreg.getText()) && !TextUtils.isEmpty(passreg.getText()))
    {
        mAuth.createUserWithEmailAndPassword(emailreg.getText().toString(), passreg.getText().toString())
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
        {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task)
            {

                progressBar.setVisibility(View.INVISIBLE);

                if (task.isSuccessful())
                {
                    // Sign in success, update UI with the signed-in user's information
                    final FirebaseUser user = mAuth.getCurrentUser();

                    // ----> Start waiting for the user_data document to be created and go to the next activity
                    FirebaseFirestore db = FirebaseFirestore.getInstance();
                    final EventListener<QuerySnapshot> listener = new EventListener<QuerySnapshot>() {
                        @Override
                        public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
                            List<DocumentSnapshot> documents = queryDocumentSnapshots.getDocuments();

                            boolean found = false;
                            for(DocumentSnapshot ds : documents)
                            {
                                if(ds.getId().equals(user.getUid()))
                                {
                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class); // Call the AppIntro java class
                                    startActivity(intent);
                                }

                            }
                        }
                    };

                    db.collection("user_data").addSnapshotListener(listener);

                } else
                {
                    // If sign in fails, display a message to the user.

                    Toast.makeText(LoginActivity.this, getString(R.string.tryagain), Toast.LENGTH_SHORT).show();

                }

                // ...
            }
        });

    }else
    {
        Toast.makeText(LoginActivity.this, getString(R.string.tryagain), Toast.LENGTH_SHORT).show();
        progressBar.setVisibility(View.INVISIBLE);

    }

}

Body:
So, my question is, is there any way for the android app to wait for the trigger to create that document before going forward to the next activity that will create that user data?

Of course it is, by adding a complete listener. This means that you can go further only when the data is written successfully to the database. When you are using DocumentReference's set() method, the object that is returned is of type Task, so you can simply use addOnCompleteListener().

yourDocumentRef.set(yourObject).addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        if (task.isSuccessful()) {
            //Do what you need to do
        }
    }
});

Edit:

If the user document is added to the Cloud Firestore database via Coud Functions, you can either change the logic of your app and create the user document client side along with Security Rules which are mandatory so your users cannot play with the data. Or you attach a snapshot listener to verify the data in realtime. Once the document is created, go ahead with logic.


来源: stackexchange

问:
Webpack - Use variable to compile
I'm using Laravel & Webpack to compile CSS for 4 different themes. But each time I only want to compile the one theme.

I am storing in my Database a template_home variable. I don't mind putting this var in my .env file either..

Ideally I'd like to then use that variable to compile one of the 4 mixes.

Is this possible?

Thanks

答:
Yes, this should be possible with the dotenv npm package.

First install the package with npm: npm install dotenv --save-dev.

Then add the template key to the .env-file:

```<code>...
THEME_KEY=test_01
...
</code>```

To access and use the variable you need to edit your webpack.mix.js-file:

const mix = require('laravel-mix');
const dotenv = require('dotenv').config();

mix.sass('resources/assets/sass/' + process.env.THEME_KEY + '.scss', 'css');
```

Hope this helps!

ContentLicense: CC BY-SA 4.0

Title: Webpack - Use variable to compile

Body:
Yes, this should be possible with the dotenv npm package.

First install the package with npm: npm install dotenv --save-dev.

Then add the template key to the .env-file:

...
THEME_KEY=test_01
...

To access and use the variable you need to edit your webpack.mix.js-file:

const mix = require('laravel-mix');
const dotenv = require('dotenv').config();

mix.sass('resources/assets/sass/' + process.env.THEME_KEY + '.scss', 'css');

Hope this helps!


问:
ActionScript 3.0 compiler macro to create string of current AS file and code Line?
i'd like to do something like this:

```<code>try{
    operationThatMayFail();
}
catch(e:Error){
    handleError();
    MyLogFileLogger.writeEntry("Error ocurred in file " + CURRENT_AS_FILE + " on line: " + CURRENT_LINE);
}
</code>```

of course i could hardcode that - but if I then change something about the as file, the linenumbers won't be correct anymore, or maybe i rename the as file and so on. It'd be great to be able to create that string somehow using compiler directives.

Is this Possible in an AIR application created with ActionScript 3.0?

答:
You should look up the Error class caught in the exception.  You'll want to do this:</p>

```<code>try{
    operationThatMayFail();
}
catch(e:Error){
    handleError();
    MyLogFileLogger.writeEntry(e.getStackTrace());
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i'd like to do something like this:

try{
    operationThatMayFail();
}
catch(e:Error){
    handleError();
    MyLogFileLogger.writeEntry("Error ocurred in file " + CURRENT_AS_FILE + " on line: " + CURRENT_LINE);
}

of course i could hardcode that - but if I then change something about the as file, the linenumbers won't be correct anymore, or maybe i rename the as file and so on. It'd be great to be able to create that string somehow using compiler directives.

Is this Possible in an AIR application created with ActionScript 3.0?

Body:
You should look up the Error class caught in the exception.  You'll want to do this:

try{
    operationThatMayFail();
}
catch(e:Error){
    handleError();
    MyLogFileLogger.writeEntry(e.getStackTrace());
}


问:
Type 'string' is not assignable to type 'number'
I really did not understand how the type assignment system works for variables in typescript.
Can anyone help me why this does not work.
Thank you

```<code>valorParcela:number;
totalCost:number;
VendaProdutoVendaNParcelas: number;

this.valorParcela = Number( this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2);
</code>```

I expected a simple parseFloat

答:
toFixed() returns string. throwing an error because trying to assign to the number type. so just cast to Number(expression) again or make this variable as string this.valorParcela

```<code>this.valorParcela = Number(Number(this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2)));
</code>```

Body:
I really did not understand how the type assignment system works for variables in typescript.
Can anyone help me why this does not work.
Thank you

valorParcela:number;
totalCost:number;
VendaProdutoVendaNParcelas: number;

this.valorParcela = Number( this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2);

I expected a simple parseFloat

Body:
toFixed() returns string. throwing an error because trying to assign to the number type. so just cast to Number(expression) again or make this variable as string this.valorParcela

this.valorParcela = Number(Number(this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2)));


问:
AndroidX causing AppCompatActivity to crash
The application was running just fine until oll of a sudden this error got triggered somehow :

```<code>E/AndroidRuntime: at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:543)
    at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:136)
    at com.thorsguild.company..Activities.MainActivity.onCreate(MainActivity.java:89)
</code>```

I should mention that I just started using this library from GitHub which serve a group toggle buttonsand was about to test it

Q: What does this error means and how to fix it ??

UPDATE

Entire Stack trace

```<code>2019-05-31 12:04:14.216 14753-14753/com.hablo.company.hablo E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hablo.company.hablo, PID: 14753
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hablo.company.hablo/com.hablo.company.hablo.Activities.MainActivity}: android.view.InflateException: Binary XML file line #126: Binary XML file line #111: Error inflating class com.nex3z.togglebuttongroup.button.CircularButton
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2947)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
    at android.app.ActivityThread.-wrap14(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6688)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
 Caused by: android.view.InflateException: Binary XML file line #126: Binary XML file line #111: Error inflating class com.nex3z.togglebuttongroup.button.CircularButton
 Caused by: android.view.InflateException: Binary XML file line #111: Error inflating class com.nex3z.togglebuttongroup.button.CircularButton
 Caused by: java.lang.ClassNotFoundException: Didn't find class "com.nex3z.togglebuttongroup.button.CircularButton" on path: DexPathList[[zip file "/data/app/com.hablo.company.hablo-1/base.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.hablo.company.hablo-1/lib/arm64, /system/lib64, /vendor/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at android.view.LayoutInflater.createView(LayoutInflater.java:616)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:794)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:734)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:865)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:873)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:873)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:873)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
    at android.view.LayoutInflater.parseInclude(LayoutInflater.java:1011)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:861)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:873)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:525)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:378)
2019-05-31 12:04:14.216 14753-14753/com.hablo.company.hablo E/AndroidRuntime:     at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:543)
    at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:136)
    at com.hablo.company.hablo.Activities.MainActivity.onCreate(MainActivity.java:89)
    at android.app.Activity.performCreate(Activity.java:6912)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
    at android.app.ActivityThread.-wrap14(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6688)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
</code>```

答:
It looks like you have misread the class name. You are supposed to use CircularToggle but you are using CircularButton which is not there in library. You can check the sample usage mentioned on github which is as below

```<code><com.nex3z.togglebuttongroup.button.CircularToggle
        android:id="@+id/choice_a"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="A"/>
</code>```

Body:
The application was running just fine until oll of a sudden this error got triggered somehow :

E/AndroidRuntime: at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:543)
    at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:136)
    at com.thorsguild.company..Activities.MainActivity.onCreate(MainActivity.java:89)

I should mention that I just started using this library from GitHub which serve a group toggle buttonsand was about to test it

Q: What does this error means and how to fix it ??

UPDATE

Entire Stack trace

2019-05-31 12:04:14.216 14753-14753/com.hablo.company.hablo E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hablo.company.hablo, PID: 14753
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hablo.company.hablo/com.hablo.company.hablo.Activities.MainActivity}: android.view.InflateException: Binary XML file line #126: Binary XML file line #111: Error inflating class com.nex3z.togglebuttongroup.button.CircularButton
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2947)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
    at android.app.ActivityThread.-wrap14(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6688)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
 Caused by: android.view.InflateException: Binary XML file line #126: Binary XML file line #111: Error inflating class com.nex3z.togglebuttongroup.button.CircularButton
 Caused by: android.view.InflateException: Binary XML file line #111: Error inflating class com.nex3z.togglebuttongroup.button.CircularButton
 Caused by: java.lang.ClassNotFoundException: Didn't find class "com.nex3z.togglebuttongroup.button.CircularButton" on path: DexPathList[[zip file "/data/app/com.hablo.company.hablo-1/base.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.hablo.company.hablo-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.hablo.company.hablo-1/lib/arm64, /system/lib64, /vendor/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at android.view.LayoutInflater.createView(LayoutInflater.java:616)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:794)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:734)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:865)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:873)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:873)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:873)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
    at android.view.LayoutInflater.parseInclude(LayoutInflater.java:1011)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:861)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:873)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:525)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:378)
2019-05-31 12:04:14.216 14753-14753/com.hablo.company.hablo E/AndroidRuntime:     at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:543)
    at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:136)
    at com.hablo.company.hablo.Activities.MainActivity.onCreate(MainActivity.java:89)
    at android.app.Activity.performCreate(Activity.java:6912)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
    at android.app.ActivityThread.-wrap14(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6688)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

Body:
It looks like you have misread the class name. You are supposed to use CircularToggle but you are using CircularButton which is not there in library. You can check the sample usage mentioned on github which is as below

<com.nex3z.togglebuttongroup.button.CircularToggle
        android:id="@+id/choice_a"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="A"/>


问:
Monads and AOP correlation?
I'm struggling to try to understand monads in functional programming and how it applies on the language I work (Swift, a multi-paradigm language).

As far as I could understand Monad is a pattern to deal mainly with two programming problems: chaining operations while isolating state complexity from it (IO, log, error, uncertainty). Is it correct?

Thinking of that, it seems that Monads could be used to handle transactional/atomic operations in a functional solution. And it seemed to me (on this point) some similarities with Aspect-Oriented Programming: separate the managing of cross-cuting concerns and its complexity from the regular business logic.

Does it make sense?

Thanks!

PS: The question is not as as broad as "What is a Monad?".

答:
At the risk of being overly simplistic; in the world of Monads you are expected to declare your Aspects via the type system. So aspects are tracked explicitly by the compiler, since you can write a Monad which handles Transactions or Logging concerns for you.

With monads you are able to statically (at compile time) declare your effects separately from your core logic, with aop you do this dynamically (at run time) with a much weaker ability to reason algebraically about aspects you have threaded into your codebase.

Title: Monads and AOP correlation?


答:
```<code>.toFixed(2);
</code>```

Always returns string.

And you have assigned type number.

Title: Type 'string' is not assignable to type 'number'

Body:
.toFixed(2);

Always returns string.

And you have assigned type number.


问:
Read all lines with BufferedReader and not empy it
BufferedReader object that has data from socket. How to get whole BufferedReader content without erasing it. I need it for tracing purposes.

答:
You should mark() the starting buffer position, so that your reset() call comes back to the beginning. For example, if you are reading chars, and want to mark a position to come back:

Data sample: A B C D

```<code>System.out.println((char)buffer.read());
System.out.println((char)buffer.read());
buffer.mark(4); // save the position
System.out.println((char)buffer.read());
System.out.println((char)buffer.read());
buffer.reset() // back to 4
System.out.println((char)buffer.read());
System.out.println((char)buffer.read());
</code>```

Will print:

A B C D C D

(as a char takes 2 bytes)

Body:
You should mark() the starting buffer position, so that your reset() call comes back to the beginning. For example, if you are reading chars, and want to mark a position to come back:

Data sample: A B C D

System.out.println((char)buffer.read());
System.out.println((char)buffer.read());
buffer.mark(4); // save the position
System.out.println((char)buffer.read());
System.out.println((char)buffer.read());
buffer.reset() // back to 4
System.out.println((char)buffer.read());
System.out.println((char)buffer.read());

Will print:

A B C D C D

(as a char takes 2 bytes)


问:
Functional map-like data structure with arbitrary length data as keys?
It could very well be that the answer to this question is an obvious and resounding "there's no such thing", but I'll give it a shot: Is there a functional map-like data structure that is more efficient than a standard map when the keys have an arbitrary, often very big, size?

For the sake of concreteness, consider the Haskell type

```<code>(Ord k) => Map [k] v
</code>```

in which lookups can take a very long time if lists need to be compared down to a deep level. I guess hashing is also out of the question due to the arbitrary length of the lists. I still can't help but think there could be a clever data structure out there.

答:
Here's one:

```<code>module ListMap where
import Data.Map as M

data ListMap k v = ListMap { ifEmpty :: Maybe v, ifFull :: Maybe k (ListMap k v) }

empty :: ListMap k v
empty = ListMap Nothing M.empty

singleton :: [k] -> v -> ListMap k v
singleton [] v = ListMap.empty { ifEmpty = Just v }
singleton (k:ks) v = ListMap.empty { ifFull = M.singleton k (ListMap.singleton ks v) }

lookup :: Ord k => [k] -> ListMap k v -> Maybe v
lookup [] lm = ifEmpty lm
lookup (k:ks) lm = M.lookup k (ifFull lm) >>= ListMap.lookup ks

insert :: Ord k => [k] -> v -> ListMap k v -> ListMap k v
insert [] v lm = lm { ifEmpty = Just v }
insert (k:ks) v lm = lm { ifFull = M.alter (Just . insertion) k (ifFull lm) }
  where insertion = maybe (ListMap.singleton ks v) (ListMap.insert ks v)
</code>```

It's essentially creating a prefix tree on the list elements so you only compare as far as necessary.

Body:
It could very well be that the answer to this question is an obvious and resounding "there's no such thing", but I'll give it a shot: Is there a functional map-like data structure that is more efficient than a standard map when the keys have an arbitrary, often very big, size?

For the sake of concreteness, consider the Haskell type

(Ord k) => Map [k] v

in which lookups can take a very long time if lists need to be compared down to a deep level. I guess hashing is also out of the question due to the arbitrary length of the lists. I still can't help but think there could be a clever data structure out there.

Body:
Here's one:

module ListMap where
import Data.Map as M

data ListMap k v = ListMap { ifEmpty :: Maybe v, ifFull :: Maybe k (ListMap k v) }

empty :: ListMap k v
empty = ListMap Nothing M.empty

singleton :: [k] -> v -> ListMap k v
singleton [] v = ListMap.empty { ifEmpty = Just v }
singleton (k:ks) v = ListMap.empty { ifFull = M.singleton k (ListMap.singleton ks v) }

lookup :: Ord k => [k] -> ListMap k v -> Maybe v
lookup [] lm = ifEmpty lm
lookup (k:ks) lm = M.lookup k (ifFull lm) >>= ListMap.lookup ks

insert :: Ord k => [k] -> v -> ListMap k v -> ListMap k v
insert [] v lm = lm { ifEmpty = Just v }
insert (k:ks) v lm = lm { ifFull = M.alter (Just . insertion) k (ifFull lm) }
  where insertion = maybe (ListMap.singleton ks v) (ListMap.insert ks v)

It's essentially creating a prefix tree on the list elements so you only compare as far as necessary.


问:
New valid date without time in javascript
I am using google charts and they require real dates for zoom in out etc.

So I have new Date('31/05/2019') that converts into same date with 02AM.

Is there a way to force 00:00:00 as time or to even use just date without time?

Now you may ask myself why would I do that when they have format option, well I need to use SteppedAreaChart that has problem with first day as it it showing that point on 0 axis.

To fix that I needed to add type="category", but now format doesn't work. It skips format option and puts the default one.

```<code>hAxis: {
  format: 'dd/MM/yy',
  type: 'category'
}
</code>```

I am getting this date from backend: 2019-05-31, And from that I get: May 31, 2019, 2:00:00 AM

答:
To set hours to 0:00:00 just use .setHours().

Either way, you can omit hours by using .toDateString():

        let today = new Date('2019-05-31')
        today.setHours(0,0,0) //this sets time to 0:00:00 in case you need it
        console.log(today.toDateString()); //Fri May 31 2019```

Body:
I am using google charts and they require real dates for zoom in out etc.

So I have new Date('31/05/2019') that converts into same date with 02AM.

Is there a way to force 00:00:00 as time or to even use just date without time?

Now you may ask myself why would I do that when they have format option, well I need to use SteppedAreaChart that has problem with first day as it it showing that point on 0 axis.

To fix that I needed to add type="category", but now format doesn't work. It skips format option and puts the default one.

hAxis: {
  format: 'dd/MM/yy',
  type: 'category'
}

I am getting this date from backend: 2019-05-31, And from that I get: May 31, 2019, 2:00:00 AM


问:
Dialogflow authentication programmatically java
Hi there I have an issue with the authentication of dialogflow. I know I have to set an GOOGLE_APPLICATION_CREDENTIALS or download Gcloud CLI to acces my agent. But since I am going to use multiple agents I need to login with credentials to my API. So I do not want to use these methods.

I saw in an other thread that there is a code available for node.js who does exactly this what I want.

Dialogflow easy way for authorization.

I want to be able to process my downloaded json file to get acces to the dialogflow agent.

This is what I tried:

```<code>//Load the json file
 String credential = "JSON{}"
 //Read the json file
 GoogleCredentials credentials = GoogleCredentials.fromStream(new
 ByteArrayInputStream(credential.getBytes()));
 //Read the project ID
 String projectId = ((ServiceAccountCredentials)credentials).getProjectId();
 System.out.println("the ID"+ projectId);
 //Read the token
 AccessToken token = ((ServiceAccountCredentials)credentials).getAccessToken();
 System.out.println("the token "+ token);
</code>```

It displays the projectID but the token is null. and the error I am receiving is

```<code>"message": "The Application Default Credentials are not available. They
are available if running in Google Compute Engine. Otherwise, the
environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined
pointing to a file defining the credentials. See
https://developers.google.com/accounts/docs/application-default-
credentials for more information.",
</code>```

So now I am stuck how can I programmatically connect to other agents? without using the GOOGLE_APPLICATION_CREDENTIALS in Java?

Please help me out

答:
I had the same problem and I think this is what you're looking for. I have copied the values of each agent configuration credentials json in my own config file, indexed by each projectId, and I read privatekey, privateKeyId, clientEmail, clientId, tokenServerUri from this config file.

Then I build a Credentials object with those values, and then a SessionSettings object with the credentials

This way you can forget about the GOOGLE_APPLICATION_CREDENTIALS environment variable

```<code>        PrivateKey privKey = null;

        StringBuilder pkcs8Lines = new StringBuilder();
        BufferedReader rdr = new BufferedReader(new StringReader(privatekey);

        String line;
        while ((line = rdr.readLine()) != null) {
            pkcs8Lines.append(line);
        }

        // Remove the "BEGIN" and "END" lines, as well as any whitespace

        String pkcs8Pem = pkcs8Lines.toString();
        pkcs8Pem = pkcs8Pem.replace("-----BEGIN PRIVATE KEY-----", "");
        pkcs8Pem = pkcs8Pem.replace("-----END PRIVATE KEY-----", "");
        pkcs8Pem = pkcs8Pem.replaceAll("\\s+", "");

        // Base64 decode the result

        byte[] pkcs8EncodedBytes = Base64.getDecoder().decode(pkcs8Pem);

        // extract the private key

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
        KeyFactory kf;
        try {
            kf = KeyFactory.getInstance("RSA");
            try {
                privKey = kf.generatePrivate(keySpec);
            } catch (InvalidKeySpecException e) {
                throw new GenericException(e);
            }
        } catch (NoSuchAlgorithmException e) {
            throw new GenericException(e);
        }

        Credentials myCredentials = ServiceAccountCredentials.newBuilder().setProjectId(projectId)
                .setPrivateKeyId(privateKeyId).setPrivateKey(privKey)
                .setClientEmail(clientEmail).setClientId(clientId)
                .setTokenServerUri(URI.create(tokenServerUri)).build();

        SessionsSettings sessionsSettings = SessionsSettings.newBuilder()
                .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)).build();

        try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) {
</code>```

Body:
Hi there I have an issue with the authentication of dialogflow. I know I have to set an GOOGLE_APPLICATION_CREDENTIALS or download Gcloud CLI to acces my agent. But since I am going to use multiple agents I need to login with credentials to my API. So I do not want to use these methods.

I saw in an other thread that there is a code available for node.js who does exactly this what I want.

Dialogflow easy way for authorization.

I want to be able to process my downloaded json file to get acces to the dialogflow agent.

This is what I tried:

//Load the json file
 String credential = "JSON{}"
 //Read the json file
 GoogleCredentials credentials = GoogleCredentials.fromStream(new
 ByteArrayInputStream(credential.getBytes()));
 //Read the project ID
 String projectId = ((ServiceAccountCredentials)credentials).getProjectId();
 System.out.println("the ID"+ projectId);
 //Read the token
 AccessToken token = ((ServiceAccountCredentials)credentials).getAccessToken();
 System.out.println("the token "+ token);

It displays the projectID but the token is null. and the error I am receiving is

"message": "The Application Default Credentials are not available. They
are available if running in Google Compute Engine. Otherwise, the
environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined
pointing to a file defining the credentials. See
https://developers.google.com/accounts/docs/application-default-
credentials for more information.",

So now I am stuck how can I programmatically connect to other agents? without using the GOOGLE_APPLICATION_CREDENTIALS in Java?

Please help me out

Body:
I had the same problem and I think this is what you're looking for. I have copied the values of each agent configuration credentials json in my own config file, indexed by each projectId, and I read privatekey, privateKeyId, clientEmail, clientId, tokenServerUri from this config file.

Then I build a Credentials object with those values, and then a SessionSettings object with the credentials

This way you can forget about the GOOGLE_APPLICATION_CREDENTIALS environment variable

        PrivateKey privKey = null;

        StringBuilder pkcs8Lines = new StringBuilder();
        BufferedReader rdr = new BufferedReader(new StringReader(privatekey);

        String line;
        while ((line = rdr.readLine()) != null) {
            pkcs8Lines.append(line);
        }

        // Remove the "BEGIN" and "END" lines, as well as any whitespace

        String pkcs8Pem = pkcs8Lines.toString();
        pkcs8Pem = pkcs8Pem.replace("-----BEGIN PRIVATE KEY-----", "");
        pkcs8Pem = pkcs8Pem.replace("-----END PRIVATE KEY-----", "");
        pkcs8Pem = pkcs8Pem.replaceAll("\\s+", "");

        // Base64 decode the result

        byte[] pkcs8EncodedBytes = Base64.getDecoder().decode(pkcs8Pem);

        // extract the private key

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
        KeyFactory kf;
        try {
            kf = KeyFactory.getInstance("RSA");
            try {
                privKey = kf.generatePrivate(keySpec);
            } catch (InvalidKeySpecException e) {
                throw new GenericException(e);
            }
        } catch (NoSuchAlgorithmException e) {
            throw new GenericException(e);
        }

        Credentials myCredentials = ServiceAccountCredentials.newBuilder().setProjectId(projectId)
                .setPrivateKeyId(privateKeyId).setPrivateKey(privKey)
                .setClientEmail(clientEmail).setClientId(clientId)
                .setTokenServerUri(URI.create(tokenServerUri)).build();

        SessionsSettings sessionsSettings = SessionsSettings.newBuilder()
                .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)).build();

        try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) {


问:
How do I reinterpret_cast between any two types?
I would like to re-declare the type of a given variable, but unfortunately reinterpret_cast<> does not help here. This line:

```<code>reinterpret_cast<std::vector<double>>(std::string("Hello"));
</code>```

results in the following compiler error:

```<code>invalid cast from type 'std::string {aka std::basic_string<char>}' to type 'std::vector<double>'
</code>```

Is there a different, clean approach?

Notes:

I know that reinterpret_cast<> is not a proper conversion. I really do only want to re-declare the type here. Some code around this line will make sure it is only performed when appropriate

Why actually does this line above not work?

I am aware of this option, which I think is too messy: *reinterpret_cast(&OldType)

Edit/Some context: This line will be part of a templated function, with:

```<code>reinterpret_cast<T>(std::string())
</code>```

For T == std::string this is completely fine, but unfortunately the compiler will also try to instantiate (but at runtime never use) it for T == std::vector<>. And this is C++11, so there is no static_if.

答:
You can't, it makes no sense to do so, and the compiler told you that.

reinterpret_cast can't hack a type into an entirely unrelated type.

Even if it did, such as with the pointer hackery you exhibit in your final bullet point, the language's rules prohibit you from using an object that's undergone such a cast.

Simply don't do it, because you can't.

If you're trying to construct a vector of doubles from a string (?), then do exactly that, writing the appropriate code to produce doubles from your string, in the manner proscribed by your business requirements.

The type system is there to help you. Let it.

Body:
I would like to re-declare the type of a given variable, but unfortunately reinterpret_cast<> does not help here. This line:

reinterpret_cast<std::vector<double>>(std::string("Hello"));

results in the following compiler error:

invalid cast from type 'std::string {aka std::basic_string<char>}' to type 'std::vector<double>'

Is there a different, clean approach?

Notes:

I know that reinterpret_cast<> is not a proper conversion. I really do only want to re-declare the type here. Some code around this line will make sure it is only performed when appropriate

Why actually does this line above not work?

I am aware of this option, which I think is too messy: *reinterpret_cast(&OldType)

Edit/Some context: This line will be part of a templated function, with:

reinterpret_cast<T>(std::string())

For T == std::string this is completely fine, but unfortunately the compiler will also try to instantiate (but at runtime never use) it for T == std::vector<>. And this is C++11, so there is no static_if.


问:
How To Access Callback Like in setState from useState Hook
Has anyone managed to create a sync callback for the update piece of the useState hook in react 16.8? I have been looking for one so that I can deal with synchronous actions with a 3rd party library and I can't seem to make one work for my needs.

If anyone has any references to people that have successfully completed this please add them here.

Cheers,

答:
You can use useEffect/useLayoutEffect to achieve this:

```<code>const SomeComponent = () => {
  const [count, setCount] = React.useState(0)

  React.useEffect(() => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  }, [count]);

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};
</code>```

If you are looking for an out of the box solution, check out this custom hook that works like useState but accepts as second parameter a callback function:

```<code>import useStateWithCallback from 'use-state-with-callback';

const SomeOtherComponent = () => {
  const [count, setCount] = useStateWithCallback(0, count => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  });

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};
</code>```

It can be installed via npm install use-state-with-callback

If you want to make synchrone layout updates, use import { useStateWithCallbackInstant } from 'use-state-with-callback'; instead.

Body:
You can use useEffect/useLayoutEffect to achieve this:

const SomeComponent = () => {
  const [count, setCount] = React.useState(0)

  React.useEffect(() => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  }, [count]);

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};

If you are looking for an out of the box solution, check out this custom hook that works like useState but accepts as second parameter a callback function:

import useStateWithCallback from 'use-state-with-callback';

const SomeOtherComponent = () => {
  const [count, setCount] = useStateWithCallback(0, count => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  });

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};

It can be installed via npm install use-state-with-callback

If you want to make synchrone layout updates, use import { useStateWithCallbackInstant } from 'use-state-with-callback'; instead.


问:
eclipse open error failed to find main class in eclipse\\plugins/org...jar
at the beginning it says that failed to find java jdk or jre so i installed it. then i run it again it came up this.
It says that "Failed to find a Main Class in ... eclipse\\plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar"

java file are under

```<code>C:\Program Files (x86)\Java\jre1.8.0_31 && jre7
C:\Program Files\Java\jdk1.8.0_31 && jre1.8.0_31
</code>```

my eclipse file are under

```<code>D:\迅雷下载\操作系统\eclipse
</code>```

can someone tell me how to fix this ??

答:
This is issue might be because of the folder location or the JDK version,
I installed the latest version JDK and with eclipse-inst-win64 provided by eclipse i was able to install and run successfully

Body:
at the beginning it says that failed to find java jdk or jre so i installed it. then i run it again it came up this.
It says that "Failed to find a Main Class in ... eclipse\\plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar"

java file are under

C:\Program Files (x86)\Java\jre1.8.0_31 && jre7
C:\Program Files\Java\jdk1.8.0_31 && jre1.8.0_31

my eclipse file are under

D:\迅雷下载\操作系统\eclipse

can someone tell me how to fix this ??


问:
How to implement sessions and logout in a react+node web application?
I am creating a webapp using  nodejs backend and reactjs frontend with a mysql database, where each user has their own separate set of data.

I need to maintain sessions to identify users(for example, which user clicked the reset password button) whilst also implementing the logout feature (necessary).

I have read articles stating that logout with jwt defeats the purpose as it requires storing tokens on database.

I am confused whether to use cookies(way less secure) or jwt with database for maintaining sessions as I have never implemented this before.

答: You can use JWT , when an user is authentified, you send back the token with a refresh token, that you store in your MySQL database, to your react app.</p>


问:
is there any Objective-C web crawler framework?
is there any Objective-C web crawler framework?</p>

答:
At this time there doesn't seem to be any widely used web spider/crawler Objective C kit or library.

WebCrawler (which was one of the first search engines) was apparently written, at least originally, in Objective C on the NeXT platform.  The author of that system mentioned that he might release it as open source once, way back when.  You might try contacting him to see if he would be willing to release a basic Objective C web crawler kit.  (He may not be able to do that, as he sold the WebCrawler company years ago.)

There is a shareware library which includes an Objective C spider called CkoSpider from "Chilkat".

There are quite a few (brief) discussions of this idea around the web (such as this one:  Can I build a web spider with WebKit?), with several folk apparently deciding over the years to roll their own.  My guess is that each of them had a relatively simple and specific project need, and never got to the point where they thought they had something of general interest. You might be able to get a critical mass of developer users of such a kit these days, what with all the renewed Objective C interest due to iPad and iPhone.  If you roll your own, consider doing it as a public github project, to see if you can tap into this interest.


问:
gio: file:///tmp/....pdf: No application is registered as handling this file
I have this code Python3.7 on Fedora 30 :

```<code>try :
    subprocess.call(["gio", "open", path_to_pdf])
</code>```

On others linux systems, including Fedora 29, the standalone application generated with Pyinstaller runs fine.

But when I run this generated code on Fedora 30, I'm facing this error :

```<code>    gio: file:///tmp/tmpxxxxx.pdf: No application is registered as handling this file
</code>```

Note :
I encountered some problem under Ubuntu/Mint/Debian, but could resolve it (acting on the system Linux) with that command :

```<code>    aa-complain /usr/bin/evince
</code>```

Is this the same kind of blocking on Fedora 30 ?

Thank you for your attention

答:
Problem solved :

This issue came from some kind of incompatibility between Matplotlib 3.0.1, and Pyinstaller 3.4.
Upgrading to Matplotlib 3.0.3 solved the problem...

Body:
I have this code Python3.7 on Fedora 30 :

try :
    subprocess.call(["gio", "open", path_to_pdf])

On others linux systems, including Fedora 29, the standalone application generated with Pyinstaller runs fine.

But when I run this generated code on Fedora 30, I'm facing this error :

    gio: file:///tmp/tmpxxxxx.pdf: No application is registered as handling this file

Note :
I encountered some problem under Ubuntu/Mint/Debian, but could resolve it (acting on the system Linux) with that command :

    aa-complain /usr/bin/evince

Is this the same kind of blocking on Fedora 30 ?

Thank you for your attention


问:
Predict.model() always returns wrong predictions
My goal: Load my pre-trained model and predict the probability of a single image.

I work with keras 2.2.4, tensorflow 1.12, and python 3.5.

I have trained the model using ImageDataGenerator() for the test and validation sets. Then, I used flow_from_directory() and fit_generator().

When I want to evaluate the model in another test set, I use ImageDataGenerator() and flow_from_directory(). The model.predict_generator() gives me the predictions I want, without a problem. The code is like this:

```<code>def evaluate_my_model(test_dir,  BATCH_SIZE = 100, image_size=(175, 100)):

    Test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input, samplewise_center=True,samplewise_std_normalization=True, horizontal_flip=True,fill_mode='nearest')
    # Create a generator for prediction
    Test_datagen = Test_datagen.flow_from_directory(test_dir,target_size=image_size, batch_size=BATCH_SIZE, class_mode='categorical', shuffle=False)
    # Get the predictions from the model using the generator
    _Score_predictions = model.predict_generator(Test_datagen, steps=Test_datagen.samples / Test_datagen.batch_size,  verbose=0)
    print(_Score_predictions)
    return _Score_predictions

MODEL_FILE = "/path/to/model/model.hdf5"
img_dir = "Path/to/images"
imgs = os.listdir(img_dir)
model = load_model(MODEL_FILE)
Score_predictions = evaluate_my_model(test_dir=img_dir, BATCH_SIZE=100, image_size=(175, 100))
</code>```

My Problem:
When I want to use the trained model to predict a single image, model.predict() returns always one of the classes (I am doing a binary classification). My code is as follows:

```<code>MODEL_FILE = "/path/to/model/model.hdf5"
img_dir = "Path/to/images"
imgs = os.listdir(img_dir)
model = load_model(MODEL_FILE)
model.summary()
for i, img in enumerate(imgs):
    img = Image.open(img_dir+"/"+img)
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    preds = model.predict(x)
    print(preds)
</code>```

The results of the code:

```<code>[[0. 1.]]
[[0. 1.]]
[[0. 1.]]
[[0. 1.]]
[[0. 1.]]
.
.
.
</code>```

[Expected results]: It is the results when I use model.predict_generator():

```<code>[[9.9975806e-01 2.4502163e-04]
 [1.1084620e-02 9.8872340e-01]
 [4.5869681e-05 9.9995399e-01]
 ...
 [6.5532902e-07 9.9999928e-01]
 [2.5114167e-07 9.9999976e-01]
 [9.5047617e-01 4.8345935e-02]]
</code>```

So, how can I change the first code to the second one correctly to receive the expected results?

答:
I realized where is the problem. I put my answer here maybe it helps the others with the same problem.

When training I used from keras.applications.resnet50 import preprocess_input, and mistakenly, I used from keras.applications.inception_v3 import InceptionV3, preprocess_input for evaluating my model.

Body:
My goal: Load my pre-trained model and predict the probability of a single image.

I work with keras 2.2.4, tensorflow 1.12, and python 3.5.

I have trained the model using ImageDataGenerator() for the test and validation sets. Then, I used flow_from_directory() and fit_generator().

When I want to evaluate the model in another test set, I use ImageDataGenerator() and flow_from_directory(). The model.predict_generator() gives me the predictions I want, without a problem. The code is like this:

def evaluate_my_model(test_dir,  BATCH_SIZE = 100, image_size=(175, 100)):

    Test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input, samplewise_center=True,samplewise_std_normalization=True, horizontal_flip=True,fill_mode='nearest')
    # Create a generator for prediction
    Test_datagen = Test_datagen.flow_from_directory(test_dir,target_size=image_size, batch_size=BATCH_SIZE, class_mode='categorical', shuffle=False)
    # Get the predictions from the model using the generator
    _Score_predictions = model.predict_generator(Test_datagen, steps=Test_datagen.samples / Test_datagen.batch_size,  verbose=0)
    print(_Score_predictions)
    return _Score_predictions

MODEL_FILE = "/path/to/model/model.hdf5"
img_dir = "Path/to/images"
imgs = os.listdir(img_dir)
model = load_model(MODEL_FILE)
Score_predictions = evaluate_my_model(test_dir=img_dir, BATCH_SIZE=100, image_size=(175, 100))

My Problem:
When I want to use the trained model to predict a single image, model.predict() returns always one of the classes (I am doing a binary classification). My code is as follows:

MODEL_FILE = "/path/to/model/model.hdf5"
img_dir = "Path/to/images"
imgs = os.listdir(img_dir)
model = load_model(MODEL_FILE)
model.summary()
for i, img in enumerate(imgs):
    img = Image.open(img_dir+"/"+img)
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    preds = model.predict(x)
    print(preds)

The results of the code:

[[0. 1.]]
[[0. 1.]]
[[0. 1.]]
[[0. 1.]]
[[0. 1.]]
.
.
.

[Expected results]: It is the results when I use model.predict_generator():

[[9.9975806e-01 2.4502163e-04]
 [1.1084620e-02 9.8872340e-01]
 [4.5869681e-05 9.9995399e-01]
 ...
 [6.5532902e-07 9.9999928e-01]
 [2.5114167e-07 9.9999976e-01]
 [9.5047617e-01 4.8345935e-02]]

So, how can I change the first code to the second one correctly to receive the expected results?


问:
Namespce OneTimeTearDownAttirbute () and OneTimeSetUpttirbute () does not exist in NUnit.Framework showing error in auto generated specflow(.cs) file
Facing build error The type or namespace name "OneTimeSetUpAttribute" and "OneTimeTearDownAttribute" doesnot exist

Xamarin.UITest-Version 3.0.0
Nunit- Version 2.6.4
NunitTestAdapter- Version 2.0.0
Specflow -Version 2.1.0.0

答:
OneTimeSetUpAttribute didn't exist until NUnit 3.0. You instead want to be using TestFixtureSetUpAttribute.

You can find the docs for NUnit 2.6.4 here: http://nunit.org/docs/2.6.4/docHome.html


问:
How to ping a website from Java Android Studio
I am currently developing an application with Android studio that needs an Internet connection to work. I would like to check the internet access at the start of the application by pinging my website. I already tried the method ConnectivityManager but it just checks if the user is connected to the wifi or mobile data. How could I ping any website to check if the phone has internet access?

答:
```<code>/**
 * Verifies if the device is connected to the internet.
 * @return
 */
public static boolean itsOnline(Context context) {
    try {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();

        StrictMode.setThreadPolicy(policy);

        int timeoutMs = 2000;
        Socket sock = new Socket();
        SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);

        sock.connect(sockaddr, timeoutMs);
        sock.close();
        Log.i("CONNECTION STATUS:", "connected");

        return true;
    } catch (IOException ioException) {
        Log.i("CONNECTION STATUS:", "disconnected");
        return false;
    }
    return false;
}
</code>```


问:
Jmeter BackendListener: How to use runtime variables
Trying to use BackendListener and observed runtime variables are not written to influxDB.

Predefined variables and properties, on the other hand, can be written to influx.

So I can separate test results by some ID by setting measurement=${__P(SOME_ID)}

What I'm looking for is a splitting results by thread group name, as I may have up to several dozens of them within the same test.

Tried to use following:

TAG_scenarioName=${__threadGroupName}

TAG_someJmeterVar=${SOME_JMETER_VAR}

TAG_someJmeterVarAsGroovy=${__groovy(vars.get("SOME_JMETER_VAR"),)}

eventTags=${__threadGroupName} testTitle=${__threadGroupName} (this

one makes less sense, but still..)

and none of those works

Those are works:
 - TAG_injectorName=${__machineName()}
 - TAG_predefinedVar=${USER_DEFINED_VAR} (I believe this is thanks to this)

So as I understand problem is with runtime variables only. Is it possible to make runtime variables accessible for the BackendListener? Or maybe there is some workaround for such case?

p.s. opened an enh for this

答:
Based on your inputs. Please try with "sample variables"
These are defined in user.properties like:-

```<code>sample_variables=FileName,retHREF,PageID,Redirect,StatusCode
</code>```

So, put all your variables in the sample_variables, restart jmeter and try. Please check if this helps.

Body:
Based on your inputs. Please try with "sample variables"
These are defined in user.properties like:-

sample_variables=FileName,retHREF,PageID,Redirect,StatusCode

So, put all your variables in the sample_variables, restart jmeter and try. Please check if this helps.


问:
PWA - file download works on android, not working on IOS
I have PWA application to create pdf report. When i click Generate raport on android all works fine, file is download, when i click Generate report, app redirect me to url to download pdf, for example my pdf url is http://generatemypdf.com/pdf?generate=true on android app download my report, on IOS, i be redirected to http://generatemypdf.com/pdf?generate=true in browser.
When i click Generate report then my app send post data to generate pdf.

My code to get file

```<code>  handleSubmit(event) {
    event.preventDefault();
    let form = store.get("form");

    window.open("http://generatemypdf.com/pdf?" + qs.stringify(form));
  }
</code>```

Where is bug?

答:
The problem is that Safari is blocking any call to window.open() which is made inside an async call.

Answer how to bypass that you can find here

Body:
I have PWA application to create pdf report. When i click Generate raport on android all works fine, file is download, when i click Generate report, app redirect me to url to download pdf, for example my pdf url is http://generatemypdf.com/pdf?generate=true on android app download my report, on IOS, i be redirected to http://generatemypdf.com/pdf?generate=true in browser.
When i click Generate report then my app send post data to generate pdf.

My code to get file

  handleSubmit(event) {
    event.preventDefault();
    let form = store.get("form");

    window.open("http://generatemypdf.com/pdf?" + qs.stringify(form));
  }

Where is bug?


问:
How do I fix blurry text in my HTML5 canvas?
I am a total n00b with HTML5 and am working with the canvas to render shapes, colors, and text. In my app, I have a view adapter that creates a canvas dynamically, and fills it with content. This works really nicely, except that my text is rendered very fuzzy/blurry/stretched. I have seen a lot of other posts on why defining the width and height in CSS will cause this issue, but I define it all in javascript.

The relevant code (view Fiddle):

var width  = 500;//FIXME:size.w;
var height = 500;//FIXME:size.h;

var canvas = document.createElement("canvas");
//canvas.className="singleUserCanvas";
canvas.width=width;
canvas.height=height;
canvas.border = "3px solid #999999";
canvas.bgcolor = "#999999";
canvas.margin = "(0, 2%, 0, 2%)";

var context = canvas.getContext("2d");

//////////////////
////  SHAPES  ////
//////////////////

var left = 0;

//draw zone 1 rect
context.fillStyle = "#8bacbe";
context.fillRect(0, (canvas.height*5/6)+1, canvas.width*1.5/8.5, canvas.height*1/6);

left = left + canvas.width*1.5/8.5;

//draw zone 2 rect
context.fillStyle = "#ffe381";
context.fillRect(left+1, (canvas.height*5/6)+1, canvas.width*2.75/8.5, canvas.height*1/6);

left = left + canvas.width*2.75/8.5 + 1;

//draw zone 3 rect
context.fillStyle = "#fbbd36";
context.fillRect(left+1, (canvas.height*5/6)+1, canvas.width*1.25/8.5, canvas.height*1/6);

left = left + canvas.width*1.25/8.5;

//draw target zone rect
context.fillStyle = "#004880";
context.fillRect(left+1, (canvas.height*5/6)+1, canvas.width*0.25/8.5, canvas.height*1/6);

left = left + canvas.width*0.25/8.5;

//draw zone 4 rect
context.fillStyle = "#f8961d";
context.fillRect(left+1, (canvas.height*5/6)+1, canvas.width*1.25/8.5, canvas.height*1/6);

left = left + canvas.width*1.25/8.5 + 1;

//draw zone 5 rect
context.fillStyle = "#8a1002";
context.fillRect(left+1, (canvas.height*5/6)+1, canvas.width-left, canvas.height*1/6);

////////////////
////  TEXT  ////
////////////////

//user name
context.fillStyle = "black";
context.font = "bold 18px sans-serif";
context.textAlign = 'right';
context.fillText("User Name", canvas.width, canvas.height*.05);

//AT:
context.font = "bold 12px sans-serif";
context.fillText("AT: 140", canvas.width, canvas.height*.1);

//AB:
context.fillText("AB: 94", canvas.width, canvas.height*.15);

//this part is done after the callback from the view adapter, but is relevant here to add the view back into the layout.
var parent = document.getElementById("layout-content");
parent.appendChild(canvas);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="layout-content"></div></code>```

The results I am seeing (in Safari) are much more skewed than shown in the Fiddle:

Mine

Fiddle

What am I doing incorrectly? Do I need a separate canvas for each text element? Is it the font? Am I required to first define the canvas in the HTML5 layout? Is there a typo? I am lost.

答:
Try this one line of CSS on your canvas:
image-rendering: pixelated

As per MDN:

When scaling the image up, the nearest-neighbor algorithm must be used, so that the image appears to be composed of large pixels.

Thus it prevents anti-aliasing entirely.

Body:
I am a total n00b with HTML5 and am working with the canvas to render shapes, colors, and text. In my app, I have a view adapter that creates a canvas dynamically, and fills it with content. This works really nicely, except that my text is rendered very fuzzy/blurry/stretched. I have seen a lot of other posts on why defining the width and height in CSS will cause this issue, but I define it all in javascript.

The relevant code (view Fiddle):

var width  = 500;//FIXME:size.w;
var height = 500;//FIXME:size.h;

var canvas = document.createElement("canvas");
//canvas.className="singleUserCanvas";
canvas.width=width;
canvas.height=height;
canvas.border = "3px solid #999999";
canvas.bgcolor = "#999999";
canvas.margin = "(0, 2%, 0, 2%)";

var context = canvas.getContext("2d");

//////////////////
////  SHAPES  ////
//////////////////

var left = 0;

//draw zone 1 rect
context.fillStyle = "#8bacbe";
context.fillRect(0, (canvas.height*5/6)+1, canvas.width*1.5/8.5, canvas.height*1/6);

left = left + canvas.width*1.5/8.5;

//draw zone 2 rect
context.fillStyle = "#ffe381";
context.fillRect(left+1, (canvas.height*5/6)+1, canvas.width*2.75/8.5, canvas.height*1/6);

left = left + canvas.width*2.75/8.5 + 1;

//draw zone 3 rect
context.fillStyle = "#fbbd36";
context.fillRect(left+1, (canvas.height*5/6)+1, canvas.width*1.25/8.5, canvas.height*1/6);

left = left + canvas.width*1.25/8.5;

//draw target zone rect
context.fillStyle = "#004880";
context.fillRect(left+1, (canvas.height*5/6)+1, canvas.width*0.25/8.5, canvas.height*1/6);

left = left + canvas.width*0.25/8.5;

//draw zone 4 rect
context.fillStyle = "#f8961d";
context.fillRect(left+1, (canvas.height*5/6)+1, canvas.width*1.25/8.5, canvas.height*1/6);

left = left + canvas.width*1.25/8.5 + 1;

//draw zone 5 rect
context.fillStyle = "#8a1002";
context.fillRect(left+1, (canvas.height*5/6)+1, canvas.width-left, canvas.height*1/6);

////////////////
////  TEXT  ////
////////////////

//user name
context.fillStyle = "black";
context.font = "bold 18px sans-serif";
context.textAlign = 'right';
context.fillText("User Name", canvas.width, canvas.height*.05);

//AT:
context.font = "bold 12px sans-serif";
context.fillText("AT: 140", canvas.width, canvas.height*.1);

//AB:
context.fillText("AB: 94", canvas.width, canvas.height*.15);

//this part is done after the callback from the view adapter, but is relevant here to add the view back into the layout.
var parent = document.getElementById("layout-content");
parent.appendChild(canvas);

The results I am seeing (in Safari) are much more skewed than shown in the Fiddle:

Mine

Fiddle

What am I doing incorrectly? Do I need a separate canvas for each text element? Is it the font? Am I required to first define the canvas in the HTML5 layout? Is there a typo? I am lost.


问:
discord.js bot replies to itself
I am currently coding my first discord bot, it can already play YouTube music.

if (message.content.includes("Good Job") ||
    message.content.includes("good job")) {
    message.channel.sendMessage("Good Job everyone :smirk:");
}
```

As you see, if someone types "good job" (this is just an example) then the bot will reply with "good job everyone :smirk:), but then the spam will begin: the bot reads his own message and replies to it.

How can I prevent the bot from answering itself?

答:
<pre class="lang-js prettyprint-override"><code>// In message event
if(message.author.id === client.user.id) return;

// I would recommend a variable like this for splits on words
// const args = message.content.trim().split(/\s+/g);
// You could also .slice() off a prefix if you have one

if(/good job/i.test(message.content)) {
  message.channel.send('Good job everyone :smirk:'); // sendMessage is deprecated, use send instead
}
</code>```

Title: discord.js bot replies to itself

Body:
I am currently coding my first discord bot, it can already play YouTube music.

if (message.content.includes("Good Job") ||
    message.content.includes("good job")) {
    message.channel.sendMessage("Good Job everyone :smirk:");
}

As you see, if someone types "good job" (this is just an example) then the bot will reply with "good job everyone :smirk:), but then the spam will begin: the bot reads his own message and replies to it.

How can I prevent the bot from answering itself?


问:
Is it safe to send a password unencrypted via an AJAX POST to a Flask Backend, should I encrypt it on the client side?
I have a form that I'm sending via AJAX to my Flask backend so I can skip the reload page, I've never really thought about it but is it wise to encrypt the password on the client side and decrypt it on the back end? What is the normal process for this? I'll be turning my Flask App into a desktop application using PyFlaDesk so it wont be hosted securely but on a users local machine, therefore it's only ever going to send the credentials to 'localhost:5000', do I even need to worry?</p>

```<code>   let credentials = {
        'client_id': $('#clientid').val(),
        'client_secret': $('#clientsecret').val(),
        'username': $('#username').val(),
        'password': $('#password').val(),
    }

    $.ajax({
        url: '/authorise',
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify({credentials}),
        dataType: "json",
        type: 'POST',
        success: function(response){
            console.log(response);
        },
        error: function(error){
            console.log(error);
        }
        });
</code>```

答:
The normal process on a remote server is to use https protocol instead of http.
The protocol will encrypt the data between client and server.

For server and client running on the same machine it's ok http.

In my system i only encrypt password to save on database.

Body:
I have a form that I'm sending via AJAX to my Flask backend so I can skip the reload page, I've never really thought about it but is it wise to encrypt the password on the client side and decrypt it on the back end? What is the normal process for this? I'll be turning my Flask App into a desktop application using PyFlaDesk so it wont be hosted securely but on a users local machine, therefore it's only ever going to send the credentials to 'localhost:5000', do I even need to worry?

   let credentials = {
        'client_id': $('#clientid').val(),
        'client_secret': $('#clientsecret').val(),
        'username': $('#username').val(),
        'password': $('#password').val(),
    }

    $.ajax({
        url: '/authorise',
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify({credentials}),
        dataType: "json",
        type: 'POST',
        success: function(response){
            console.log(response);
        },
        error: function(error){
            console.log(error);
        }
        });


问:
tf.keras.backend.get_session() and keras.backend.get_session() return different session objects
I've noticed that tf.keras.backend.get_session() and keras.backend.get_session() return different session objects.

Anyway to make sure they return the same object? I have some code that uses tf.keras.backend.get_session() to save a Keras model with tf.saved_model.simple_save but it throws an uninitialised error if the model comes from a library that uses keras instead of tensorflow.keras

Example code:

```<code>import tensorflow as tf
from keras.applications import ResNet50
import keras.backend as K
import tensorflow.keras.backend as J

model = ResNet50()
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

print(K.get_session())
print(J.get_session())
</code>```

答:
You have bigger issues, you should not mix code using keras and tf.keras, these modules are not compatible, and you will get weird errors if you mix them.

If you really have a good reason to change the session, you can use K.set_session to set the session manually to the object returned by the other implementation.

Body:
I've noticed that tf.keras.backend.get_session() and keras.backend.get_session() return different session objects.

Anyway to make sure they return the same object? I have some code that uses tf.keras.backend.get_session() to save a Keras model with tf.saved_model.simple_save but it throws an uninitialised error if the model comes from a library that uses keras instead of tensorflow.keras

Example code:

import tensorflow as tf
from keras.applications import ResNet50
import keras.backend as K
import tensorflow.keras.backend as J

model = ResNet50()
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

print(K.get_session())
print(J.get_session())


问:
A task failed to un-serialize
I'm trying to evaluate an ANN. I get the accuracies if I use n_jobs = 1, however, when I use n_jobs = - 1 I get the following error.
    BrokenProcessPool: A task has failed to un-serialize. Please ensure that the arguments of the function are all picklable.

I have tried using other numbers but it only works if I use n_jobs = 1

This is the code I am running:
    accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)

This is the error I am getting:

```<code> Traceback (most recent call last):
 File "<ipython-input-12-cc51c2d2980a>", line 1, in <module>
 accuracies = cross_val_score(estimator = classifier, X = X_train,
 y = y_train, cv = 10, n_jobs = -1)

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\model_selection\_validation.py", line 402, in
 cross_val_score
 error_score=error_score)

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\model_selection\_validation.py", line 240, in
 cross_validate
 for train, test in cv.split(X, y, groups))

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\externals\joblib\parallel.py", line 930, in __call__
 self.retrieve()

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\externals\joblib\parallel.py", line 833, in retrieve
 self._output.extend(job.get(timeout=self.timeout))

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\externals\joblib\_parallel_backends.py", line 521, in
 wrap_future_result
 return future.result(timeout=timeout)

 File "C:\Users\javie\Anaconda3\lib\concurrent\futures\_base.py", line
 432, in result
 return self.__get_result()

 File "C:\Users\javie\Anaconda3\lib\concurrent\futures\_base.py", line
 384, in __get_result
 raise self._exception

 BrokenProcessPool: A task has failed to un-serialize. Please ensure that
 the arguments of the function are all picklable.`
</code>```

Spyder should have analyzed each batch in parallel, but even when I use n_jobs = 1 it only analyzes 10 epochs.

答: This always happens when using multiprocessing in an iPython console in Spyder. A workaround is to run the script from the command line instead. </p>

Title: A task failed to un-serialize

Body:
I'm trying to evaluate an ANN. I get the accuracies if I use n_jobs = 1, however, when I use n_jobs = - 1 I get the following error.
    BrokenProcessPool: A task has failed to un-serialize. Please ensure that the arguments of the function are all picklable.

I have tried using other numbers but it only works if I use n_jobs = 1

This is the code I am running:
    accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)

This is the error I am getting:

 Traceback (most recent call last):
 File "<ipython-input-12-cc51c2d2980a>", line 1, in <module>
 accuracies = cross_val_score(estimator = classifier, X = X_train,
 y = y_train, cv = 10, n_jobs = -1)

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\model_selection\_validation.py", line 402, in
 cross_val_score
 error_score=error_score)

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\model_selection\_validation.py", line 240, in
 cross_validate
 for train, test in cv.split(X, y, groups))

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\externals\joblib\parallel.py", line 930, in __call__
 self.retrieve()

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\externals\joblib\parallel.py", line 833, in retrieve
 self._output.extend(job.get(timeout=self.timeout))

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\externals\joblib\_parallel_backends.py", line 521, in
 wrap_future_result
 return future.result(timeout=timeout)

 File "C:\Users\javie\Anaconda3\lib\concurrent\futures\_base.py", line
 432, in result
 return self.__get_result()

 File "C:\Users\javie\Anaconda3\lib\concurrent\futures\_base.py", line
 384, in __get_result
 raise self._exception

 BrokenProcessPool: A task has failed to un-serialize. Please ensure that
 the arguments of the function are all picklable.`

Spyder should have analyzed each batch in parallel, but even when I use n_jobs = 1 it only analyzes 10 epochs.


问:
Unable to create process : .ui to .py
I have been trying for a long time to generate a python code frome qtDesigner but I always have the same issue :

The command I used : pyuic5 ExtraInfo_Design.ui -o ExtraInfo_Designui.py

```<code>Fatal error in launcher: Unable to create process using '"c:\users\Dorian\appdata\local\programs\python\python37-32\python.exe"  "C:\Users\lDorian\Desktop\extrInfo\pyuic5.exe" ExtraInfo_Design.ui -o ExtraInfo_Designui.py'
</code>```

I think that all these problems happen because I changed the name of my laptop so I have other files that had been created "lDorian".

I have tried to open the shell as ana administrator.
I had tried to generate the code from a (.bat) file.
I had tried to add python path to the path directory.

Thanks, folks.

答:
After reinstalling Anaconda and all the version of python/pyqt that I already have,
I opened the cmd on Windows but I had the same problem.

The solution is:

After reinstalling all and deleting the python link in the path environment.

Open the Anaconda Powershell Prompt (not Anaconda Prompt) as an administrator

Type pip install pyqt5

then run : pyuic5 fileName.ui -o fileName.py

Have a nice day.

Title: Unable to create process : .ui to .py

Body:
I have been trying for a long time to generate a python code frome qtDesigner but I always have the same issue :

The command I used : pyuic5 ExtraInfo_Design.ui -o ExtraInfo_Designui.py

Fatal error in launcher: Unable to create process using '"c:\users\Dorian\appdata\local\programs\python\python37-32\python.exe"  "C:\Users\lDorian\Desktop\extrInfo\pyuic5.exe" ExtraInfo_Design.ui -o ExtraInfo_Designui.py'

I think that all these problems happen because I changed the name of my laptop so I have other files that had been created "lDorian".

I have tried to open the shell as ana administrator.
I had tried to generate the code from a (.bat) file.
I had tried to add python path to the path directory.

Thanks, folks.


问:
What is the meaning of ":" in this TypeScript code?
I can't understand what is the meaning of second : in this code:

```<code>  getDish(id: number): Observable<Dish> {
    return  this.restangular.one('dishes',id).get();
  }
</code>```

I know the first : means id has the type number, and it is the input argument of getDish() function. But what do does the second : do? Is it the output type of the getDish() function and means the output is an object of Dish class with the Observable type?

答:
Please check the explaination below</p>

```<code>id: number <-- type of the id variable is number
getDish(id: number): Observable<Dish> <-- the return value of the function i GetDish is of type Observable<Dish>
</code>```

Body:
I can't understand what is the meaning of second : in this code:

  getDish(id: number): Observable<Dish> {
    return  this.restangular.one('dishes',id).get();
  }

I know the first : means id has the type number, and it is the input argument of getDish() function. But what do does the second : do? Is it the output type of the getDish() function and means the output is an object of Dish class with the Observable type?

Body:
Please check the explaination below

id: number <-- type of the id variable is number
getDish(id: number): Observable<Dish> <-- the return value of the function i GetDish is of type Observable<Dish>


问:
Include file.php + id. Is this possible with php?
I've built my site with php include and the index is as follows:

Menu.php (menu system)

main.php (Index site)

footer.php (footer obv.)

Anyway, when main.php (index) opens, I've added a news script that uses $_GET to fetch the news-data from our mysql database. This generates an ID for each news, and it shows only a few characters of the full news.

So, I've added a link in each news that says "Read more" to expand the news, it looks like this:

```<code><a href="news.php?id=<?=$row['id']?>">Read More</a></p>
</code>```

So, is there a way for me to include this site (replace news.php?id=x with main.php)?

It gives me syntax error when I'm trying to use <?php include in the link since it's already using <?=$row['id']?>.

The only help I got so far are people telling me to change the menu system to Javascript (Ajax, Jquery) but I'm not too familiar with this. Is there something I can do more simple than changing the menu to javascript?

Thanks for your help and understanding,

Have a great day!

答:
leave your link as is, it's fine.

do not include main into news.

include only menu and footer into news.

Body:
I've built my site with php include and the index is as follows:

Menu.php (menu system)

main.php (Index site)

footer.php (footer obv.)

Anyway, when main.php (index) opens, I've added a news script that uses $_GET to fetch the news-data from our mysql database. This generates an ID for each news, and it shows only a few characters of the full news.

So, I've added a link in each news that says "Read more" to expand the news, it looks like this:

<a href="news.php?id=<?=$row['id']?>">Read More

So, is there a way for me to include this site (replace news.php?id=x with main.php)?

It gives me syntax error when I'm trying to use <?php include in the link since it's already using <?=$row['id']?>.

The only help I got so far are people telling me to change the menu system to Javascript (Ajax, Jquery) but I'm not too familiar with this. Is there something I can do more simple than changing the menu to javascript?

Thanks for your help and understanding,

Have a great day!


问:
How to display a byte array as hex values
```<code>>>> struct.pack('2I',12, 30)
b'\x0c\x00\x00\x00\x1e\x00\x00\x00'
>>> struct.pack('2I',12, 31)
b'\x0c\x00\x00\x00\x1f\x00\x00\x00'
>>> struct.pack('2I',12, 32)
b'\x0c\x00\x00\x00 \x00\x00\x00'
                  ^in question
>>> struct.pack('2I',12, 33)
b'\x0c\x00\x00\x00!\x00\x00\x00'
                  ^in question
</code>```

<p>I'd like all values to display as hex </p>

答:
In Python 3.7, bytes objects don't have an encode() method; the following code doesn't work anymore.

import struct

hex_str = struct.pack('2I',12, 30).encode('hex')
```
<p>Instead of <code>encode()</code>, Python 3.7 code should use the <code>hex()</code> method, introduced in Python 3.5.</p>
<pre class="lang-py prettyprint-override"><code>import struct

# hex_str will contain the '0c0000001e000000' string.
hex_str = struct.pack('2I',12, 30).hex()
</code>```

Body:
>>> struct.pack('2I',12, 30)
b'\x0c\x00\x00\x00\x1e\x00\x00\x00'
>>> struct.pack('2I',12, 31)
b'\x0c\x00\x00\x00\x1f\x00\x00\x00'
>>> struct.pack('2I',12, 32)
b'\x0c\x00\x00\x00 \x00\x00\x00'
                  ^in question
>>> struct.pack('2I',12, 33)
b'\x0c\x00\x00\x00!\x00\x00\x00'
                  ^in question

I'd like all values to display as hex

Body:
In Python 3.7, bytes objects don't have an encode() method; the following code doesn't work anymore.

import struct

hex_str = struct.pack('2I',12, 30).encode('hex')

Instead of encode(), Python 3.7 code should use the hex() method, introduced in Python 3.5.

import struct

# hex_str will contain the '0c0000001e000000' string.
hex_str = struct.pack('2I',12, 30).hex()


问:
Print QrCode from php escpos Toshiba compatible
I'm trying to print with a Toshiba 4610-1nr, compatible with escpos, emulating Epson TM-T88II a receipt.

All works but not the QR code.

I tried some code but none works

I'm able to print everything, but not the QR code, the barcode works... but not the QR code.

```<code><?php
header('Content-Type: text/html; charset=utf-8');
/* ASCII constants */
const ESC = "\x1b";
const GS="\x1d";
const NUL="\x00";
const BAR="\x1c";

/* Output an example receipt */
define('EURO',chr(128));
echo ESC."t".chr(19); // table 19 lituana // 858 multilingual
echo ESC."a".chr(0); // Left print
echo "MY PLACE\n";
echo ESC."a".chr(0); // Left print
echo "Description my place\n";
echo ESC."a".chr(0); // Left print
echo "Adress my place\n";
echo ESC."a".chr(1); // Center print
echo " \n";
echo " \n";
echo " \n";
echo "header text\n";
echo "header text\n";
echo " \n";
echo " \n";
echo ESC."a".chr(0); // Left print
echo "DESCRIPTION";
echo ESC."a".chr(2); // right print
echo "VAT ";
echo "PRICE(".EURO.")";
echo ESC."a".chr(0); // Left print
echo ESC."!".chr(16); // doppia altezza
echo "SUBTOTAL\n";
echo ESC."!".chr(0); // 4 Blank lines
echo ESC."a".chr(0); // Left print
echo "VAT\n";
echo " \n";
echo "Importo pagato\n";
echo " \n";
echo ESC."a".chr(1); // Center print

echo ESC."d".chr(1); // Blank line
echo GS."h".chr(60); // seleziono hight
echo GS."w".chr(1); // seleziono widht
echo GS."m".chr(8); // code128
echo GS."k".chr(4)."0000MFDFMD0000".chr(0);
echo ESC."d".chr(1); // Blank line

echo ESC."d".chr(1); // Blank line
echo GS."k".chr(4)."70707007";
echo ESC."d".chr(1); // Blank line

echo ESC."d".chr(1); // Blank line
//echo GS."k".chr(49).chr(81)."fdhfhsl";
//echo GS."k".chr(49).chr(81)."fdhfhsl";

echo ESC."d".chr(1); // Blank line
//echo qr code GS."k".chr(28).chr(4).chr(49).chr(81)."httpsooostackoverflowocomom44";

//echo ESC."v".chr(1); // Blank line
echo ESC."V".chr(66).chr(0); // Cut
exit(0);
?>
</code>```

Body:
I'm trying to print with a Toshiba 4610-1nr, compatible with escpos, emulating Epson TM-T88II a receipt.

All works but not the QR code.

I tried some code but none works

I'm able to print everything, but not the QR code, the barcode works... but not the QR code.

<?php
header('Content-Type: text/html; charset=utf-8');
/* ASCII constants */
const ESC = "\x1b";
const GS="\x1d";
const NUL="\x00";
const BAR="\x1c";

/* Output an example receipt */
define('EURO',chr(128));
echo ESC."t".chr(19); // table 19 lituana // 858 multilingual
echo ESC."a".chr(0); // Left print
echo "MY PLACE\n";
echo ESC."a".chr(0); // Left print
echo "Description my place\n";
echo ESC."a".chr(0); // Left print
echo "Adress my place\n";
echo ESC."a".chr(1); // Center print
echo " \n";
echo " \n";
echo " \n";
echo "header text\n";
echo "header text\n";
echo " \n";
echo " \n";
echo ESC."a".chr(0); // Left print
echo "DESCRIPTION";
echo ESC."a".chr(2); // right print
echo "VAT ";
echo "PRICE(".EURO.")";
echo ESC."a".chr(0); // Left print
echo ESC."!".chr(16); // doppia altezza
echo "SUBTOTAL\n";
echo ESC."!".chr(0); // 4 Blank lines
echo ESC."a".chr(0); // Left print
echo "VAT\n";
echo " \n";
echo "Importo pagato\n";
echo " \n";
echo ESC."a".chr(1); // Center print

echo ESC."d".chr(1); // Blank line
echo GS."h".chr(60); // seleziono hight
echo GS."w".chr(1); // seleziono widht
echo GS."m".chr(8); // code128
echo GS."k".chr(4)."0000MFDFMD0000".chr(0);
echo ESC."d".chr(1); // Blank line

echo ESC."d".chr(1); // Blank line
echo GS."k".chr(4)."70707007";
echo ESC."d".chr(1); // Blank line

echo ESC."d".chr(1); // Blank line
//echo GS."k".chr(49).chr(81)."fdhfhsl";
//echo GS."k".chr(49).chr(81)."fdhfhsl";

echo ESC."d".chr(1); // Blank line
//echo qr code GS."k".chr(28).chr(4).chr(49).chr(81)."httpsooostackoverflowocomom44";

//echo ESC."v".chr(1); // Blank line
echo ESC."V".chr(66).chr(0); // Cut
exit(0);
?>

Body:
def generate_qr(self, data, size= b'\x09'):
    return b'\x1D\x28\x6B\x04\x00\x31\x41\x32\x00\x1D\x28\x6B\x03\x00\x31\x43' + size + \
           b'\x1D\x28\x6B\x03\x00\x31\x43\x51' + b'\x1D\x28\x6B' \
           + (len(data) + 3).to_bytes(2, byteorder="little") + \
           b'\x31\x50\x30' + data.encode() + b'\x1D\x28\x6B\x03\x00\x31\x51\x30'

this will output

b'\x1d(k\x04\x001A2\x00\x1d(k\x03\x001C\x04\x1d(k\x03\x001CQ\x1d(k=\x001P01111111111111111111111111111112222222222tyrytryryt12312312\x1d(k\x03\x001Q0'

if you echo -en '\x1d(k\x04\x001A2\x00\x1d(k\x03\x001C\x04\x1d(k\x03\x001CQ\x1d(k=\x001P01111111111111111111111111111112222222222tyrytryryt12312312\x1d(k\x03\x001Q0' >/dev/usb/lp0 #considering lp0 is your thermal printer will print you the qr code


问:
SharePoint : How to check for null with a CAML Query?
I have this CAML:

```<code>query.Query = @"<Where><Eq><FieldRef Name='MessageID' /><Value Type='Text'></Value></Eq></Where>";
</code>```

This checks if the value of MessageID = string.empty()

What I would like to check for is null.... not empty string...

Is this possible with CAML?

答:
You can Check for Nulls using: IsNotNull element (Query).

Used within a query to return items that are not empty (Null).

Example:

```<code><IsNotNull>
   <FieldRef Name = "Field_Name"/>
   <Value Type = "Field_Type"/>
   <XML />
</IsNotNull>
</code>```

You can Check for Nulls using: IsNull element (Query).

Used within a query to return items that are empty (Null).

Example:

```<code><IsNull>
   <FieldRef Name = "Field_Name"/>
     <Value Type = "Field_Type"/>
   <XML />
</IsNull>
</code>```

Body:
I have this CAML:

query.Query = @"<Where><Eq><FieldRef Name='MessageID' /><Value Type='Text'></Value></Eq></Where>";

This checks if the value of MessageID = string.empty()

What I would like to check for is null.... not empty string...

Is this possible with CAML?

Body:
You can Check for Nulls using: IsNotNull element (Query).

Used within a query to return items that are not empty (Null).

Example:

<IsNotNull>
   <FieldRef Name = "Field_Name"/>
   <Value Type = "Field_Type"/>
   <XML />
</IsNotNull>

You can Check for Nulls using: IsNull element (Query).

Used within a query to return items that are empty (Null).

Example:

<IsNull>
   <FieldRef Name = "Field_Name"/>
     <Value Type = "Field_Type"/>
   <XML />
</IsNull>


问:
Count frequency of text in list in dataframe
I’m new to python / pandas but have a question which I’ll ask logically to help me learn

I have a dataframe called parties with the following data

```<code>(index)    name                  invitees
0            birthday party     [mike, peter]
1            Retirement          [peter]
2            office opening     [simon, mike, peter]
</code>```

I’d like to be able to create a dictionary which will show the distinct names from the invitees column along with frequency e.g. something like this

```<code>mike: 2, peter: 3, simon: 1
</code>```

I’ve tried to find something similar on here but I’m not too sure of the right terminology to use.

Any help would be greatly appreciated
Thanks a lot

答:
Collect names from data frame and then use Counter:

```<code>from collections import Counter
import pandas as pd

# setup test data
data = {'invitees': [['mike', 'peter'], ['peter'], ['simon', 'mike', 'peter']]}
data = pd.DataFrame(data=data)

# select data series
names_lists = data['invitees']

# collect names
all_names = []
for item in names_lists:
    for name in item:
        all_names.append(name)

# count occurrence
summary = Counter(all_names)
</code>```

Output:

```<code>{'peter': 3, 'mike': 2, 'simon': 1}
</code>```

Body:
I’m new to python / pandas but have a question which I’ll ask logically to help me learn

I have a dataframe called parties with the following data

(index)    name                  invitees
0            birthday party     [mike, peter]
1            Retirement          [peter]
2            office opening     [simon, mike, peter]

I’d like to be able to create a dictionary which will show the distinct names from the invitees column along with frequency e.g. something like this

mike: 2, peter: 3, simon: 1

I’ve tried to find something similar on here but I’m not too sure of the right terminology to use.

Any help would be greatly appreciated
Thanks a lot

Body:
Collect names from data frame and then use Counter:

from collections import Counter
import pandas as pd

# setup test data
data = {'invitees': [['mike', 'peter'], ['peter'], ['simon', 'mike', 'peter']]}
data = pd.DataFrame(data=data)

# select data series
names_lists = data['invitees']

# collect names
all_names = []
for item in names_lists:
    for name in item:
        all_names.append(name)

# count occurrence
summary = Counter(all_names)

Output:

{'peter': 3, 'mike': 2, 'simon': 1}