问:
Getting an index to run one at a time in a for loop
I have a quick question here. Is there a way to stop a for loop and wait for one index to be done before the next one can execute? I'll try to be clear as much as possible so apologize if my question and my code aren't clear enough. Plus, I will give more explanation for whatever clues that you can give me. Much appreciate

So I try to get each id to put on my API, in order to trigger the script to be run. However, the requirement is 1 script has to be done first before the next one can be trigger.

I was messing around with setTimeOut() but looks like it doesn't give me what I need. And sorry guys, my project isn't allowed me to work with any external libraries and either async await

```<code> function sampleScriptRunning(activity){
    var ID = activity.map(function(activity){return activity.ID})
             for(var i = 0; i < ID.length; i++){
                      if(ID[i] === 'undefined'){
                        console.log('No more scripts to run')
                        return;
                            }
       Api.getActivityStatus(ID[i]).then(function(response){
   return $http.post('/proxy/api/nodejsjob/' + response.sample.sample[0].ScriptId + '/run')
       })
</code>```

答:
If you're trying to manage asynchronous calls in series, you have two options - Promise objects, or managing callbacks yourself.

One powerful tool you can use is the mapSeries functionality of bluebird, a npm module for promise management. That way, you can execute the commands only one at a time without any other management:

```<code>const Promise = require('bluebird');

const ids = activities.map((activity) => activity.id);
return Promise.mapSeries(ids, (id) => {
  return Api.getActivityStatus(ID[i])
    .then(() => $http.post('/proxy/api/nodejsjob/' + response.sample.sample[0].ScriptId + '/run'))
});
</code>```

Body:
I have a quick question here. Is there a way to stop a for loop and wait for one index to be done before the next one can execute? I'll try to be clear as much as possible so apologize if my question and my code aren't clear enough. Plus, I will give more explanation for whatever clues that you can give me. Much appreciate

So I try to get each id to put on my API, in order to trigger the script to be run. However, the requirement is 1 script has to be done first before the next one can be trigger.

I was messing around with setTimeOut() but looks like it doesn't give me what I need. And sorry guys, my project isn't allowed me to work with any external libraries and either async await

 function sampleScriptRunning(activity){
    var ID = activity.map(function(activity){return activity.ID})
             for(var i = 0; i < ID.length; i++){
                      if(ID[i] === 'undefined'){
                        console.log('No more scripts to run')
                        return;
                            }
       Api.getActivityStatus(ID[i]).then(function(response){
   return $http.post('/proxy/api/nodejsjob/' + response.sample.sample[0].ScriptId + '/run')
       })

Body:
If you're trying to manage asynchronous calls in series, you have two options - Promise objects, or managing callbacks yourself.

One powerful tool you can use is the mapSeries functionality of bluebird, a npm module for promise management. That way, you can execute the commands only one at a time without any other management:

const Promise = require('bluebird');

const ids = activities.map((activity) => activity.id);
return Promise.mapSeries(ids, (id) => {
  return Api.getActivityStatus(ID[i])
    .then(() => $http.post('/proxy/api/nodejsjob/' + response.sample.sample[0].ScriptId + '/run'))
});


来源: stackexchange

问:
java.io.IOException Permission denied even after asking the permision
I'm having an exception on some devices (both pre and post api 23):

```<code>Non-fatal Exception: java.io.IOException
Permission denied

imageFile.createNewFile();
</code>```

In my AndroidManifest.xml I do have the permission:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

And calling it only after granting the Manifest.permission.WRITE_EXTERNAL_STORAGE permission (api 23+)

```<code>String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (EasyPermissions.hasPermissions(getActivity(), perms)) {
// Call it
} else {
   EasyPermissions.requestPermissions(this,
           getString(R.string.please_grant_permission),
           RC_SAVE,
           perms);
}
</code>```

Here's my code:

```<code> File downloadsFolder = Environment.getExternalStoragePublicDirectory(
         Environment.DIRECTORY_DOWNLOADS);
 if (!downloadsFolder.exists()) {
     downloadsFolder.mkdir();
 }

 File imageFile = new File(downloadsFolder, fileName);

 if (!imageFile.exists()) {
     try {
         imageFile.createNewFile(); // Error on some devices
...
</code>```

Statistics: https://imgur.com/B9noOb6
Statistics: https://imgur.com/DsoeO2B

答:
The following is a solution for minSdkVersion 15 & targetSdkVersion 28.

Working code snippet based on your problem is as below,

Image Downloaded Successfully Snapshot

Code Layout View

build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.zackdawood.albummanager"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code>```

strings.xml

```<code><resources>
    <string name="app_name">AlbumManager</string>
    <string name="write_button">Write Image</string>
    <string name="read_button">Read Image</string>
    <string name="request_access">Request Access</string>
</resources>
</code>```

external_files.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>
</code>```

network_security_config.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">maven.apache.org</domain>
    <domain includeSubdomains="true">upload.wikimedia.org</domain>
</domain-config>
</network-security-config>
</code>```

GenericFileProvider.java

```<code>package com.zackdawood.albummanager;

import android.support.v4.content.FileProvider;

public class GenericFileProvider extends FileProvider {
}
</code>```

FileDownloader.java

```<code>package com.zackdawood.albummanager;

import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileDownloader {

    private static final String TAG = "FileDownloader";

    private static final int MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory) {
        try {
            Log.v(TAG, "downloadFile() invoked ");
            Log.v(TAG, "downloadFile() fileUrl " + fileUrl);
            Log.v(TAG, "downloadFile() directory " + directory);

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
            Log.v(TAG, "downloadFile() completed ");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        }
    }
}
</code>```

MainActivity.java

```<code>package com.zackdawood.albummanager;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.INTERNET};

    private static boolean hasPermissions(Context context, String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 112);
        Log.v(TAG, "onCreate() Method invoked ");
    }

    public void write(View view) {
        if (!hasPermissions(MainActivity.this, PERMISSIONS)) {

            Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");

            Toast t = Toast.makeText(getApplicationContext(), "You don't have write access !", Toast.LENGTH_LONG);
            t.show();

        } else {

            new DownloadFile().execute("https://upload.wikimedia.org/wikipedia/commons/thumb/c/c2/Adler.jpg/547px-Adler.jpg", "lab_result_2019-04-06.jpg");

        }
    }

    public void read(View view) {
        if (!hasPermissions(MainActivity.this, PERMISSIONS)) {

            Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");

            Toast t = Toast.makeText(getApplicationContext(), "You don't have read access !", Toast.LENGTH_LONG);
            t.show();

        } else {

            File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);

            File directory = new File(folder + "/TB System");
            File imgFile = new File(directory, "lab_result_2019-04-06.jpg");

            Log.v(TAG, "view() Method imgfile " + imgFile.getAbsolutePath());

            Uri path = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", imgFile);

            Log.v(TAG, "view() Method path " + path);

            Intent imageIntent = new Intent(Intent.ACTION_VIEW);
            imageIntent.setDataAndType(path, "image/*");
            imageIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            imageIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            try {
                startActivity(imageIntent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(MainActivity.this, "No Application available to view Image", Toast.LENGTH_SHORT).show();
            }

        }
    }

    public void request(View view) {
        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 112);

    }

    private class DownloadFile extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... strings) {
            Log.v(TAG, "doInBackground() Method invoked ");

            String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
            String fileName = strings[1];  // -> maven.pdf
            File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);

            File directory = new File(folder + "/TB System");
            if (!directory.exists()) {
                directory.mkdir();
                Log.v(TAG, "doInBackground() Method Directory Created ");

            }

            File imgFile = new File(directory, fileName);
            Log.v(TAG, "doInBackground() imgFile invoked " + imgFile.getAbsolutePath());
            Log.v(TAG, "doInBackground() imgFile invoked " + imgFile.getAbsoluteFile());

            try {
                imgFile.createNewFile();
                Log.v(TAG, "doInBackground() file created" + imgFile);

            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "doInBackground() error" + e.getMessage());
                Log.e(TAG, "doInBackground() error" + e.getStackTrace());

            }
            FileDownloader.downloadFile(fileUrl, imgFile);
            Log.v(TAG, "doInBackground() file download completed");

            return null;
        }
    }

}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="395dp"
        android:layout_height="715dp"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/write_button"
            android:onClick="write"/>

        <Button
            android:id="@+id/button3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/read_button"
            android:onClick="read"/>

        <Button
            android:id="@+id/button4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/request_access"
            android:onClick="request"/>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zackdawood.albummanager">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:networkSecurityConfig="@xml/network_security_config">
        <provider
            android:name=".GenericFileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/external_files"/>
        </provider>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
</code>```

App Launcher Screen

Read Image Output

ContentLicense: CC BY-SA 4.0

Body:
I'm having an exception on some devices (both pre and post api 23):

Non-fatal Exception: java.io.IOException
Permission denied

imageFile.createNewFile();

In my AndroidManifest.xml I do have the permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

And calling it only after granting the Manifest.permission.WRITE_EXTERNAL_STORAGE permission (api 23+)

String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (EasyPermissions.hasPermissions(getActivity(), perms)) {
// Call it
} else {
   EasyPermissions.requestPermissions(this,
           getString(R.string.please_grant_permission),
           RC_SAVE,
           perms);
}

Here's my code:

 File downloadsFolder = Environment.getExternalStoragePublicDirectory(
         Environment.DIRECTORY_DOWNLOADS);
 if (!downloadsFolder.exists()) {
     downloadsFolder.mkdir();
 }

 File imageFile = new File(downloadsFolder, fileName);

 if (!imageFile.exists()) {
     try {
         imageFile.createNewFile(); // Error on some devices
...

Statistics: https://imgur.com/B9noOb6
Statistics: https://imgur.com/DsoeO2B

Body:
The following is a solution for minSdkVersion 15 & targetSdkVersion 28.

Working code snippet based on your problem is as below,

Image Downloaded Successfully Snapshot

Code Layout View

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.zackdawood.albummanager"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

strings.xml

<resources>
    <string name="app_name">AlbumManager</string>
    <string name="write_button">Write Image</string>
    <string name="read_button">Read Image</string>
    <string name="request_access">Request Access</string>
</resources>

external_files.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">maven.apache.org</domain>
    <domain includeSubdomains="true">upload.wikimedia.org</domain>
</domain-config>
</network-security-config>

GenericFileProvider.java

package com.zackdawood.albummanager;

import android.support.v4.content.FileProvider;

public class GenericFileProvider extends FileProvider {
}

FileDownloader.java

package com.zackdawood.albummanager;

import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileDownloader {

    private static final String TAG = "FileDownloader";

    private static final int MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory) {
        try {
            Log.v(TAG, "downloadFile() invoked ");
            Log.v(TAG, "downloadFile() fileUrl " + fileUrl);
            Log.v(TAG, "downloadFile() directory " + directory);

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
            Log.v(TAG, "downloadFile() completed ");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        }
    }
}

MainActivity.java

package com.zackdawood.albummanager;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.INTERNET};

    private static boolean hasPermissions(Context context, String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 112);
        Log.v(TAG, "onCreate() Method invoked ");
    }

    public void write(View view) {
        if (!hasPermissions(MainActivity.this, PERMISSIONS)) {

            Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");

            Toast t = Toast.makeText(getApplicationContext(), "You don't have write access !", Toast.LENGTH_LONG);
            t.show();

        } else {

            new DownloadFile().execute("https://upload.wikimedia.org/wikipedia/commons/thumb/c/c2/Adler.jpg/547px-Adler.jpg", "lab_result_2019-04-06.jpg");

        }
    }

    public void read(View view) {
        if (!hasPermissions(MainActivity.this, PERMISSIONS)) {

            Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");

            Toast t = Toast.makeText(getApplicationContext(), "You don't have read access !", Toast.LENGTH_LONG);
            t.show();

        } else {

            File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);

            File directory = new File(folder + "/TB System");
            File imgFile = new File(directory, "lab_result_2019-04-06.jpg");

            Log.v(TAG, "view() Method imgfile " + imgFile.getAbsolutePath());

            Uri path = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", imgFile);

            Log.v(TAG, "view() Method path " + path);

            Intent imageIntent = new Intent(Intent.ACTION_VIEW);
            imageIntent.setDataAndType(path, "image/*");
            imageIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            imageIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            try {
                startActivity(imageIntent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(MainActivity.this, "No Application available to view Image", Toast.LENGTH_SHORT).show();
            }

        }
    }

    public void request(View view) {
        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 112);

    }

    private class DownloadFile extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... strings) {
            Log.v(TAG, "doInBackground() Method invoked ");

            String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
            String fileName = strings[1];  // -> maven.pdf
            File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);

            File directory = new File(folder + "/TB System");
            if (!directory.exists()) {
                directory.mkdir();
                Log.v(TAG, "doInBackground() Method Directory Created ");

            }

            File imgFile = new File(directory, fileName);
            Log.v(TAG, "doInBackground() imgFile invoked " + imgFile.getAbsolutePath());
            Log.v(TAG, "doInBackground() imgFile invoked " + imgFile.getAbsoluteFile());

            try {
                imgFile.createNewFile();
                Log.v(TAG, "doInBackground() file created" + imgFile);

            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "doInBackground() error" + e.getMessage());
                Log.e(TAG, "doInBackground() error" + e.getStackTrace());

            }
            FileDownloader.downloadFile(fileUrl, imgFile);
            Log.v(TAG, "doInBackground() file download completed");

            return null;
        }
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="395dp"
        android:layout_height="715dp"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/write_button"
            android:onClick="write"/>

        <Button
            android:id="@+id/button3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/read_button"
            android:onClick="read"/>

        <Button
            android:id="@+id/button4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/request_access"
            android:onClick="request"/>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zackdawood.albummanager">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:networkSecurityConfig="@xml/network_security_config">
        <provider
            android:name=".GenericFileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/external_files"/>
        </provider>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

App Launcher Screen

Read Image Output


问:
inline xaml in html document
How could I view XAML code inside html document, this is my XAML code:

```<code><Canvas Name="myxaml"
        Width="618.125"
        Height="37.325001"
        ClipToBounds="True"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Canvas Name="g10"
            RenderTransform="1.25,0,0,-1.25,0,37.325001">
        <Canvas Name="g12">
            <Path Fill="#FF000000"
                  Name="path16">
                <Path.Data>
                    <PathGeometry FillRule="Nonzero"
                                  Figures="M41.977,17.434L41.977,18.165 48.719,18.165 48.719,17.434 41.977,17.434z M41.977,15.165L41.977,15.891 48.719,15.891 48.719,15.165 41.977,15.165z" />
                </Path.Data>
            </Path>
        </Canvas>
    </Canvas>
</Canvas>
</code>```

and my goal is doing something like this:

```<code><html>
  <body>
    <span>
      <Canvas Name="myxaml" Width="618.125" Height...............</canvas>
    </span>
  </body>
</html>
</code>```

And if it isn't possible, is it possible to convert xaml to html, I found a tool called html2xaml it converts from html to xaml and visversa but it results in no output for such xaml file.

答:
You could try saving the xaml as a file, and opening them in a vector based illustration editor such as InkScape, and then export to a more html friendly format (such as SVG, which could be displayed inside the canvas).

Link :
Inkscape supports XAML

ContentLicense: CC BY-SA 3.0

Title: inline xaml in html document

Body:
How could I view XAML code inside html document, this is my XAML code:

<Canvas Name="myxaml"
        Width="618.125"
        Height="37.325001"
        ClipToBounds="True"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Canvas Name="g10"
            RenderTransform="1.25,0,0,-1.25,0,37.325001">
        <Canvas Name="g12">
            <Path Fill="#FF000000"
                  Name="path16">
                <Path.Data>
                    <PathGeometry FillRule="Nonzero"
                                  Figures="M41.977,17.434L41.977,18.165 48.719,18.165 48.719,17.434 41.977,17.434z M41.977,15.165L41.977,15.891 48.719,15.891 48.719,15.165 41.977,15.165z" />
                </Path.Data>
            </Path>
        </Canvas>
    </Canvas>
</Canvas>

and my goal is doing something like this:

      <Canvas Name="myxaml" Width="618.125" Height...............</canvas>

And if it isn't possible, is it possible to convert xaml to html, I found a tool called html2xaml it converts from html to xaml and visversa but it results in no output for such xaml file.


问:
How to wrap every third table cell with a row within Kentico for email template?
How can I wrap every 3rd  with a
 using Kentico email template?

I wrote the following code in jQuery, but do not have knowledge or idea how to write this loop logic in Kentico.

var td = $("#myTable tr td");           // Getting all td
td.each(function(i) {                   // Looping the td
  if (i % 3 == 0) {                     // Splitting td as multiple of 3
    td.slice(i, i + 3).wrapAll('
') // Wrapping it inside tr
  }
}).parent('tr').unwrap();
```

I want the same logic using Kentico.

答:
Are you trying to replace the JS with Kentico Macro which can be used in email template or email widget?

If so, and you have Kentico 11+, then you can go to Email marketing application > Email widgets and open the "Latest Article" sample widget and look at how the logic works.

Here is the HTML/macro for the sample widget

```<code>{% /*
The Latest articles email widget dynamically obtains four latest articles from the Dancing Goat demo site at the time when the email issue is generated.
It achieves so by using macros that access pages with the given attributes.
*/ @%}

{%
  articles = Documents["/Articles"]
               .CultureVersions["en-US"]
               .Children
                 .ClassNames("dancinggoat.article")
                 .OrderBy("DocumentPublishFrom DESC")
                 .TopN(4)
                 .WithAllData;
return;
#%}

<!--[if (gte mso 9)|(IE)]>
<table align="center" border="0" cellspacing="0" cellpadding="0" width="500">
<tr>
<td align="center" valign="top" width="500">
<![endif]-->
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width:500px;">

{%
  i = 0;
  isFirstItemInRow = false;
  foreach (article in articles) {
%}

{%
    isFirstItemInRow = (Modulo(i, 2) == 0);
    articleUrl = UTMContent == String.Empty ? article.RelativeURL : article.RelativeURL + "?utm_content=" + UTMContent;
    articleTeaserUrl = GetAttachmentUrlByGUID(article.ArticleTeaser, "teaser", "teaser");
    articleLinkText = LinkText == String.Empty ? "Continue reading" : LinkText;
    return;
%}

{%  if (isFirstItemInRow)  { %}
  <tr>
    <td align="center" valign="top" style="font-size:0; padding: 10px 0 15px 0" class="padding">
<!--[if (gte mso 9)|(IE)]>
<table align="center" border="0" cellspacing="0" cellpadding="0" width="500">
<tr>
<![endif]-->
{% } /* END if */ #%}

<!--[if (gte mso 9)|(IE)]>
<td align="left" valign="top" width="240">
<![endif]-->
      <div style="display:inline-block; margin: 0 -2px; max-width:50%; min-width:240px; vertical-align:top; width:100%;" class="wrapper">
        <table align="left" border="0" cellpadding="0" cellspacing="0" width="100%" style="{% isFirstItemInRow ? "max-width:240px;" : "max-width:240px; float:right;" %}" class="wrapper">
          <tr>
            <td align="center" valign="top">
              <table border="0" cellpadding="0" cellspacing="0" width="100%">
                <tr>
                  <td style="padding: 20px 0 30px 0;">
                    <table cellpadding="0" cellspacing="0" border="0" width="100%">
                      <tr>
                        <td align="center" valign="middle"><a href="{% articleUrl #%}" target="_blank"><img src="{% articleTeaserUrl #%}" width="240" height="130" style="display: block; color: #666666; font-family: Helvetica, arial, sans-serif; font-size: 13px; width: 240px; height: 130px;" alt="Fluid images" border="0" class="img-max"></a></td>
                      </tr>
                      <tr>
                        <td align="center" style="padding: 15px 0 0 0; font-family: Arial, sans-serif; color: #333333; font-size: 20px;">{% article.ArticleTitle #%}</td>
                      </tr>
                      <tr>
                        <td align="center" style="padding: 5px 0 0 0; font-family: Arial, sans-serif; color: #666666; font-size: 14px; line-height: 20px;">{% article.ArticleSummary #%}</td>
                      </tr>
                      <tr>
                        <td align="center" style="padding: 5px 0 0 0; font-family: Arial, sans-serif; color: #666666; font-size: 14px; line-height: 20px;"><a href="{% articleUrl #%}" target="_blank" style="color: #256F9C; text-decoration: none;">{% articleLinkText #%} →</a></td>
                      </tr>
                    </table>
                  </td>
                </tr>
              </table>

            </td>
          </tr>
        </table>
      </div>
<!--[if (gte mso 9)|(IE)]>
</td>
<![endif]-->

{%  if (isFirstItemInRow)  { %}
<!--[if (gte mso 9)|(IE)]>
<td width="20" style="font-size: 1px;"> </td>
<![endif]-->
{% } /* END if */ #%}

{%  if (!isFirstItemInRow)  { %}
<!--[if (gte mso 9)|(IE)]>
</tr>
</table>
<![endif]-->
</td>
</tr>
{% } /* END if */ #%}

{% i++; return; %}
{% } /* END foreach */ #%}

</table>
</code>```

Body:
How can I wrap every 3rd  with a
 using Kentico email template?

I wrote the following code in jQuery, but do not have knowledge or idea how to write this loop logic in Kentico.

var td = $("#myTable tr td");           // Getting all td
td.each(function(i) {                   // Looping the td
  if (i % 3 == 0) {                     // Splitting td as multiple of 3
    td.slice(i, i + 3).wrapAll('
') // Wrapping it inside tr
  }
}).parent('tr').unwrap();

I want the same logic using Kentico.

Body:
Are you trying to replace the JS with Kentico Macro which can be used in email template or email widget?

If so, and you have Kentico 11+, then you can go to Email marketing application > Email widgets and open the "Latest Article" sample widget and look at how the logic works.

Here is the HTML/macro for the sample widget

{% /*
The Latest articles email widget dynamically obtains four latest articles from the Dancing Goat demo site at the time when the email issue is generated.
It achieves so by using macros that access pages with the given attributes.
*/ @%}

{%
  articles = Documents["/Articles"]
               .CultureVersions["en-US"]
               .Children
                 .ClassNames("dancinggoat.article")
                 .OrderBy("DocumentPublishFrom DESC")
                 .TopN(4)
                 .WithAllData;
return;
#%}

<!--[if (gte mso 9)|(IE)]>
<table align="center" border="0" cellspacing="0" cellpadding="0" width="500">
<tr>
<td align="center" valign="top" width="500">
<![endif]-->
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width:500px;">

{%
  i = 0;
  isFirstItemInRow = false;
  foreach (article in articles) {
%}

{%
    isFirstItemInRow = (Modulo(i, 2) == 0);
    articleUrl = UTMContent == String.Empty ? article.RelativeURL : article.RelativeURL + "?utm_content=" + UTMContent;
    articleTeaserUrl = GetAttachmentUrlByGUID(article.ArticleTeaser, "teaser", "teaser");
    articleLinkText = LinkText == String.Empty ? "Continue reading" : LinkText;
    return;
%}

{%  if (isFirstItemInRow)  { %}
  <tr>
    <td align="center" valign="top" style="font-size:0; padding: 10px 0 15px 0" class="padding">
<!--[if (gte mso 9)|(IE)]>
<table align="center" border="0" cellspacing="0" cellpadding="0" width="500">
<tr>
<![endif]-->
{% } /* END if */ #%}

<!--[if (gte mso 9)|(IE)]>
<td align="left" valign="top" width="240">
<![endif]-->
      <div style="display:inline-block; margin: 0 -2px; max-width:50%; min-width:240px; vertical-align:top; width:100%;" class="wrapper">
        <table align="left" border="0" cellpadding="0" cellspacing="0" width="100%" style="{% isFirstItemInRow ? "max-width:240px;" : "max-width:240px; float:right;" %}" class="wrapper">
          <tr>
            <td align="center" valign="top">
              <table border="0" cellpadding="0" cellspacing="0" width="100%">
                <tr>
                  <td style="padding: 20px 0 30px 0;">
                    <table cellpadding="0" cellspacing="0" border="0" width="100%">
                      <tr>
                        <td align="center" valign="middle"><a href="{% articleUrl #%}" target="_blank"><img src="{% articleTeaserUrl #%}" width="240" height="130" style="display: block; color: #666666; font-family: Helvetica, arial, sans-serif; font-size: 13px; width: 240px; height: 130px;" alt="Fluid images" border="0" class="img-max"></a></td>
                      </tr>
                      <tr>
                        <td align="center" style="padding: 15px 0 0 0; font-family: Arial, sans-serif; color: #333333; font-size: 20px;">{% article.ArticleTitle #%}</td>
                      </tr>
                      <tr>
                        <td align="center" style="padding: 5px 0 0 0; font-family: Arial, sans-serif; color: #666666; font-size: 14px; line-height: 20px;">{% article.ArticleSummary #%}</td>
                      </tr>
                      <tr>
                        <td align="center" style="padding: 5px 0 0 0; font-family: Arial, sans-serif; color: #666666; font-size: 14px; line-height: 20px;"><a href="{% articleUrl #%}" target="_blank" style="color: #256F9C; text-decoration: none;">{% articleLinkText #%} &rarr;</a></td>
                      </tr>
                    </table>
                  </td>
                </tr>
              </table>

            </td>
          </tr>
        </table>
      </div>
<!--[if (gte mso 9)|(IE)]>
</td>
<![endif]-->

{%  if (isFirstItemInRow)  { %}
<!--[if (gte mso 9)|(IE)]>
<td width="20" style="font-size: 1px;">&nbsp;</td>
<![endif]-->
{% } /* END if */ #%}

{%  if (!isFirstItemInRow)  { %}
<!--[if (gte mso 9)|(IE)]>
</tr>
</table>
<![endif]-->
</td>
</tr>
{% } /* END if */ #%}

{% i++; return; %}
{% } /* END foreach */ #%}

</table>


问:
How to use a FractionallySizedBox inside a Column?
I am trying to use a FractionallySizedBox inside a Column to make my app responsive, but I get

Needs Layout Error.

How can I use a FractionallySizedBox inside a Column?

答: You could use LayoutBuilder instead.

Body: You could use LayoutBuilder instead.


问:
How can I update the voice channel when a user enters the guild with JDA
I basically wanted to convert this code to JDA

JavaScript

bot.channels.get(serverStats.totalUserID).setName(`Total Users: ${member.guild.memberCount}`);

```

<p>Java (Error)</p>

<pre class="lang-java prettyprint-override"><code>public void onGuildJoin(GuildJoinEvent event) {
     event.getGuild().getTextChannelById(573629024102776853L).setName("Total Users:" + event.getGuild().getMembers().size()); //<---- Error
}
</code>```

答:
To rename a TextChannel you have to use the manager.
For example this:

```<code>  event.getGuild().getTextChannelById(573629024102776853L).getManager().setName("Total Users:" + event.getGuild().getMembers().size());
</code>```

Check out Channel#getManager() for more information.

Body:
I basically wanted to convert this code to JDA

JavaScript

bot.channels.get(serverStats.totalUserID).setName(`Total Users: ${member.guild.memberCount}`);

Java (Error)

public void onGuildJoin(GuildJoinEvent event) {
     event.getGuild().getTextChannelById(573629024102776853L).setName("Total Users:" + event.getGuild().getMembers().size()); //<---- Error
}

Body:
To rename a TextChannel you have to use the manager.
For example this:

  event.getGuild().getTextChannelById(573629024102776853L).getManager().setName("Total Users:" + event.getGuild().getMembers().size());

Check out Channel#getManager() for more information.


问:
How to apply styles in WPF without overriding packages?
I have the package Material Design Themes installed which changes the appearance of buttons. I would like to use styles with my buttons but when a style is used the button reverts to the default appearance with the style applied. Example

How would I apply a style without overriding the package?

MainWindow

```<code>  <Window.Resources>
        <Style TargetType="Button" x:Key="redFont">
            <Setter Property="Foreground" Value="red"/>
        </Style>
    </Window.Resources>

    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
        <Button Content="Without style"/>
        <Button Style="{StaticResource redFont}" Content="With style"/>
    </StackPanel>
</code>```

App.xaml

```<code><Application x:Class="WPF_TestMaterialSetterProperties.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">

    <Application.Resources>
        <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
    </Application.Resources>
</Application>
</code>```

答:
The style is overriding your derived style.  You need to make your style "BasedOn" the generic type style to inherit the style you've imported.

```<code><Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}" x:Key="redFont">
   ...
</code>```

That package is overriding the default theme that your app is using.  Your new style is "based-on" that override.

Body:
I have the package Material Design Themes installed which changes the appearance of buttons. I would like to use styles with my buttons but when a style is used the button reverts to the default appearance with the style applied. Example

How would I apply a style without overriding the package?

MainWindow

  <Window.Resources>

    </Window.Resources>

    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
        <Button Content="Without style"/>
        <Button Style="{StaticResource redFont}" Content="With style"/>
    </StackPanel>

App.xaml

<Application x:Class="WPF_TestMaterialSetterProperties.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">

    <Application.Resources>
        <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
    </Application.Resources>
</Application>

Body:
The style is overriding your derived style.  You need to make your style "BasedOn" the generic type style to inherit the style you've imported.

<Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}" x:Key="redFont">
   ...

That package is overriding the default theme that your app is using.  Your new style is "based-on" that override.


问:
Is that we cannot set some styles attributes that we can set in XML?
```<code><GridView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="90px"
    android:gravity="center"
    android:numColumns="5"
    android:verticalSpacing="30dp"
    android:stretchMode="columnWidth"
/>
</code>```

For Example, the XML above defined a GridView's style,

and now I want to make a number of GridView instances using this Style.
So I have to generate those in code.(Is there another way?)

I can only know:

```<code>mGridView = new GridView(this);
mGridView.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
</code>```

and then how to set the other attributes in code?

And if this question has an answer, the problem above will be solved:

Can we get a lot of instances defined by the same XML?

thought can include styles in XML, I need 100 instances I have to include in 100 <GridView ... />?

答: You can create the GridView in one layout, and reuse this layout in other views wherever you need it using the include tag. Check out Layout Tricks: Creating Reusable UI Components for more info.

Body:
<GridView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="90px"
    android:gravity="center"
    android:numColumns="5"
    android:verticalSpacing="30dp"
    android:stretchMode="columnWidth"
/>

For Example, the XML above defined a GridView's style,

and now I want to make a number of GridView instances using this Style.
So I have to generate those in code.(Is there another way?)

I can only know:

mGridView = new GridView(this);
mGridView.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

and then how to set the other attributes in code?

And if this question has an answer, the problem above will be solved:

Can we get a lot of instances defined by the same XML?

thought can include styles in XML, I need 100 instances I have to include in 100 <GridView ... />?


问:
Copying a column in excel and doubling every entry/cell. How to?
Let's say we have a row of elements, 1 per cell: 1,2,3,4.
I want to copy this row(or column) and double every entry: 1,1,2,2,3,3,4,4.

Is there any formula, function, etc that does this? Thanks a lot.

I have about 20k entries so doing it manually is not an option.

答:
Easy alternative using the advanced possibilities of Application.Index()

This approach demonstrates the advanced restructuring possibilities of the ►Application.Index() function whose row and column arguments are fed by arrays instead of single numeric indices.

Main procedure RedoubleCols

This procedure executes two steps:

it assigns data to a 1-based 2-dim array v by one code line,

it restructures the complete array via Application.Index where the row and column arguments are arrays returned by helper functions AllRows() and RDC(); the resulting array is written back to a given target.

```<code>Sub RedoubleCols(rng As Range, rng2 As Range)
' Purpose: get column values and write them back in pairs
' Param.:  1-rng: source range, 2-rng2: target range
' Method:  uses the advanced features of the Application.Index function
  Dim v                 ' declare variant (array)
' [1] get data
  v = rng.Value2
' [2] rearrange data by redoubling columns (RDC) and write them to a given target range
  rng2.Value2 = Application.Index(v, AllRows(UBound(v)), RDC(UBound(v, 2)))
End Sub
</code>```

Helper functions used by main procedure above

```<code>Function AllRows(ByVal n&) As Variant
' Purpose: create transposed Array(1,2,...n)
Dim i&: ReDim tmp(n - 1)
For i = 0 To n - 1
    tmp(i) = i + 1
Next i
AllRows = Application.Transpose(tmp)
End Function

Function RDC(ByVal n&) As Variant()
' Purpose: create Array(1,1,2,2,...n,n) containing pairs of each column number
Dim i&: ReDim tmp(2 * n - 1)                  ' declare counter and zero based counter array
For i = 0 To n - 1                            ' redouble column counters
    tmp(i * 2) = i + 1
    tmp(i * 2 + 1) = i + 1
Next i
RDC = tmp                                     ' return counter array
End Function
</code>```

Example Call

The essential code line in section [3] simply calls the main procedure RedoubleCols:

```<code>RedoubleCols src, target
</code>```

where source range and target range can be defined following your needs - c.f. sections [1] and [2].

```<code>Sub ExampleCall()
' [1] Identify source range
  Dim src As Range
  Set src = ThisWorkbook.Worksheets("MySheet").Range("A1:D2")
' [2] define any target, e.g. 1 column to the right of source data
  Dim target As Range, r&, c&
  r = src.Rows.Count: c = src.Columns.Count
  Set target = src.Offset(0, c + 1).Resize(r, c * 2)    ' reserve double space for columns
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' [3] write redoubled source range columns back to target
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  RedoubleCols src, target
End Sub
</code>```

Recommended link

Treating Some peculiarities of the the Application.Index function

Body:
Easy alternative using the advanced possibilities of Application.Index()

This approach demonstrates the advanced restructuring possibilities of the ►Application.Index() function whose row and column arguments are fed by arrays instead of single numeric indices.

Main procedure RedoubleCols

This procedure executes two steps:

it assigns data to a 1-based 2-dim array v by one code line,

it restructures the complete array via Application.Index where the row and column arguments are arrays returned by helper functions AllRows() and RDC(); the resulting array is written back to a given target.

Sub RedoubleCols(rng As Range, rng2 As Range)
' Purpose: get column values and write them back in pairs
' Param.:  1-rng: source range, 2-rng2: target range
' Method:  uses the advanced features of the Application.Index function
  Dim v                 ' declare variant (array)
' [1] get data
  v = rng.Value2
' [2] rearrange data by redoubling columns (RDC) and write them to a given target range
  rng2.Value2 = Application.Index(v, AllRows(UBound(v)), RDC(UBound(v, 2)))
End Sub

Helper functions used by main procedure above

Function AllRows(ByVal n&) As Variant
' Purpose: create transposed Array(1,2,...n)
Dim i&: ReDim tmp(n - 1)
For i = 0 To n - 1
    tmp(i) = i + 1
Next i
AllRows = Application.Transpose(tmp)
End Function

Function RDC(ByVal n&) As Variant()
' Purpose: create Array(1,1,2,2,...n,n) containing pairs of each column number
Dim i&: ReDim tmp(2 * n - 1)                  ' declare counter and zero based counter array
For i = 0 To n - 1                            ' redouble column counters
    tmp(i * 2) = i + 1
    tmp(i * 2 + 1) = i + 1
Next i
RDC = tmp                                     ' return counter array
End Function

Example Call

The essential code line in section [3] simply calls the main procedure RedoubleCols:

RedoubleCols src, target

where source range and target range can be defined following your needs - c.f. sections [1] and [2].

Sub ExampleCall()
' [1] Identify source range
  Dim src As Range
  Set src = ThisWorkbook.Worksheets("MySheet").Range("A1:D2")
' [2] define any target, e.g. 1 column to the right of source data
  Dim target As Range, r&, c&
  r = src.Rows.Count: c = src.Columns.Count
  Set target = src.Offset(0, c + 1).Resize(r, c * 2)    ' reserve double space for columns
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' [3] write redoubled source range columns back to target
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  RedoubleCols src, target
End Sub

Recommended link

Treating Some peculiarities of the the Application.Index function


问:
Save value of then in a variable outside of the Promise
I'm fairly new to the concept of Promises and I'm trying to understand how the scopes work. I'm basically trying to store the value from inside a then() into a variable outside of the Promise

Below is a simple function I've written in Nodejs (Express), using Sequelize to run the query on the DB.

```<code>exports.getTest = (req, res, next) => {
    var categories = [];
    var names = ['Category 1', 'Category 2', 'Category 3', 'Category 4'];
    for (var i = 0; i < names.length; i++) {
        model.Category.findOne({
            where: {
                name: names[i]
            },
            attributes: ['id']
        }).then(id => {
            categories.push(
            {
                category_id: id.id
            });
        });
    }
    res.json(categories);
}
</code>```

I have other logic to be run after that, and I have a for loop around the Promise. So, I can't run my next logic inside the then, otherwise I'll have it running multiple times because of the for loop. I need to populate the array categories to use it in my next operation.

Currently, my response (res.json(categories)) is []

Any help would be appreciated.

PS: I know this is a common topic, but as I mentioned, I'm fairly new to this and the other answers didn't fit my scenario and were further confusing me.

Thanks in advance!

答:
You can try Promise.all()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

The Promise.all() method returns a single Promise that resolves when all of the promises passed as an iterable have resolved or when the iterable contains no promises. It rejects with the reason of the first promise that rejects.

var getTest = (req, res, next) => {
    var categories = [];
    var promises = [];
    var names = ['Category 1', 'Category 2', 'Category 3', 'Category 4'];
    var resolveCount = 0;
    for (var i = 0; i < names.length; i++) {
        // Store the name in variable so that can be persistent and not
        // affected by the changing 'i' value
        const name = names[i]
        promises.push(new Promise((resolve, reject) => {

          // Your DB calls here. We shall use a simple timer to mimic the
          // effect
          setTimeout(() => {
            categories.push(name)
            resolveCount++;
            resolve();
          }, 1000)
        }));
    }

    Promise.all(promises).then(function() {
      console.log("This should run ONCE before AFTER promise resolved")
      console.log("resolveCount: " + resolveCount)
      console.log(categories);

      // Do your logic with the updated array
      // res.json(categories);
    });

    console.log("This will run immediately, before any promise resolve")
    console.log("resolveCount: " + resolveCount)
    console.log(categories)
}

getTest();```

Body:
I'm fairly new to the concept of Promises and I'm trying to understand how the scopes work. I'm basically trying to store the value from inside a then() into a variable outside of the Promise

Below is a simple function I've written in Nodejs (Express), using Sequelize to run the query on the DB.

exports.getTest = (req, res, next) => {
    var categories = [];
    var names = ['Category 1', 'Category 2', 'Category 3', 'Category 4'];
    for (var i = 0; i < names.length; i++) {
        model.Category.findOne({
            where: {
                name: names[i]
            },
            attributes: ['id']
        }).then(id => {
            categories.push(
            {
                category_id: id.id
            });
        });
    }
    res.json(categories);
}

I have other logic to be run after that, and I have a for loop around the Promise. So, I can't run my next logic inside the then, otherwise I'll have it running multiple times because of the for loop. I need to populate the array categories to use it in my next operation.

Currently, my response (res.json(categories)) is []

Any help would be appreciated.

PS: I know this is a common topic, but as I mentioned, I'm fairly new to this and the other answers didn't fit my scenario and were further confusing me.

Thanks in advance!


问:
expected conv2d_1_input to have shape (28, 28, 1) but got array with shape (1, 28, 28)
So i'm using the mnist example on keras and I am trying to predict a digit of my own. I'm really struggling with how I can match the dimension sizes as I cant seem to find a way to resize my image to have the rows and columns after the image no. I've tried resizing with via numpy however I just get error after error...

The code

```<code>from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
import numpy as np
import cv2

batch_size = 20
num_classes = 10
epochs = 1
img_rows, img_cols = 28, 28

(x_train, y_train), (x_test, y_test) = mnist.load_data()

print("Processing image")
im = cv2.imread('C:/Users/Luke/pic4.png', 0) #loading the image
print(im.shape) #28*28
im = cv2.resize(im,  (img_rows, img_cols))

list = [im]

batch = np.array([list for i in range(1)])
print(batch.shape)#1*28*28
batch = batch.astype('float32')
batch /= 255

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

#print("x_train shape")

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255

y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

def base_model():
    model = Sequential()
    model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
    model.add(Conv2D(64, (3, 3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(num_classes, activation='softmax'))

    model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])
return model

cnn_m = base_model()
cnn_m.summary()

print("Predicting image")
cnn_m.predict(batch)
print("Predicted image")
</code>```

Error

```<code>$ python mnist_cnn_test.py
Using TensorFlow backend.

x_train shape: (60000, 28, 28, 1)
60000 train samples
10000 test samples
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_1 (Conv2D)            (None, 26, 26, 32)        320
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 24, 24, 64)        18496
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 12, 12, 64)        0
_________________________________________________________________
dropout_1 (Dropout)          (None, 12, 12, 64)        0
_________________________________________________________________
flatten_1 (Flatten)          (None, 9216)              0
_________________________________________________________________
dense_1 (Dense)              (None, 128)               1179776
_________________________________________________________________
dropout_2 (Dropout)          (None, 128)               0
_________________________________________________________________
dense_2 (Dense)              (None, 10)                1290
=================================================================
Total params: 1,199,882
Trainable params: 1,199,882
Non-trainable params: 0
_________________________________________________________________
Predicting image
Traceback (most recent call last):
  File "mnist_cnn_test.py", line 100, in <module>
    cnn_m.predict(batch)
  File "C:\Python35\lib\site-packages\keras\models.py", line 1027, in predict
steps=steps)
  File "C:\Python35\lib\site-packages\keras\engine\training.py", line 1782, in predict
    check_batch_axis=False)
  File "C:\Python35\lib\site-packages\keras\engine\training.py", line 120, in _standardize_input_data
str(data_shape))
ValueError: Error when checking : expected conv2d_1_input to have shape (28, 28, 1) but got array with shape (1, 28, 28)
</code>```

答:
You can simply add </p>

```<code>K.set_image_dim_ordering('th')
</code>```

Body:
So i'm using the mnist example on keras and I am trying to predict a digit of my own. I'm really struggling with how I can match the dimension sizes as I cant seem to find a way to resize my image to have the rows and columns after the image no. I've tried resizing with via numpy however I just get error after error...

The code

from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
import numpy as np
import cv2

batch_size = 20
num_classes = 10
epochs = 1
img_rows, img_cols = 28, 28

(x_train, y_train), (x_test, y_test) = mnist.load_data()

print("Processing image")
im = cv2.imread('C:/Users/Luke/pic4.png', 0) #loading the image
print(im.shape) #28*28
im = cv2.resize(im,  (img_rows, img_cols))

list = [im]

batch = np.array([list for i in range(1)])
print(batch.shape)#1*28*28
batch = batch.astype('float32')
batch /= 255

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

#print("x_train shape")

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255

y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

def base_model():
    model = Sequential()
    model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
    model.add(Conv2D(64, (3, 3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(num_classes, activation='softmax'))

    model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])
return model

cnn_m = base_model()
cnn_m.summary()

print("Predicting image")
cnn_m.predict(batch)
print("Predicted image")

Error

$ python mnist_cnn_test.py
Using TensorFlow backend.

x_train shape: (60000, 28, 28, 1)
60000 train samples
10000 test samples
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_1 (Conv2D)            (None, 26, 26, 32)        320
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 24, 24, 64)        18496
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 12, 12, 64)        0
_________________________________________________________________
dropout_1 (Dropout)          (None, 12, 12, 64)        0
_________________________________________________________________
flatten_1 (Flatten)          (None, 9216)              0
_________________________________________________________________
dense_1 (Dense)              (None, 128)               1179776
_________________________________________________________________
dropout_2 (Dropout)          (None, 128)               0
_________________________________________________________________
dense_2 (Dense)              (None, 10)                1290
=================================================================
Total params: 1,199,882
Trainable params: 1,199,882
Non-trainable params: 0
_________________________________________________________________
Predicting image
Traceback (most recent call last):
  File "mnist_cnn_test.py", line 100, in <module>
    cnn_m.predict(batch)
  File "C:\Python35\lib\site-packages\keras\models.py", line 1027, in predict
steps=steps)
  File "C:\Python35\lib\site-packages\keras\engine\training.py", line 1782, in predict
    check_batch_axis=False)
  File "C:\Python35\lib\site-packages\keras\engine\training.py", line 120, in _standardize_input_data
str(data_shape))
ValueError: Error when checking : expected conv2d_1_input to have shape (28, 28, 1) but got array with shape (1, 28, 28)

Body:
You can simply add

K.set_image_dim_ordering('th')


问:
ActiveMQ Artemis Anycast and Multicast prefix
I'm using ActiveMQ Artemis version 2.6.2 and using Apache Camel to route messages.

When I connect Camel with jms-component in AMQ, for some reason in ActiveMQ Artemis the new queue is created with jms.queue. as a prefix.

I know if I add the follow code on acceptor in broker.xml the problem is solved. But sadly I don't have access to do that.

anycastPrefix=jms.queue.;multicastPrefix=jms.topic.

Is there a way to solve this in Java Code? I tried these steps but no success.

```<code>from("amq:QUEUE.TEST").setProperty("anycastPrefix", simple("jms.queue."))
from("amq:jms:queue:QUEUE.TEST")
</code>```

答:
The reason that the queue is being created with the jms.queue. prefix is almost certainly because Camel is using an Artemis 1.x client instead of a 2.x client. The 1.x client is hard-coded to use the jms.queue. and jms.topic. prefixes.

As you note, the simplest way to solve this issue is by configuring the prefixes on the appropriate acceptor in broker.xml. I don't know of any way to solve this issue in Java code. I think your best bet would be just to upgrade the Artemis client implementation which Camel is using.

Body:
I'm using ActiveMQ Artemis version 2.6.2 and using Apache Camel to route messages.

When I connect Camel with jms-component in AMQ, for some reason in ActiveMQ Artemis the new queue is created with jms.queue. as a prefix.

I know if I add the follow code on acceptor in broker.xml the problem is solved. But sadly I don't have access to do that.

anycastPrefix=jms.queue.;multicastPrefix=jms.topic.

Is there a way to solve this in Java Code? I tried these steps but no success.

from("amq:QUEUE.TEST").setProperty("anycastPrefix", simple("jms.queue."))
from("amq:jms:queue:QUEUE.TEST")


问:
How to test a method in Junit5
I have to make a junit test a method in one of my classes, but I never did such a thing and all the info on the INternet is for simple calculation tests. I don't know how to implement a test for my method, to be honest, I tried a boolean check but it did not really help me, maybe someone here can give me a pointer.

I watched a few tutorials with Junit but did not help me out because they are simple methods. I tried a boolean check but I could not make it work

```<code>public void takeDamage(int damage) {

    if (!todelete) {
        damage = damage / damagereduction;
        currentLife -= damage;
    }
    if (currentLife <= 0) {
        todelete = true;
        return;
    }
    if (currentLife >= 100) {
        sprite.setTexture(skins[0]);
        currentLife = 100;
        return;
    }
    int life = currentLife / 20;
    sprite.setTexture(skins[life]);
}
</code>```

So this method is changing the picture of my character to a set picture depending on the health he has left. I don't know how I could test this method. Maybe someone can give me an pointer.

答:
a simple Test with the information you gave us would similar look like this.

You need to adjust the methods, classnames and actual values you expect.

@Test
public void testDamage() {
  MyPersonClass myPerson = new MyPersonClass();
  myPerson.takeDamage(50);
  int expectedRemainingLife = 80;
  Texture expectedPicture = new Texture(); // You need to load the correct picture here
  assertEquals(expectedRemainingLife, myPerson.getLife());
  assertEquals(expectedPicture, myPerson.getPicture());
}
```

If the Texture is stored somewhere else, you need to get the holding object too, to verify the texture.

Title: How to test a method in Junit5

Body:
I have to make a junit test a method in one of my classes, but I never did such a thing and all the info on the INternet is for simple calculation tests. I don't know how to implement a test for my method, to be honest, I tried a boolean check but it did not really help me, maybe someone here can give me a pointer.

I watched a few tutorials with Junit but did not help me out because they are simple methods. I tried a boolean check but I could not make it work

public void takeDamage(int damage) {

    if (!todelete) {
        damage = damage / damagereduction;
        currentLife -= damage;
    }
    if (currentLife <= 0) {
        todelete = true;
        return;
    }
    if (currentLife >= 100) {
        sprite.setTexture(skins[0]);
        currentLife = 100;
        return;
    }
    int life = currentLife / 20;
    sprite.setTexture(skins[life]);
}

So this method is changing the picture of my character to a set picture depending on the health he has left. I don't know how I could test this method. Maybe someone can give me an pointer.

Body:
a simple Test with the information you gave us would similar look like this.

You need to adjust the methods, classnames and actual values you expect.

@Test
public void testDamage() {
  MyPersonClass myPerson = new MyPersonClass();
  myPerson.takeDamage(50);
  int expectedRemainingLife = 80;
  Texture expectedPicture = new Texture(); // You need to load the correct picture here
  assertEquals(expectedRemainingLife, myPerson.getLife());
  assertEquals(expectedPicture, myPerson.getPicture());
}

If the Texture is stored somewhere else, you need to get the holding object too, to verify the texture.


问:
C# laziness question
What's the common approach to design applications, which strongly rely on lazy evaluation in C# (LINQ, IEnumerable, IQueryable, ...)?

Right now I usually attempt to make every query as lazy as possible, using yield return and LINQ queries, but in runtime this could usually lead to "too lazy" behavior, when every query gets builts from it's beginning obviously resulting in severe visual performance degradation.

What I usually do means putting ToList() projection operators somewhere to cache the data, but I suspect this approach might be incorrect.

What's the appropriate / common ways to design this sort of applications from the very beginning?

答:
I you need a certain sequence of data to be cached, call one of the aggregation operators (ToList, ToArray, etc.) on that sequence. Otherwise just use lazy evaluation.

Build your code around your data. What data is volatile and needs to be pulled fresh each time? Use lazy evaluation and don't cache. What data is relatively static and only needs to be pulled once? Cache that data in memory so you don't pull it unnecessarily.

Title: C# laziness question


问:
How to display special characters in QT 5?
Excerpt from my code:

```<code>  char msg[80];
  sprintf(msg, "Chuck Temperature: %.1f °C", temperature);
  ui.TemperatureLabel->setText(QString::fromUtf8(msg));
</code>```

What I get:

What does not work:

Replacing the degree symbol (°) by ° while setting textFormat to RichText. It is displayed as "Chuck Temperature: °C".

Adding QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); did not help at all.

I work under Visual C++, if that is important.

答:
What about using a QString instead ? It handles for you the special characters.

If I understand your code, you want to update the text of a QLabel.

You could do something as follows:

```<code>QString msg("Chuck Temperature: " + QString::number(temperature) + " °C");
ui.TemperatureLabel->setText(msg);
</code>```

Note that you can specify the desired precision in QString::number(). Here you can see how to do it.
If you want to format the temperature the same way as %.1f does, just write the following:

```<code>QString msg("Chuck Temperature: " + QString::number(temperature, 'g', 2) + " °C");
ui.TemperatureLabel->setText(msg);
</code>```

I hope it will solve your problem.

Body:
Excerpt from my code:

  char msg[80];
  sprintf(msg, "Chuck Temperature: %.1f °C", temperature);
  ui.TemperatureLabel->setText(QString::fromUtf8(msg));

What I get:

What does not work:

Replacing the degree symbol (°) by ° while setting textFormat to RichText. It is displayed as "Chuck Temperature: °C".

Adding QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); did not help at all.

I work under Visual C++, if that is important.

Body:
What about using a QString instead ? It handles for you the special characters.

If I understand your code, you want to update the text of a QLabel.

You could do something as follows:

QString msg("Chuck Temperature: " + QString::number(temperature) + " °C");
ui.TemperatureLabel->setText(msg);

Note that you can specify the desired precision in QString::number(). Here you can see how to do it.
If you want to format the temperature the same way as %.1f does, just write the following:

QString msg("Chuck Temperature: " + QString::number(temperature, 'g', 2) + " °C");
ui.TemperatureLabel->setText(msg);

I hope it will solve your problem.


问:
How do I get a named range to appear on another sheet?
I am trying to duplicate a named range on a different worksheet but I am having problems making it work.

On Sheet1, A3:A92 (90 cells) is a named range, "Employees"

On Sheet2, I want to duplicate the named range, "Employees" such that when values in the named range change on Sheet1 it is updated on Sheet2.

On Sheet2, I also want new entries that expand the range beyond the current 90 cells to appear on Sheet2

On Sheet2, I have tried: ='Employees'!A1" and then dragged the formula down until it fill 90 cells.

I also tried entering =Employees in A1 and hit enter but I get #VALUE!

If I use and array formula {=Employees} on A2 I get the correct entry for the first row of the named range but when I drag it down, it just repeats the first entry in the named range.

Is there are solution to this problem? What is the best approach?

答:
Based on the comments of you and SJR, On the second worksheet, select more cells than the 90 that currently exist to create a margin for growth and enter the array formula =Employees

If you want to make the #N/A errors to "disappear," use conditional formatting. This way, you have room for growth built in and it still appears "pretty."


问:
How to sign using a mouse in Iphone
I have to make an application where i need digital signature for authentication before a transaction completes.

Now i do not know how to implement the same. My requirements are:-

A screen where i can sign by swyping my fingers .

Now can anyone please tell me how to do make such a screen where i can sign using my fingers and it can be captured at the back.

答:
```<code>- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

    mouseSwiped = NO;
    UITouch *touch = [touches anyObject];

    if ([touch tapCount] == 2) {
        drawImage.image = nil;
        return;
    }

    if ((lastPoint.x<17 && lastPoint.y < 116) || (lastPoint.x>287 && lastPoint.y >159))
        NSLog(@"Outside");
    else
    {
        lastPoint = [touch locationInView:vw];
        //          lastPoint.y -= 20;
    }

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    mouseSwiped = YES;

    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:vw];

    if ((currentPoint.x<17 && currentPoint.y < 116) || (currentPoint.x>287 && currentPoint.y >159))
        NSLog(@"Outside");
    else
    {
        UIGraphicsBeginImageContext(vw.frame.size);
        [drawImage.image drawInRect:CGRectMake(0, 0, vw.frame.size.width, vw.frame.size.height)];
        CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
        CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
        CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);
        CGContextBeginPath(UIGraphicsGetCurrentContext());
        CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
        CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
        CGContextStrokePath(UIGraphicsGetCurrentContext());
        drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        lastPoint = currentPoint;

        mouseMoved++;

        if (mouseMoved == 10) {
            mouseMoved = 0;
        }
    }

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:vw];

    if ([touch tapCount] == 2) {
        drawImage.image = nil;
        return;
    }

    if ((currentPoint.x<20 && currentPoint.y < 199) || (currentPoint.x>743 && currentPoint.y >425))
        NSLog(@"Outside");
    else
    {
        if(!mouseSwiped)
        {
            UIGraphicsBeginImageContext(vw.frame.size);
            [drawImage.image drawInRect:CGRectMake(0, 0, vw.frame.size.width, vw.frame.size.height)];
            CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
            CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
            CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);
            CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
            CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
            CGContextStrokePath(UIGraphicsGetCurrentContext());
            CGContextFlush(UIGraphicsGetCurrentContext());
            drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
    }
}
</code>```

Title: How to sign using a mouse in Iphone


问:
Why does ckeditor plugin tab doesn't work?
Hy,

I need the tab function to work in Ckeditor and I put the "tab" plugin in the plugin folder and I told the editor but when I press tab on the keyboard the focus leaves the editor. What am I doing wrong? My script:

```<code>        <script>
            CKEDITOR.replace( 'editor', {
                width: 795, height: 642,
                enterMode: CKEDITOR.ENTER_DIV,
                shiftEnterMode: CKEDITOR.ENTER_BR
            }
            );
            CKEDITOR.editorConfig = function( config ) {
                config.toolbarGroups = [
                    { name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
                    { name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
                    { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },
                    { name: 'forms', groups: [ 'forms' ] },
                    '/',
                    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
                    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },
                    { name: 'links', groups: [ 'links' ] },
                    { name: 'insert', groups: [ 'insert' ] },
                    '/',
                    { name: 'styles', groups: [ 'styles' ] },
                    { name: 'colors', groups: [ 'colors' ] },
                    { name: 'tools', groups: [ 'tools' ] },
                    { name: 'others', groups: [ 'others' ] },
                    { name: 'about', groups: [ 'about' ] }
                ];

                config.removeButtons = 'Source,Save,Templates,NewPage,Preview,Print,Flash,HorizontalRule,Smiley,PageBreak,Iframe,ShowBlocks,Maximize,About,Link,Unlink,Anchor,Language,CreateDiv';
                config.extraPlugins = 'tab';    };

        </script>
</code>```

答: Thanks but it's only works to the first line. When I press Tab, the focus get out of the document. </p>


问:
I have JWT middleware set up in ASP.NET Core 2.2 Web API. It only works with RSA256 and NOT HS256
For the problem stated in the title, when I attempt an RSA256 Access Token, the JWT Decode decodes it and more importantly, "OnTokenValidated" gets called from the JwtBearer events. Here's the code shortened for brevity. Remember, this works fine with RSA, but NOT HS (some parts of the code were left out for brevity). Any help is a God-send as I've struggled with this for more than a few hours. Please let me know if you can help:

```<code>public void ConfigureServices(IServiceCollection services)
 {
            var tokenValidationParameters = new TokenValidationParameters
                    {
/* I understand that I need to (and I did unsuccessfully) change these for HS256) */
                        IssuerSigningKey = new RsaSecurityKey(RSA.Create(2048)),
                        ValidateIssuer = true,
                        ValidIssuer = appSettings.Auth0Issuer,
                        ValidateIssuerSigningKey = true,
                        ValidateLifetime = false,
                        RequireExpirationTime = true,
                        ValidAudience = appSettings.Auth0Audience,
                        ValidateAudience = true
                    };

            services.AddAuthentication(
                x =>
                {
                    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer(
                x =>
                {
                    x.Authority = appSettings.Auth0Tenant;
                    x.Events = new JwtBearerEvents
                    {
                        OnTokenValidated = context =>
                                           {
                                               string token = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", string.Empty);
                                               IDictionary<string, object> headers = AuthenticationHelper.JwtHeaders(token);

                                               // Validate the HS256 Key using a PSK
                                               if (headers.ContainsKey("alg") && headers["alg"].ToString() == "HS256")
                                               {
                                                   string secret = appSettings.Auth0MachineToMachineSecret;
                                                   string payload = AuthenticationHelper.JwtDecode(token, secret);
                                                   this.SetTokenInfo(JObject.Parse(payload), context, appSettings.Auth0AppMeta);
                                               }

                                               // Validate token with a public RSA key published by the IDP as a list of JSON Web Keys (JWK)
                                               // step 0: you've read the keys from the jwks_uri URL found in http://<IDP authority URL>/.well-known/openid-configuration endpoint
                                               if (!headers.ContainsKey("alg") || headers["alg"].ToString() != "RS256")
                                               {
                                                   context.Fail("No algorithm was present or validated");
                                                   return Task.CompletedTask;
                                               }

                                               List<IDPKey> idpKeys = AuthenticationHelper.GetIdpKeys(appSettings.Auth0Tenant);
                                               IDPKey iDpKey = AuthenticationHelper.FindIdpKey(headers, "kid", idpKeys);

                                               if (iDpKey == null)
                                               {
                                                   context.Fail($"Invalid authorization scheme: {context.Request}");
                                                   return Task.CompletedTask;
                                               }

                                               try
                                               {
                                                   //If everything is good set the Authorization as true and the CRM user.
                                                   JObject payload = AuthenticationHelper.ParsePayload(token);
                                                   this.SetTokenInfo(payload, context, appSettings.Auth1AppMeta);
                                               }
                                               catch (JoseException ex)
                                               {
                                                   context.Fail(ex);
                                               }

                                               context.Success();

                                               return Task.CompletedTask;
                                           },
                        OnAuthenticationFailed = context =>
                                                 {
                                                     return Task.FromException(context.Exception);
                                                 }
                    };
                    x.TokenValidationParameters = tokenValidationParameters;
                });
 }
</code>```

答: They had given me an expired token instead of a valid one. Now both HS256 and RSA256 fire the "OnTokenValidated" JwtBearer event. </p>

Body:
For the problem stated in the title, when I attempt an RSA256 Access Token, the JWT Decode decodes it and more importantly, "OnTokenValidated" gets called from the JwtBearer events. Here's the code shortened for brevity. Remember, this works fine with RSA, but NOT HS (some parts of the code were left out for brevity). Any help is a God-send as I've struggled with this for more than a few hours. Please let me know if you can help:

public void ConfigureServices(IServiceCollection services)
 {
            var tokenValidationParameters = new TokenValidationParameters
                    {
/* I understand that I need to (and I did unsuccessfully) change these for HS256) */
                        IssuerSigningKey = new RsaSecurityKey(RSA.Create(2048)),
                        ValidateIssuer = true,
                        ValidIssuer = appSettings.Auth0Issuer,
                        ValidateIssuerSigningKey = true,
                        ValidateLifetime = false,
                        RequireExpirationTime = true,
                        ValidAudience = appSettings.Auth0Audience,
                        ValidateAudience = true
                    };

            services.AddAuthentication(
                x =>
                {
                    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer(
                x =>
                {
                    x.Authority = appSettings.Auth0Tenant;
                    x.Events = new JwtBearerEvents
                    {
                        OnTokenValidated = context =>
                                           {
                                               string token = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", string.Empty);
                                               IDictionary<string, object> headers = AuthenticationHelper.JwtHeaders(token);

                                               // Validate the HS256 Key using a PSK
                                               if (headers.ContainsKey("alg") && headers["alg"].ToString() == "HS256")
                                               {
                                                   string secret = appSettings.Auth0MachineToMachineSecret;
                                                   string payload = AuthenticationHelper.JwtDecode(token, secret);
                                                   this.SetTokenInfo(JObject.Parse(payload), context, appSettings.Auth0AppMeta);
                                               }

                                               // Validate token with a public RSA key published by the IDP as a list of JSON Web Keys (JWK)
                                               // step 0: you've read the keys from the jwks_uri URL found in http://<IDP authority URL>/.well-known/openid-configuration endpoint
                                               if (!headers.ContainsKey("alg") || headers["alg"].ToString() != "RS256")
                                               {
                                                   context.Fail("No algorithm was present or validated");
                                                   return Task.CompletedTask;
                                               }

                                               List<IDPKey> idpKeys = AuthenticationHelper.GetIdpKeys(appSettings.Auth0Tenant);
                                               IDPKey iDpKey = AuthenticationHelper.FindIdpKey(headers, "kid", idpKeys);

                                               if (iDpKey == null)
                                               {
                                                   context.Fail($"Invalid authorization scheme: {context.Request}");
                                                   return Task.CompletedTask;
                                               }

                                               try
                                               {
                                                   //If everything is good set the Authorization as true and the CRM user.
                                                   JObject payload = AuthenticationHelper.ParsePayload(token);
                                                   this.SetTokenInfo(payload, context, appSettings.Auth1AppMeta);
                                               }
                                               catch (JoseException ex)
                                               {
                                                   context.Fail(ex);
                                               }

                                               context.Success();

                                               return Task.CompletedTask;
                                           },
                        OnAuthenticationFailed = context =>
                                                 {
                                                     return Task.FromException(context.Exception);
                                                 }
                    };
                    x.TokenValidationParameters = tokenValidationParameters;
                });
 }


问:
Cite various python packages in paper
We have a working tool built off of various packages in python. I am not sure how to cite these packages for a paper I am working on. How do I properly cite python packages? One of them have a way they ask us to cite them  via a book. Most say nothing on citations that I can find. Is there a standard?</p>

答:
For people coming across this in the future, the citepy library may solve some problems. It won't pick up the "preferred" citations for the vanishingly small proportion of libraries which have them, but it provides a convenient way of generating CSL-compatible citation metadata for either specific libraries, or everything in your virtual environment.

It dumps out CSL-data JSON, which can then be converted into basically anything by tools like citation-js.

Title: Cite various python packages in paper