问:
How to communicate with BLE
I have the following working code that is able to scan and connect to a BLE device:

```<code>import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity2 extends AppCompatActivity {

    private final static String TAG = MainActivity2.class.getSimpleName();

    BluetoothManager btManager;
    BluetoothAdapter btAdapter;
    BluetoothLeScanner btScanner;
    private final static int REQUEST_ENABLE_BT = 1;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;

    Boolean btScanning = false;
    int deviceIndex = 0;
    ArrayList<BluetoothDevice> devicesDiscovered = new ArrayList<BluetoothDevice>();
    BluetoothGatt bluetoothGatt;

    public final static String ACTION_GATT_CONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED =
            "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE =
            "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA =
            "com.example.bluetooth.le.EXTRA_DATA";

    public Map<String, String> uuids = new HashMap<String, String>();

    // Stops scanning after 5 seconds.
    private Handler mHandler = new Handler();
    private static final long SCAN_PERIOD = 5000;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

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

        btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        btAdapter = btManager.getAdapter();
        btScanner = btAdapter.getBluetoothLeScanner();

        if (btAdapter != null && !btAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }

        // Make sure we have access coarse location enabled, if not, prompt the user to enable it
        if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("This app needs location access");
            builder.setMessage("Please grant location access so this app can detect peripherals.");
            builder.setPositiveButton(android.R.string.ok, null);
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                }
            });
            builder.show();
        }

        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    // Device scan callback.
    private ScanCallback leScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            devicesDiscovered.add(result.getDevice());
            deviceIndex++;
        }
    };

    // Device connect call back
    private final BluetoothGattCallback btleGattCallback = new BluetoothGattCallback() {

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {

        }

        @Override
        public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {

        }

        @Override
        public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
            displayGattServices(bluetoothGatt.getServices());
        }

        @Override
        // Result of a characteristic read operation
        public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic characteristic,
                                         int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            // >> DUNNO WHAT TO DO HERE <<
        }
    };

    private void broadcastUpdate(final String action,
                                 final BluetoothGattCharacteristic characteristic) {

        System.out.println(characteristic.getUuid());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_COARSE_LOCATION: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    System.out.println("coarse location permission granted");
                } else {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Functionality limited");
                    builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                        }

                    });
                    builder.show();
                }
                return;
            }
        }
    }

    public void startScanning() {
        System.out.println("start scanning");
        btScanning = true;
        deviceIndex = 0;
        devicesDiscovered.clear();
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                btScanner.startScan(leScanCallback);
            }
        });

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                stopScanning();
            }
        }, SCAN_PERIOD);
    }

    public void stopScanning() {
        System.out.println("stopping scanning");
        btScanning = false;
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                btScanner.stopScan(leScanCallback);
            }
        });
    }

    public void connectToDeviceSelected() {
        int deviceSelected = Integer.parseInt("0" /* MY DEVICE INDEX TAKEN FROM AN EDITTEXT*/);
        bluetoothGatt = devicesDiscovered.get(deviceSelected).connectGatt(this, false, btleGattCallback);
    }

    public void disconnectDeviceSelected() {
        bluetoothGatt.disconnect();
    }

    private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null) return;

        // Loops through available GATT Services.
        for (BluetoothGattService gattService : gattServices) {
            new ArrayList<HashMap<String, String>>();
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();

            // Loops through available Characteristics.
            for (BluetoothGattCharacteristic gattCharacteristic :
                    gattCharacteristics) {
                // SHOWS AVAILABLES
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();

        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.example.joelwasserman.androidbleconnectexample/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.example.joelwasserman.androidbleconnectexample/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }
}
</code>```

Now, once connected, I want to send data (in byte[] format) to the BLE device... How can I reach that goal? Thanks in advance

Obs.: I'm targetting APIs >= 21

答:
Check out an example with writing a new value in characteristic:</p>

```<code>public static final byte NO_ALERT = 0x00; //your byte data
public final static UUID IMMEDIATE_ALERT_UUID =
        UUID.fromString("00001802-0000-1000-8000-00805f9b34fb"); //UUID of gatt service
public final static UUID IMMEDIATE_ALERT_LEVEL_UUID =
        UUID.fromString("00002a06-0000-1000-8000-00805f9b34fb"); //UUID of characteristic

@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {

   byte[] data;
   byte b = NO_ALERT;
   data = new byte[]{b};
   BluetoothGattService service = gatt.getService(IMMEDIATE_ALERT_UUID);
   if (service != null) {
       BluetoothGattCharacteristic characteristic = service.getCharacteristic(IMMEDIATE_ALERT_LEVEL_UUID);
       characteristic.setValue(data);
       gatt.writeCharacteristic(characteristic);
   }
}
</code>```

Title: How to communicate with BLE

Body:
I have the following working code that is able to scan and connect to a BLE device:

import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity2 extends AppCompatActivity {

    private final static String TAG = MainActivity2.class.getSimpleName();

    BluetoothManager btManager;
    BluetoothAdapter btAdapter;
    BluetoothLeScanner btScanner;
    private final static int REQUEST_ENABLE_BT = 1;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;

    Boolean btScanning = false;
    int deviceIndex = 0;
    ArrayList<BluetoothDevice> devicesDiscovered = new ArrayList<BluetoothDevice>();
    BluetoothGatt bluetoothGatt;

    public final static String ACTION_GATT_CONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED =
            "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE =
            "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA =
            "com.example.bluetooth.le.EXTRA_DATA";

    public Map<String, String> uuids = new HashMap<String, String>();

    // Stops scanning after 5 seconds.
    private Handler mHandler = new Handler();
    private static final long SCAN_PERIOD = 5000;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

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

        btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        btAdapter = btManager.getAdapter();
        btScanner = btAdapter.getBluetoothLeScanner();

        if (btAdapter != null && !btAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }

        // Make sure we have access coarse location enabled, if not, prompt the user to enable it
        if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("This app needs location access");
            builder.setMessage("Please grant location access so this app can detect peripherals.");
            builder.setPositiveButton(android.R.string.ok, null);
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                }
            });
            builder.show();
        }

        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    // Device scan callback.
    private ScanCallback leScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            devicesDiscovered.add(result.getDevice());
            deviceIndex++;
        }
    };

    // Device connect call back
    private final BluetoothGattCallback btleGattCallback = new BluetoothGattCallback() {

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {

        }

        @Override
        public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {

        }

        @Override
        public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
            displayGattServices(bluetoothGatt.getServices());
        }

        @Override
        // Result of a characteristic read operation
        public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic characteristic,
                                         int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            // >> DUNNO WHAT TO DO HERE <<
        }
    };

    private void broadcastUpdate(final String action,
                                 final BluetoothGattCharacteristic characteristic) {

        System.out.println(characteristic.getUuid());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_COARSE_LOCATION: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    System.out.println("coarse location permission granted");
                } else {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Functionality limited");
                    builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                        }

                    });
                    builder.show();
                }
                return;
            }
        }
    }

    public void startScanning() {
        System.out.println("start scanning");
        btScanning = true;
        deviceIndex = 0;
        devicesDiscovered.clear();
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                btScanner.startScan(leScanCallback);
            }
        });

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                stopScanning();
            }
        }, SCAN_PERIOD);
    }

    public void stopScanning() {
        System.out.println("stopping scanning");
        btScanning = false;
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                btScanner.stopScan(leScanCallback);
            }
        });
    }

    public void connectToDeviceSelected() {
        int deviceSelected = Integer.parseInt("0" /* MY DEVICE INDEX TAKEN FROM AN EDITTEXT*/);
        bluetoothGatt = devicesDiscovered.get(deviceSelected).connectGatt(this, false, btleGattCallback);
    }

    public void disconnectDeviceSelected() {
        bluetoothGatt.disconnect();
    }

    private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null) return;

        // Loops through available GATT Services.
        for (BluetoothGattService gattService : gattServices) {
            new ArrayList<HashMap<String, String>>();
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();

            // Loops through available Characteristics.
            for (BluetoothGattCharacteristic gattCharacteristic :
                    gattCharacteristics) {
                // SHOWS AVAILABLES
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();

        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.example.joelwasserman.androidbleconnectexample/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.example.joelwasserman.androidbleconnectexample/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }
}

Now, once connected, I want to send data (in byte[] format) to the BLE device... How can I reach that goal? Thanks in advance

Obs.: I'm targetting APIs >= 21

Body:
Check out an example with writing a new value in characteristic:

public static final byte NO_ALERT = 0x00; //your byte data
public final static UUID IMMEDIATE_ALERT_UUID =
        UUID.fromString("00001802-0000-1000-8000-00805f9b34fb"); //UUID of gatt service
public final static UUID IMMEDIATE_ALERT_LEVEL_UUID =
        UUID.fromString("00002a06-0000-1000-8000-00805f9b34fb"); //UUID of characteristic

@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {

   byte[] data;
   byte b = NO_ALERT;
   data = new byte[]{b};
   BluetoothGattService service = gatt.getService(IMMEDIATE_ALERT_UUID);
   if (service != null) {
       BluetoothGattCharacteristic characteristic = service.getCharacteristic(IMMEDIATE_ALERT_LEVEL_UUID);
       characteristic.setValue(data);
       gatt.writeCharacteristic(characteristic);
   }
}


来源: stackexchange

问:
Create a list of dictionaries from a list of keys and multiple lists of values
My solution

```<code>keys = ['FirstName', 'LastName', 'ID']

name1 = ['Michael', 'Jordan', '224567']
name2 = ['Kyle', 'Hynes', '294007']
name3 = ['Josef', 'Jones', '391107']

dictList = []
dictList.append(dict(zip(keys, name1)))
dictList.append(dict(zip(keys, name2)))
dictList.append(dict(zip(keys, name3)))
</code>```

Works fine, but is there any other solution, because I will have at least 20000 names, so I am looking how to improve this.

答:
pandas makes this too easy.

```<code>import pandas as pd

keys = ['FirstName', 'LastName', 'ID']
name1 = ['Michael', 'Jordan', '224567']
name2 = ['Kyle', 'Hynes', '294007']
name3 = ['Josef', 'Jones', '391107']

doc_list = [name1,name2,name3]
df = pd.DataFrame(doc_list,columns = keys)
</code>```

So you'll have a DataFrame like this:

```<code>   FirstName  LastName   ID
0   Michael   Jordan  224567
1      Kyle    Hynes  294007
2     Josef    Jones  391107
</code>```

If your names are already in a file,read_csv would be better.

```<code>pd.read_csv("file_name.csv",header=keys)//remove the header parameter if it is present in your csv.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My solution

keys = ['FirstName', 'LastName', 'ID']

name1 = ['Michael', 'Jordan', '224567']
name2 = ['Kyle', 'Hynes', '294007']
name3 = ['Josef', 'Jones', '391107']

dictList = []
dictList.append(dict(zip(keys, name1)))
dictList.append(dict(zip(keys, name2)))
dictList.append(dict(zip(keys, name3)))

Works fine, but is there any other solution, because I will have at least 20000 names, so I am looking how to improve this.

Body:
pandas makes this too easy.

import pandas as pd

keys = ['FirstName', 'LastName', 'ID']
name1 = ['Michael', 'Jordan', '224567']
name2 = ['Kyle', 'Hynes', '294007']
name3 = ['Josef', 'Jones', '391107']

doc_list = [name1,name2,name3]
df = pd.DataFrame(doc_list,columns = keys)

So you'll have a DataFrame like this:

   FirstName  LastName   ID
0   Michael   Jordan  224567
1      Kyle    Hynes  294007
2     Josef    Jones  391107

If your names are already in a file,read_csv would be better.

pd.read_csv("file_name.csv",header=keys)//remove the header parameter if it is present in your csv.

ContentLicense: CC BY-SA 3.0


问:
HTML "Range" Input Problems
I'm trying to write a slider program that will cover an entire square canvas with a blue square when range is set to maximum. There are two problems I'm having though:

When moving my slider, it produces a rectangle instead of a square.

The maximum value of my slider's square only covers less than half of the canvas.

I'm doing my project on Codepen, and my code for the slider is below. Here's a link to my pen if you need the full details: https://codepen.io/drummerlover33/pen/EXdobV.

```<code>function doSquare() {
  var slider = document.getElementById("colorSlider");
  var sliderValue = slider.value;
  var canvas = document.getElementById("mainCanvas");
  var canvasContext = canvas.getContext("2d");
  canvasContext.clearRect(0,0,canvas.width,canvas.height);
  canvasContext.fillStyle = "blue";
  canvasContext.fillRect(0,0,sliderValue,sliderValue);
}
</code>```

Hope you can help a newbie out!

Thanks!

答:
The canvas's width and height attributes are not only the size of the canvas, but also set its resolution. If you don't set width and height via the attributes (or via script), the canvas's default resolution is 300px X 150px.

Setting the dimensions via CSS only sets the outer size of the canvas element (the style). You have to set the width and the height attributes explicitly on the canvas element.

// Remnant function from previous case
function doRed() {
  var canvasElements = document.getElementById("mainCanvas");
  canvasElements.style.backgroundColor = "red";
}
// END of remnant function

var slider = document.getElementById("colorSlider");
var canvas = document.getElementById("mainCanvas");
var canvasContext = canvas.getContext("2d");

function doSquare() {
  var sliderValue = slider.value;
  canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  canvasContext.fillStyle = "blue";
  canvasContext.fillRect(
    0,
    0,
    sliderValue,
    sliderValue
  );
}

function doColor() {
  var canvasElements = document.getElementById("mainCanvas");
  var pickedColor = document.getElementById("colorInput").value;
  canvasElements.style.backgroundColor = pickedColor;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Inputs and Events</h1>
<canvas id="mainCanvas" height="100px" width="100px"></canvas>

<p>
  <input type="range" min="0" max="100" value="0" id="colorSlider" oninput="doSquare()">

  <input type="color" value="#ffffff" id="colorInput" onchange="doColor()">
</p></code>```

Title: HTML "Range" Input Problems

Body:
I'm trying to write a slider program that will cover an entire square canvas with a blue square when range is set to maximum. There are two problems I'm having though:

When moving my slider, it produces a rectangle instead of a square.

The maximum value of my slider's square only covers less than half of the canvas.

I'm doing my project on Codepen, and my code for the slider is below. Here's a link to my pen if you need the full details: https://codepen.io/drummerlover33/pen/EXdobV.

function doSquare() {
  var slider = document.getElementById("colorSlider");
  var sliderValue = slider.value;
  var canvas = document.getElementById("mainCanvas");
  var canvasContext = canvas.getContext("2d");
  canvasContext.clearRect(0,0,canvas.width,canvas.height);
  canvasContext.fillStyle = "blue";
  canvasContext.fillRect(0,0,sliderValue,sliderValue);
}

Hope you can help a newbie out!

Thanks!

Body:
The canvas's width and height attributes are not only the size of the canvas, but also set its resolution. If you don't set width and height via the attributes (or via script), the canvas's default resolution is 300px X 150px.

Setting the dimensions via CSS only sets the outer size of the canvas element (the style). You have to set the width and the height attributes explicitly on the canvas element.

// Remnant function from previous case
function doRed() {
  var canvasElements = document.getElementById("mainCanvas");
  canvasElements.style.backgroundColor = "red";
}
// END of remnant function

var slider = document.getElementById("colorSlider");
var canvas = document.getElementById("mainCanvas");
var canvasContext = canvas.getContext("2d");

function doSquare() {
  var sliderValue = slider.value;
  canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  canvasContext.fillStyle = "blue";
  canvasContext.fillRect(
    0,
    0,
    sliderValue,
    sliderValue
  );
}

function doColor() {
  var canvasElements = document.getElementById("mainCanvas");
  var pickedColor = document.getElementById("colorInput").value;
  canvasElements.style.backgroundColor = pickedColor;
}

<h1>Inputs and Events</h1>
<canvas id="mainCanvas" height="100px" width="100px"></canvas>

<p>
  <input type="range" min="0" max="100" value="0" id="colorSlider" oninput="doSquare()">

  <input type="color" value="#ffffff" id="colorInput" onchange="doColor()">
</p>


问:
npm init not working and getting stuck on version
So I am using version 8.1.0 of Node.Js and when I call npm init to set up a project it goes to version and stays there. I have tried pressing enter or quitting with ^C but nothing happens. I have waited for over an hour and it hasn't progressed at all. Any idea what I should do?

Here is basically what I am seeing:

Edit: I tried reinstalling and still didn't work; so I uninstalled version 8.1.0 and installed the user recommended one (6.11.0) and it works fine. I am pretty sure it's a bug in version 8.1.0, but it's the one I need.

Edit 2: Oh, I am running this on Windows 10.

答:
Yes, I also faced this issue, so you can downgrade the node to LTS version.

Currently 6.11 version is LTS.

It would be easier to downgrade, if you have used a nvm (Node Version Manager) for installing node.

Use below NVM commands

```<code>nvm install 6.11
nvm use 6.11
</code>```

Body:
Yes, I also faced this issue, so you can downgrade the node to LTS version.

Currently 6.11 version is LTS.

It would be easier to downgrade, if you have used a nvm (Node Version Manager) for installing node.

Use below NVM commands

nvm install 6.11
nvm use 6.11


问:
.Runcommand Type Mismatch
I'm getting a Type mismatched error from AccessApp.Docmd.RunCommand "RunUpdate"

I am trying to open a access database thru automation and run one of the public subs in a modual. This is what im using.

```<code>Sub VCSUpdate()
On Error GoTo ErrorHandler

Dim AccessApp As New Access.Application
Set AccessApp = New Access.Application
AccessApp.AutomationSecurity = msoAutomationSecurityLow
AccessApp.OpenCurrentDatabase CurrentProject.Path & "\VICI Desktop Installer.accde"
AccessApp.RunCommand "RunInstall" '<------ errors here
AccessApp.CloseCurrentDatabase
AccessApp.Quit

Exit Sub
ErrorHandler:
    Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext
End Sub
</code>```

This is what the .Runcommand is tring to run

```<code>Public Sub RunInstall()
    Call LinkFrontEnd
    Call InstallDesktopVICI
End Sub
</code>```

I tried both AccessApp.docm.runcommand and AccessApp.Runcommand both have the same error.

答: You've mistaken Application.RunCommand for Application.Run. Use Application.Run when calling a user-defined function from a string.

Title: .Runcommand Type Mismatch

Body:
I'm getting a Type mismatched error from AccessApp.Docmd.RunCommand "RunUpdate"

I am trying to open a access database thru automation and run one of the public subs in a modual. This is what im using.

Sub VCSUpdate()
On Error GoTo ErrorHandler

Dim AccessApp As New Access.Application
Set AccessApp = New Access.Application
AccessApp.AutomationSecurity = msoAutomationSecurityLow
AccessApp.OpenCurrentDatabase CurrentProject.Path & "\VICI Desktop Installer.accde"
AccessApp.RunCommand "RunInstall" '<------ errors here
AccessApp.CloseCurrentDatabase
AccessApp.Quit

Exit Sub
ErrorHandler:
    Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext
End Sub

This is what the .Runcommand is tring to run

Public Sub RunInstall()
    Call LinkFrontEnd
    Call InstallDesktopVICI
End Sub

I tried both AccessApp.docm.runcommand and AccessApp.Runcommand both have the same error.


问:
How to undelete file in git and keep his original blame history ?
I'v accidentally removed a file (I wasn't his creator) and commit and push it to the remote. Now I want to make git to undelete this change but when I use git revert #mistaken commit it works BUT blame information points at me as the creator of this file not for his original creator. Can anyone knows how to undelete this file in git and keep its original blame history ?
Thanks in advance for any help.
Adam</p>

答:
The only way to do what you want is to rewrite the revision history with something like Find and restore a deleted file in a Git repository. However, this has the nasty side-effect that everyone who has made commits since the file was deleted will now need to rebase their code. As you can imagine, this will cause a lot of work for everyone on the team.

For the sake of everyone's sanity, it is best just to revert the single commit and leave the "blame" as your own. A little bit of history archaeology will show anyone interested what happened.


问:
About use 'aria-expanded' on 'role=menuitem'
aria-expanded="bool" is not support attribute that role="menuitem".

Please refer to W3C HTML Document. (https://www.w3.org/TR/html/)

If use that, get markup error on Nu Html Checker. But when I create some menu widget I must use it. And W3C use the same way in the formula example:

https://www.w3.org/TR/2017/WD-wai-aria-practices-1.1-20170628/examples/menubar/menubar-1/menubar-1.html

https://www.w3.org/WAI/tutorials/menus/application-menus-code/

What is right and what is wrong?

答:
As pointed out by the ARIA documentation

State and properties "Related Concepts", "Used in Roles", "Inherits into Roles" are Advisory information, but more important :

Use of a given state or property is not defined when used on roles other than those listed.

So, you have perfectly the right to use the aria-expanded on a role=menuitem element but the "Nu validator" is right as long as it emits a warning, not an error.

EDIT: HTML-ARIA documentation also specifies that section "3. Allowed ARIA roles, states and properties" is non-normative:

The following table provides an informative reference to the ARIA roles, states and properties permitted for use in HTML. All ARIA roles, states and properties are normatively defined in the ARIA 1.1 specification.


问:
TypeError: Python thinks that I passed a function 2 arguments but I only passed it 1
I work on something in Seattle Repy which is a restricted subset of Python. Anyway, I wanted to implement my own Queue that derives from a list:

```<code>class Queue(list):
    job_count = 0

    def __init__(self):
        list.__init__(self)

    def appendleft(item):
        item.creation_time = getruntime()
        item.current_count = self.job_count
        self.insert(0, item)

    def pop():
        item = self.pop()
        item.pop_time = getruntime()
        return item
</code>```

Now I call this in my main server, where I use my own Job class to pass Jobs to the Queue:

```<code>mycontext['queue'] = Queue()
# ...
job = Job(str(ip), message)
mycontext['queue'].appendleft(job)
</code>```

The last line raises the following exception:

Exception (with type 'exceptions.TypeError'): appendleft() takes exactly 1 argument (2 given)

I'm relatively new to Python, so could anyone explain to me why it would think that I gave appendleft() two arguments when there obviously was only one?

答:
You must enter the self reference in each function definition:</p>

```<code>def appendleft(self, item):
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I work on something in Seattle Repy which is a restricted subset of Python. Anyway, I wanted to implement my own Queue that derives from a list:

class Queue(list):
    job_count = 0

    def __init__(self):
        list.__init__(self)

    def appendleft(item):
        item.creation_time = getruntime()
        item.current_count = self.job_count
        self.insert(0, item)

    def pop():
        item = self.pop()
        item.pop_time = getruntime()
        return item

Now I call this in my main server, where I use my own Job class to pass Jobs to the Queue:

mycontext['queue'] = Queue()
# ...
job = Job(str(ip), message)
mycontext['queue'].appendleft(job)

The last line raises the following exception:

Exception (with type 'exceptions.TypeError'): appendleft() takes exactly 1 argument (2 given)

I'm relatively new to Python, so could anyone explain to me why it would think that I gave appendleft() two arguments when there obviously was only one?

Body:
You must enter the self reference in each function definition:

def appendleft(self, item):


问:
Concatenating specific words together in an array list
I have a problem, suppose I have a text file like so:

Name Surname, number, number ..... number\n
Name Middle  Surname, number, number......number\n
Name, number, number ..... number\n

I wanted to keep the "names + surname" or "names +middle +surname" in each line into one array list index.
For Example, I want "Name Surname" of the first line in one index of an array list.

I did try using a string variable and adding the two elements together in a loop. But as you see the names aren't really of any specific type.
How would I do it? I would really appreciate the help!

答:
Let's suppose you have a String variable called line which holds a given line. In this case:

```<code>String namePart = line.substring(0, line.indexOf(","));
String dataPart = line.substring(line.IndexOf(",") + 1);
</code>```

This should help you get started.

The first row assigns the part of line left to the first comma to namePart. The second row assigns the part of line right to the first comma to dataPart. Of course, you will need to split dataPart using comma as separator and build an array or something like that and add the relevant information into a new entry of your item set.

Body:
Let's suppose you have a String variable called line which holds a given line. In this case:

String namePart = line.substring(0, line.indexOf(","));
String dataPart = line.substring(line.IndexOf(",") + 1);

This should help you get started.

The first row assigns the part of line left to the first comma to namePart. The second row assigns the part of line right to the first comma to dataPart. Of course, you will need to split dataPart using comma as separator and build an array or something like that and add the relevant information into a new entry of your item set.


问:
How to set an icon in MenuTrigger
I have a menu icon in my navbar and I need to use it as a menu.

I'm trying to achieve this with the react-native-popup-menu lib.

The component <MenuTrigger /> only accepts text (strings) as prop.

How could I use an icon as a menu trigger?

答:
Actually MenuTrigger.text is only optional property according to the doc

Optional | Text to be rendered. When this prop is provided, trigger's children won't be rendered

It is possible to place any content inside of MenuTrigger (if you don't use text property) like

```<code><MenuTrigger>
  <YourIcon>
</MenuTrigger>
</code>```

See also official example

Title: How to set an icon in MenuTrigger

Body:
Actually MenuTrigger.text is only optional property according to the doc

Optional | Text to be rendered. When this prop is provided, trigger's children won't be rendered

It is possible to place any content inside of MenuTrigger (if you don't use text property) like

<MenuTrigger>
  <YourIcon>
</MenuTrigger>

See also official example


问:
Getting string from project Resources in VS c#
I have defined some strings within the Rersources tab in Project Properties.

The way I try to get such values is:

```<code>rm = new ResourceManager("items", Assembly.GetExecutingAssembly());
rm.GetString("DBO_LISTA_URLS_TEST");
</code>```

The question is that I do not know what's 'items' and where to get it from.

What's the procedure?

答:
First parameter of ResourceManager constructor is a full namespace of your resource file. I've added two resource files (fisrt from project properties window and second by 'Add new item'):

Now I can get strings from them:

```<code>var assembly = Assembly.GetExecutingAssembly();
var projResource = new ResourceManager("ResourcesDemo.Properties.Resources", assembly);
var customResource = new ResourceManager("ResourcesDemo.Custom", assembly);

Console.WriteLine(projResource.GetString("DBO_LISTA_URLS_TEST"));
Console.WriteLine(customResource.GetString("CUSTOM_RESOURCE"));
</code>```

Body:
I have defined some strings within the Rersources tab in Project Properties.

The way I try to get such values is:

rm = new ResourceManager("items", Assembly.GetExecutingAssembly());
rm.GetString("DBO_LISTA_URLS_TEST");

The question is that I do not know what's 'items' and where to get it from.

What's the procedure?

Body:
First parameter of ResourceManager constructor is a full namespace of your resource file. I've added two resource files (fisrt from project properties window and second by 'Add new item'):

Now I can get strings from them:

var assembly = Assembly.GetExecutingAssembly();
var projResource = new ResourceManager("ResourcesDemo.Properties.Resources", assembly);
var customResource = new ResourceManager("ResourcesDemo.Custom", assembly);

Console.WriteLine(projResource.GetString("DBO_LISTA_URLS_TEST"));
Console.WriteLine(customResource.GetString("CUSTOM_RESOURCE"));


问:
Encode Swift array for Alamofire post using URLEncoding
Reposting as I messed up with the type of encoding before...
I need to send an array to the server with Alamofire using URLEncoding. However, it needs to be encoded in some way for Alamofire to send it properly. This is my code:

```<code>let parameters: [String : Any] = [
    "names" : ["bob", "fred"]
]

Alamofire.request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.default)
   .responseJSON { response in
       // etc
   }
</code>```

However the parameters never get encoded and just get sent as nil. How can I encode it?

答:
I solved it by using the following custom encoding:

```<code>struct ArrayEncoding: ParameterEncoding {
    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var request = try URLEncoding().encode(urlRequest, with: parameters)
        request.url = URL(string: request.url!.absoluteString.replacingOccurrences(of: "%5B%5D=", with: "="))
        return request
    }
}
</code>```

The problem was the arrays were being encoded like foo[]=bar&foo[]=bar2 whereas my server needed it to look like foo=bar&foo=bar2. ArrayEncoding() then replaces URLEncoding.default in the request.

Body:
Reposting as I messed up with the type of encoding before...
I need to send an array to the server with Alamofire using URLEncoding. However, it needs to be encoded in some way for Alamofire to send it properly. This is my code:

let parameters: [String : Any] = [
    "names" : ["bob", "fred"]
]

Alamofire.request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.default)
   .responseJSON { response in
       // etc
   }

However the parameters never get encoded and just get sent as nil. How can I encode it?

Body:
I solved it by using the following custom encoding:

struct ArrayEncoding: ParameterEncoding {
    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var request = try URLEncoding().encode(urlRequest, with: parameters)
        request.url = URL(string: request.url!.absoluteString.replacingOccurrences(of: "%5B%5D=", with: "="))
        return request
    }
}

The problem was the arrays were being encoded like foo[]=bar&foo[]=bar2 whereas my server needed it to look like foo=bar&foo=bar2. ArrayEncoding() then replaces URLEncoding.default in the request.


问:
Is there any means to serialize custom Transformer in Spark ML Pipeline
I use ML pipeline with various custom UDF-based transformers. What I'm looking for is a way to serialize/deserialize this pipeline.

I serialize the PipelineModel using

```<code>ObjectOutputStream.write()
</code>```

However whenever I try to deserialize the pipeline I'm having:

```<code>java.lang.ClassNotFoundException: org.sparkexample.DateTransformer
</code>```

Where is DateTransformer is my custom transformer. Is there any method/interface to implement for proper serialization?

I've found out there is

```<code>MLWritable
</code>```

Interface that might be implemented by my class (DateTransformer extends Transfrormer), however can't find useful example of it.

答:
If you are using Spark 2.x+ then extend your transformer with DefaultParamsWritable

for example

```<code>class ProbabilityMaxer extends Transformer with DefaultParamsWritable{
</code>```

Then create a constructor with a string parameter

```<code> def this(_uid: String) {
    this()
  }
</code>```

Finally for a successful read add a companion class

```<code>object ProbabilityMaxer extends  DefaultParamsReadable[ProbabilityMaxer]
</code>```

I have this working on my production server. I will add gitlab link to the project later when I upload it

Body:
I use ML pipeline with various custom UDF-based transformers. What I'm looking for is a way to serialize/deserialize this pipeline.

I serialize the PipelineModel using

ObjectOutputStream.write()

However whenever I try to deserialize the pipeline I'm having:

java.lang.ClassNotFoundException: org.sparkexample.DateTransformer

Where is DateTransformer is my custom transformer. Is there any method/interface to implement for proper serialization?

I've found out there is

MLWritable

Interface that might be implemented by my class (DateTransformer extends Transfrormer), however can't find useful example of it.

Body:
If you are using Spark 2.x+ then extend your transformer with DefaultParamsWritable

for example

class ProbabilityMaxer extends Transformer with DefaultParamsWritable{

Then create a constructor with a string parameter

 def this(_uid: String) {
    this()
  }

Finally for a successful read add a companion class

object ProbabilityMaxer extends  DefaultParamsReadable[ProbabilityMaxer]

I have this working on my production server. I will add gitlab link to the project later when I upload it


问:
Element componentValidation is not defided in variable
There's a method in one of my components componentValitation.cfc:

```<code><cffunction name="getValidationTypeRegExpByID" access="public"
      returntype="string" output="false">

    <cfargument name="componentValidationTypeID" type="numeric" required="true">
    <cfscript>
        if (structKeyExists(variables.componentValidationTypes, arguments.componentValidationTypeID))
        {
            return variables.componentValidationTypes[arguments.componentValidationTypeID].RegExp;
        }
        return '';
    </cfscript>
</cffunction>
</code>```

I want to call the above mentioned method from another component. I tried calling it from common.cfc like this

```<code>var advertisement = getComponentValidation('component','sys.jo.core.fe.componentValidation');
<cfset testttt = advertisement.getValidationTypeRegExpByID(componentValidationTypeID) />
<cfset errorMessage = "#componentShortLabel# #Lib.showCaption('message_Decimal2dpValidation', UserIdentity)#" />
<cfset arguments.Message.addValidationError( keyName=QuestionID,  errorMessage=errorMessage, componentKey=ComponentID, componentErrorMessage=errorMessage, tupleIndex=arguments.tupleIndex, QuestionDisplayNumber=errorDisplaySequenceNumber ) />
</code>```

But I'm getting an error like Elementcomponent is not defined in variable in componentValidation.cfc (which was already defined in my init() function). Any ideas?

答:
This is probably a mistake:

```<code>var advertisement = getComponentValidation('component','sys.jo.core.fe.componentValidation');
</code>```

Shouldn't it be:

```<code>var advertisement = createobject('component','sys.jo.core.fe.componentValidation');
</code>```

Body:
There's a method in one of my components componentValitation.cfc:

<cffunction name="getValidationTypeRegExpByID" access="public"
      returntype="string" output="false">

    <cfargument name="componentValidationTypeID" type="numeric" required="true">
    <cfscript>
        if (structKeyExists(variables.componentValidationTypes, arguments.componentValidationTypeID))
        {
            return variables.componentValidationTypes[arguments.componentValidationTypeID].RegExp;
        }
        return '';
    </cfscript>
</cffunction>

I want to call the above mentioned method from another component. I tried calling it from common.cfc like this

var advertisement = getComponentValidation('component','sys.jo.core.fe.componentValidation');
<cfset testttt = advertisement.getValidationTypeRegExpByID(componentValidationTypeID) />
<cfset errorMessage = "#componentShortLabel# #Lib.showCaption('message_Decimal2dpValidation', UserIdentity)#" />
<cfset arguments.Message.addValidationError( keyName=QuestionID,  errorMessage=errorMessage, componentKey=ComponentID, componentErrorMessage=errorMessage, tupleIndex=arguments.tupleIndex, QuestionDisplayNumber=errorDisplaySequenceNumber ) />

But I'm getting an error like Elementcomponent is not defined in variable in componentValidation.cfc (which was already defined in my init() function). Any ideas?

Body:
This is probably a mistake:

var advertisement = getComponentValidation('component','sys.jo.core.fe.componentValidation');

Shouldn't it be:

var advertisement = createobject('component','sys.jo.core.fe.componentValidation');


问:
how to add data to an existing dataset
I have a dataset and I am adding some values in it by for loop.

```<code>System.Data.DataSet dsUserResult = new System.Data.DataSet();
dsUserResult = new System.Data.DataSet();
for (i= 0; i< 3; i++) {
  dsUserResult = getUserByProgramId(i); //This return some values and store it into the dsUserresult
}
</code>```

Now if the getUserByProgramId(i) return 4 values when i=0 , it stores it into dataset, but when it runs again for the second time (i=1) , it removes existing dataset value and then add new values, I actually want the new values to be appended with the previous values added in the dataset.

答:
You are not adding some values in the Dataset. You are replacing at each loop the previous values of the dsUserResult with a new dataset returned by the call to getUserByProgramId. The loop ends and the only dataset present is the last one retrieved from the loop.

A Dataset contains a collection of DataTable. It is in this collection that the value retrieved from the database are stored.

So, I suppose, from the name of the method, that every time you call that method  you retrieve a different set of user stored in the first DataTable of the Dataset returned.

If this is what happens inside the getUserByProgramId then you should Merge the result of the first loop with the result of the second loop and the third loop. But what you want to merge are the DataTable contained in the DataSet returned.

```<code>// First dataset used as base...
dsUserResult = getUserByProgramId(0);

// skip the first and get the other two.
for (i=1; i<3; i++)
{
   // Get another one...
   DataSet ds = getUserByProgramId(i);

   // Merge the content of the first table currently returned
   // with the content of the base dataset....
   dsUserResult.Tables[0].Merge(ds.Tables[0]);
}
</code>```

About DataTable.Merge

About Dataset.Tables

Title: how to add data to an existing dataset

Body:
I have a dataset and I am adding some values in it by for loop.

System.Data.DataSet dsUserResult = new System.Data.DataSet();
dsUserResult = new System.Data.DataSet();
for (i= 0; i< 3; i++) {
  dsUserResult = getUserByProgramId(i); //This return some values and store it into the dsUserresult
}

Now if the getUserByProgramId(i) return 4 values when i=0 , it stores it into dataset, but when it runs again for the second time (i=1) , it removes existing dataset value and then add new values, I actually want the new values to be appended with the previous values added in the dataset.

Body:
You are not adding some values in the Dataset. You are replacing at each loop the previous values of the dsUserResult with a new dataset returned by the call to getUserByProgramId. The loop ends and the only dataset present is the last one retrieved from the loop.

A Dataset contains a collection of DataTable. It is in this collection that the value retrieved from the database are stored.

So, I suppose, from the name of the method, that every time you call that method  you retrieve a different set of user stored in the first DataTable of the Dataset returned.

If this is what happens inside the getUserByProgramId then you should Merge the result of the first loop with the result of the second loop and the third loop. But what you want to merge are the DataTable contained in the DataSet returned.

// First dataset used as base...
dsUserResult = getUserByProgramId(0);

// skip the first and get the other two.
for (i=1; i<3; i++)
{
   // Get another one...
   DataSet ds = getUserByProgramId(i);

   // Merge the content of the first table currently returned
   // with the content of the base dataset....
   dsUserResult.Tables[0].Merge(ds.Tables[0]);
}

About DataTable.Merge

About Dataset.Tables


问:
Doc2Vec Gensim Similarity between Document and Topic
I am trying out Gensim for the first time and have a question now. I have trained a LSI Model with a corpus of prepared documents. My question is, how do i get to know if a new document is similar to my model generated from the corpus of documents. I don´t want to know the similarity for the document to each document in my corpus like MatrixSimilarity does but rather know if the document is similar to my topic/model.</p>

答:
I think you should do LSI on new document and then Computing similarity between topics see this.
https://stats.stackexchange.com/questions/271359/using-lda-to-calculate-similarity/271368</p>


问:
Group Addon causes Input to Lose Round Edges on Right Side
When using an input-group-addon (twitter bootsrap css) in a horizontal form layout the input loses the right hand side edge which becomes square instead of the normal nice round edges.

```<code><div class="form-horizontal">
  <div class="form-group">
    <label asp-for="Date" class="col-md-2 control-label"></label>
    <div class="col-md-4">
       <input asp-for="Authoriser" class="form-control" />
      <span asp-validation-for="Date" class="text-danger"></span>
    </div>
    <label asp-for="AircraftID" class="col-md-2 control-label"></label>
    <div class="col-md-4">
      <div class="input-group">
        <span class="input-group-addon"><span class="glyphicon glyphicon-plane"></span></span>
        <select asp-for="AircraftID" class="form-control" asp-items="ViewBag.AircraftID"></select>
        <span asp-validation-for="AircraftID" class="text-danger"></span>
      </div>
    </div>
  </div>
</div>
</code>```

https://jsfiddle.net/knju0sb0/

答:
I have no idea what is this element used for

```<code> <span asp-validation-for="AircraftID" class="text-danger"></span>
</code>```

but this is making the issue. place it outside its div.input-group ,(if possible) to achive rounded corners.

or else override with custom style

hope this helps..

Body:
When using an input-group-addon (twitter bootsrap css) in a horizontal form layout the input loses the right hand side edge which becomes square instead of the normal nice round edges.

       <input asp-for="Authoriser" class="form-control" />

        <select asp-for="AircraftID" class="form-control" asp-items="ViewBag.AircraftID"></select>

https://jsfiddle.net/knju0sb0/

Body:
I have no idea what is this element used for

 <span asp-validation-for="AircraftID" class="text-danger"></span>

but this is making the issue. place it outside its div.input-group ,(if possible) to achive rounded corners.

or else override with custom style

hope this helps..


问:
How to format file in Visual Studio Code (hotkeys)?
How to format file | project folder | all project files (using hot keys AND using menu) in Visual Studio Code?</p>

答:
@Sergii

Your question looks like you are looking for a way to format your entire code in VSCode.  If this is the case, a VSCode extension like Prettier should meet the three requirements you've listed (file | project folder | all project files).  Bear in mind though that formatting all project files is a bit unclear and you probably want to be specific about formatting all *.ts or all *.js files etc.

The below may be of help to you:

Read about prettier because it provides ability to format entire code base

Install prettier-vscode extension to your VSCode and enable settings that you want

Alternatively, you can use prettier from the CLI, npm build script or via its API in build task - the choice is yours.

The one I found most useful is adding it as a git pre-commit hook for staged files.

I hope above points you in the right direction.

SOJ


问:
Subscript in text (Windows Forms) in C#
How to display superscript in Windows Forms using C#.
Say, i need to display 5 cubic metre as
    5 m3 (with 3 as superscript). </p>

答: The keystroke for the '³' character is Alt+0179. Charmap is your friend. ;)</p>

Title: Subscript in text (Windows Forms) in C#


问:
How to get tabs in angular forms based on given xml file?
I have to get number of input tabs or fields based on given xml or json file.

example : If xml has 3 tags, then form should contain 3 input fields.
Same with JSON.

答:
You can use ng-repeat on service response array of objects. And also you can create new scope variable & assign unique property of response array object to it. Then you can have as many number of input fields based on service data & also dynamic ng-model on them to handle their model data to submit it.
This is small example which demonstrates your requirement: http://jsfiddle.net/DrQ77/

For xml response, better use xml to json library plugins to convert it to json data https://github.com/abdmob/x2js. Or prefer server side sending json data (with implementing xml to json functionality at server side).


问:
send html template in php
My Php mail code is like this i want to send html content in mail but i can not send html template with this code

```<code>                    $to = $email;;
                    $subject = 'New Order Detail';
                    $message = 'Hi Jane';
                    $from = 'info@abc.co.in';

                    // Sending email
                    if(mail($to, $subject, $message))
                    {
                        echo 'Your mail has been sent successfully.';
                    }
                    else
                    {
                        echo 'Unable to send email. Please try again.';
                        $headers  = 'MIME-Version: 1.0' . "\r\n";
                        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

                        // Create email headers
                        $headers .= 'From: '.$from."\r\n".
                            'Reply-To: '.$from."\r\n" .
                            'X-Mailer: PHP/' . phpversion();

                        // Compose a simple HTML email message
                        $message = '<html><body>';
                        $message = '<table border="1" align="center" width="50%">';
                        $message .= '<tr><td>Test Mail';
                        $message .= '</td></tr>';
                        //$message .= '<p style="color:#080;font-size:18px;">Will you marry me?</p>';
                        $message .= '</table>';
                        $message .= '</body></html>';

                        // Sending email
                        if(mail($to, $subject, $message, $headers))
                        {
                            echo 'Your mail has been sent successfully.';
                        } else
                        {
                            echo 'Unable to send email. Please try again.';
                        }
                    }
</code>```

This kind of output i get in mail i do not know where is my mistake in this code..
Output

```<code><html><body>
<table border="1" align="center" width="50%">
<tr><td>Test Mail</td></tr>
</table>
</body></html>
</code>```

答:
A variation on a theme perhaps and redundant as you have an answer. You should be able to add styles within the style tag region of the below code - or you could potentially add a link to an external css file but that could cause issues.

```<code>$to = $email;
$subject = 'New Order Detail';
$message = 'Hi Jane';
$from = 'info@abc.co.in';

$obj=new StdClass;
$obj->success='Your mail has been sent successfully.';
$obj->fail='Unable to send email. Please try again.';
$obj->nl="\r\n";

$status = @mail( $to, $subject, $message );

if( $status ) {
    exit( $obj->success );
} else {

    $headers = array();
    $html = array();

    $headers[]="MIME-Version: 1.0";
    $headers[]="From: {$from}";
    $headers[]="Reply-To: {$from}";
    $headers[]="X-Mailer: PHP/". phpversion();
    $headers[]="MIME-Version: 1.0";
    $headers[]="Content-type: text/html; charset=iso-8859-1";

    $html[]="";
    $html[]="<html>";
    $html[]="<head>";
    $html[]="<title>{$subject}</title>";
    $html[]="<style>";
    $html[]="p{color:red;font-size:18px;}";
    $html[]="table{border:1px solid black;width:50%;display:table;}";
    $html[]="td{text-align:center;background:yellow;color:blue;}";
    $html[]="</style>";
    $html[]="</head>";
    $html[]="<body>";
    $html[]="<table>";
    $html[]="<tr><td>Test Mail</td></tr>";
    $html[]="<tr><td><p>Will you marry me?</p></td></tr>";
    $html[]="</table>";
    $html[]="</body>";
    $html[]="</html>";

    $status = @mail( $to, $subject, implode( $obj->nl, $html ), implode( $obj->nl, $headers ) );

    exit( $status ? $obj->success : $obj->fail );
}
</code>```

Title: send html template in php

Body:
My Php mail code is like this i want to send html content in mail but i can not send html template with this code

                    $to = $email;;
                    $subject = 'New Order Detail';
                    $message = 'Hi Jane';
                    $from = 'info@abc.co.in';

                    // Sending email
                    if(mail($to, $subject, $message))
                    {
                        echo 'Your mail has been sent successfully.';
                    }
                    else
                    {
                        echo 'Unable to send email. Please try again.';
                        $headers  = 'MIME-Version: 1.0' . "\r\n";
                        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

                        // Create email headers
                        $headers .= 'From: '.$from."\r\n".
                            'Reply-To: '.$from."\r\n" .
                            'X-Mailer: PHP/' . phpversion();

                        // Compose a simple HTML email message
                        $message = '';
                        $message = '
';
                        $message .= '
Test Mail';
                        $message .= '
';
                        //$message .= '
Will you marry me?
';
                        $message .= '
';
                        $message .= '';

                        // Sending email
                        if(mail($to, $subject, $message, $headers))
                        {
                            echo 'Your mail has been sent successfully.';
                        } else
                        {
                            echo 'Unable to send email. Please try again.';
                        }
                    }

This kind of output i get in mail i do not know where is my mistake in this code..
Output

Test Mail

Body:
A variation on a theme perhaps and redundant as you have an answer. You should be able to add styles within the style tag region of the below code - or you could potentially add a link to an external css file but that could cause issues.

$to = $email;
$subject = 'New Order Detail';
$message = 'Hi Jane';
$from = 'info@abc.co.in';

$obj=new StdClass;
$obj->success='Your mail has been sent successfully.';
$obj->fail='Unable to send email. Please try again.';
$obj->nl="\r\n";

$status = @mail( $to, $subject, $message );

if( $status ) {
    exit( $obj->success );
} else {

    $headers = array();
    $html = array();

    $headers[]="MIME-Version: 1.0";
    $headers[]="From: {$from}";
    $headers[]="Reply-To: {$from}";
    $headers[]="X-Mailer: PHP/". phpversion();
    $headers[]="MIME-Version: 1.0";
    $headers[]="Content-type: text/html; charset=iso-8859-1";

    $html[]="";
    $html[]="<html>";
    $html[]="<head>";
    $html[]="<title>{$subject}</title>";
    $html[]="<style>";
    $html[]="p{color:red;font-size:18px;}";
    $html[]="table{border:1px solid black;width:50%;display:table;}";
    $html[]="td{text-align:center;background:yellow;color:blue;}";
    $html[]="</style>";
    $html[]="</head>";
    $html[]="<body>";
    $html[]="<table>";
    $html[]="<tr><td>Test Mail</td></tr>";
    $html[]="<tr><td><p>Will you marry me?</p></td></tr>";
    $html[]="</table>";
    $html[]="</body>";
    $html[]="</html>";

    $status = @mail( $to, $subject, implode( $obj->nl, $html ), implode( $obj->nl, $headers ) );

    exit( $status ? $obj->success : $obj->fail );
}


问:
In sklearn's classification_report, what does avg/total mean? How is it computed?
```<code>              precision    recall  f1-score   support

          0       0.98      0.90      0.94       305
          1       0.77      0.93      0.84       102
avg / total       0.92      0.91      0.91       407
</code>```

what does avg/total mean? and how does it be computed?
didn't find answer on the official website TAT

答:
Let's take a look at your first column. In the third row of the column you can see that 0.92 is computed by
0.98*(305/407) + 0.77*(102/407).

Body:
              precision    recall  f1-score   support

          0       0.98      0.90      0.94       305
          1       0.77      0.93      0.84       102
avg / total       0.92      0.91      0.91       407

what does avg/total mean? and how does it be computed?
didn't find answer on the official website TAT


问:
Trigger when video completes in an iframe on a page
I have a video in an iframe on a page. I am hoping to trigger a function, let's say an alert("Finished"); when the video finishes.

Hence, there are two things I wanna do:

Show alert()

Trigger alert when the video finishes.

The video is in an iframe.

HTML

```<code><div class="h5p-iframe-wrapper">
<iframe id="h5p-iframe-3" class="h5p-iframe h5p-initialized" data-content-id="3" style="height: 761px;" src="about:blank" frameborder="0" scrolling="no">

<video src="http://techslides.com/demos/sample-videos/small.mp4" webkit-playsinline="" playsinline="" preload="metadata" class="h5p-video" style="display: block;"></video>

</iframe></div>
</code>```

This is what I tried

```<code>$("iframe").each(function() {
        var src= $(this).attr('src');
        $(this).attr('src',src);
});
</code>```

It kinda doesn't work.

Any idea what I can do?

答:
Why are you going for a video inside an iframe when you don't have anything inside the iframe?

This is just using the video tag inside div.

```<code> $(".h5p-iframe-wrapper > video").on('ended',function(){  alert('Video has ended!');  });
</code>```

or

```<code> $("div > video",".h5p-iframe-wrapper").on('ended',function(){  alert('Video has ended!');  });
</code>```

or

```<code>$(".h5p-iframe-wrapper").contents().find('video').on('ended',function(){ alert("Video has ended!");});
</code>```

Body:
I have a video in an iframe on a page. I am hoping to trigger a function, let's say an alert("Finished"); when the video finishes.

Hence, there are two things I wanna do:

Show alert()

Trigger alert when the video finishes.

The video is in an iframe.

HTML

<video src="http://techslides.com/demos/sample-videos/small.mp4" webkit-playsinline="" playsinline="" preload="metadata" class="h5p-video" style="display: block;"></video>

This is what I tried

$("iframe").each(function() {
        var src= $(this).attr('src');
        $(this).attr('src',src);
});

It kinda doesn't work.

Any idea what I can do?

Body:
Why are you going for a video inside an iframe when you don't have anything inside the iframe?

This is just using the video tag inside div.

 $(".h5p-iframe-wrapper > video").on('ended',function(){  alert('Video has ended!');  });

or

 $("div > video",".h5p-iframe-wrapper").on('ended',function(){  alert('Video has ended!');  });

or

$(".h5p-iframe-wrapper").contents().find('video').on('ended',function(){ alert("Video has ended!");});


问:
Vba, Excel, Changing calculation base on dropdown list and clearing cell when others are blank
I created an excel sheet to merge 3 columns into 1 string. The code should produce a string like this:

```<code>"A"; B; C; 0.000; 14.1; 4.1; 14.1; ""; 0.00; -3.1; ""; 0.00; ""; 1; 0.500; 0.000; 0.000; 0; 0.05
</code>```

At its current state, the code works just fine it just that I'd like to make it a little bit more tidy and functional.

```<code>Sub WP2_Maker()
'
' Simple_WP2_Maker Macro
'

For i = 20 To Cells(Rows.Count, "B").End(xlUp).Row
Cells(i, "E").Value = Chr(34) & Cells(i, "A").Value & Chr(34) & "; " & Cells(i, "B").Value & "; " & Cells(i, "C").Value & "; " & "0.000" & "; " & "14.1" & "; " & "4.1" & "; " & "14.1" & "; " & Chr(34) & Chr(34) & "; " & "0.00" & "; " & "-3.1" & "; " & Chr(34) & Chr(34) & "; " & "0.00" & "; " & Chr(34) & Chr(34) & "; " & "1" & "; " & "0.500" & "; " & "0.000" & "; " & "0.000" & "; " & "0" & "; " & "0.05"

Next i
End Sub
</code>```

Basically I have 3 columns A, B and C and when clicked generate, it populate row E with the combined string.

For now, it does the job fine but there are more features that I'd like to add.

I added clear all button to clear the sheet for next input, because
now even though I clear cell A, B, C for new input, I still need to
clear cell E too. how can I make column E to automatically cleared
upon clicking generate button when cells in B and/or C are blank?
Saw this workaround but not sure how to implement it in my code.
(Determine when two consecutive cells are blank)

How to create a save button to save the generated string into a text
format without messing with the result? I'd tried save it as tab
delimited format but that added extra quotes in the strings.

I wanted to have a drop down list/combo box showing options like
circle (-2.1), small circle (-3.1) and depending on which option
selected change the values in the code respectively. How can I
achieve this?

Thank you.

答:
I suggest to create column E via a formula like (E20):

```<code>=IF(LEN(A20&B20&C20),""""&A20&"""; "&B20&"; "&C20&"; 0.000; 14.1; 4.1; 14.1; """"; 0.00; -3.1; """"; 0.00; """"; 1; 0.500; 0.000; 0.000; 0; 0.05","")
</code>```

If you want to change the 3.1 to something different via dropdown simply change the formula (assuming the dropdown at E1):

```<code>=IF(LEN(A20&B20&C20),""""&A20&"""; "&B20&"; "&C20&"; 0.000; 14.1; 4.1; 14.1; """"; 0.00; "&E1&"; """"; 0.00; """"; 1; 0.500; 0.000; 0.000; 0; 0.05","")
</code>```

Simply copy the formula down as you like to (if A, B and C are empty, the formula shows an empty string)

And then run the code to populate.

To save column E (20 to last entry) the way you want, you can do it via Open For Output:

```<code>Option Explicit

Public Sub to_text()

  Dim i As Long

  Open "C:\OutputTestFile.txt" For Output As #1

    For i = 20 To Columns(5).Find("*", Cells(1, 5), xlValues, , , 2).Row
      Print #1, Cells(i, 5).Value
    Next i

  Close 1#

End Sub
</code>```

Using the formula, column E will be automatically empty when clearing contents for A:C.

Body:
I created an excel sheet to merge 3 columns into 1 string. The code should produce a string like this:

"A"; B; C; 0.000; 14.1; 4.1; 14.1; ""; 0.00; -3.1; ""; 0.00; ""; 1; 0.500; 0.000; 0.000; 0; 0.05

At its current state, the code works just fine it just that I'd like to make it a little bit more tidy and functional.

Sub WP2_Maker()
'
' Simple_WP2_Maker Macro
'

For i = 20 To Cells(Rows.Count, "B").End(xlUp).Row
Cells(i, "E").Value = Chr(34) & Cells(i, "A").Value & Chr(34) & "; " & Cells(i, "B").Value & "; " & Cells(i, "C").Value & "; " & "0.000" & "; " & "14.1" & "; " & "4.1" & "; " & "14.1" & "; " & Chr(34) & Chr(34) & "; " & "0.00" & "; " & "-3.1" & "; " & Chr(34) & Chr(34) & "; " & "0.00" & "; " & Chr(34) & Chr(34) & "; " & "1" & "; " & "0.500" & "; " & "0.000" & "; " & "0.000" & "; " & "0" & "; " & "0.05"

Next i
End Sub

Basically I have 3 columns A, B and C and when clicked generate, it populate row E with the combined string.

For now, it does the job fine but there are more features that I'd like to add.

I added clear all button to clear the sheet for next input, because
now even though I clear cell A, B, C for new input, I still need to
clear cell E too. how can I make column E to automatically cleared
upon clicking generate button when cells in B and/or C are blank?
Saw this workaround but not sure how to implement it in my code.
(Determine when two consecutive cells are blank)

How to create a save button to save the generated string into a text
format without messing with the result? I'd tried save it as tab
delimited format but that added extra quotes in the strings.

I wanted to have a drop down list/combo box showing options like
circle (-2.1), small circle (-3.1) and depending on which option
selected change the values in the code respectively. How can I
achieve this?

Thank you.

Body:
I suggest to create column E via a formula like (E20):

=IF(LEN(A20&B20&C20),""""&A20&"""; "&B20&"; "&C20&"; 0.000; 14.1; 4.1; 14.1; """"; 0.00; -3.1; """"; 0.00; """"; 1; 0.500; 0.000; 0.000; 0; 0.05","")

If you want to change the 3.1 to something different via dropdown simply change the formula (assuming the dropdown at E1):

=IF(LEN(A20&B20&C20),""""&A20&"""; "&B20&"; "&C20&"; 0.000; 14.1; 4.1; 14.1; """"; 0.00; "&E1&"; """"; 0.00; """"; 1; 0.500; 0.000; 0.000; 0; 0.05","")

Simply copy the formula down as you like to (if A, B and C are empty, the formula shows an empty string)

And then run the code to populate.

To save column E (20 to last entry) the way you want, you can do it via Open For Output:

Option Explicit

Public Sub to_text()

  Dim i As Long

  Open "C:\OutputTestFile.txt" For Output As #1

    For i = 20 To Columns(5).Find("*", Cells(1, 5), xlValues, , , 2).Row
      Print #1, Cells(i, 5).Value
    Next i

  Close 1#

End Sub

Using the formula, column E will be automatically empty when clearing contents for A:C.


问:
How to group records in Ecto and return them as a map?
I have "influencer_platforms" table in my DB which consists of:

```<code>id | influencer_handle | name
</code>```

I want to query them and group by name like:

```<code>%{
  name1: [%{id: 1, influencer_handle: "i1"}, %{id: 3, influencer_handle: "i2"}],
  name2: [%{id: 2, influencer_handle: "i3"}]
}
</code>```

How do do that in Ecto? So far I have:

```<code>defmacrop influencer_platform_json(influencer) do
  quote do
    fragment(
      "jsonb_agg(?)",
      fragment(
        "json_build_object(?, ?, ?, ?)",
        "id",                unquote(influencer).id,
        "influencer_handle", unquote(influencer).influencer_handle
      )
    )
  end
end

def all do
  from ip in InfluencerPlatform,
    group_by: :name,
    select: %{
      ip.name => influencer_platform_json(ip)
    }
end
</code>```

Is is a more elegant way to achieve it?

答:
If you want all this to be done in the database, you could collapse the two fragments into one. You also don't need to pass the column names as arguments to fragment if they're simple constants; you can put the column names inside the query in fragment.

```<code>defmacrop influencer_platform_json(influencer) do
  quote do
    fragment("jsonb_agg(jsonb_build_object('id', ?, 'influencer_handle', ?))", unquote(influencer).id, unquote(influencer).influencer_handle)
  end
end
</code>```

You could also fetch the necessary data and do the group by in Elixir using Enum.group_by/2. This would be much more elegant but may be less performant than the above, depending on how optimized PostgreSQL's JSON handling is for the above query.

```<code>from(ip in InfluencerPlatform, select: map(ip, [:id, :name, :influencer_handle]))
|> Repo.all
|> Enum.group_by(fn ip -> ip.name end)
# Delete `:name` from each map.
|> Enum.map(fn {k, v} ->
  {k, Enum.map(v, &Map.delete(&1, :name))}
end)
|> Map.new
</code>```

Body:
I have "influencer_platforms" table in my DB which consists of:

id | influencer_handle | name

I want to query them and group by name like:

%{
  name1: [%{id: 1, influencer_handle: "i1"}, %{id: 3, influencer_handle: "i2"}],
  name2: [%{id: 2, influencer_handle: "i3"}]
}

How do do that in Ecto? So far I have:

defmacrop influencer_platform_json(influencer) do
  quote do
    fragment(
      "jsonb_agg(?)",
      fragment(
        "json_build_object(?, ?, ?, ?)",
        "id",                unquote(influencer).id,
        "influencer_handle", unquote(influencer).influencer_handle
      )
    )
  end
end

def all do
  from ip in InfluencerPlatform,
    group_by: :name,
    select: %{
      ip.name => influencer_platform_json(ip)
    }
end

Is is a more elegant way to achieve it?

Body:
If you want all this to be done in the database, you could collapse the two fragments into one. You also don't need to pass the column names as arguments to fragment if they're simple constants; you can put the column names inside the query in fragment.

defmacrop influencer_platform_json(influencer) do
  quote do
    fragment("jsonb_agg(jsonb_build_object('id', ?, 'influencer_handle', ?))", unquote(influencer).id, unquote(influencer).influencer_handle)
  end
end

You could also fetch the necessary data and do the group by in Elixir using Enum.group_by/2. This would be much more elegant but may be less performant than the above, depending on how optimized PostgreSQL's JSON handling is for the above query.

from(ip in InfluencerPlatform, select: map(ip, [:id, :name, :influencer_handle]))
|> Repo.all
|> Enum.group_by(fn ip -> ip.name end)
# Delete `:name` from each map.
|> Enum.map(fn {k, v} ->
  {k, Enum.map(v, &Map.delete(&1, :name))}
end)
|> Map.new