问:
How to also change UIButton Image when UITableViewCell uncollapsed using Swift?
I know subject question sounds complicated. I will do my best to simplify the issue I am having.

I have UIButton in my UITableView. UITableViewCell is configured for the UITableView. Although, I am using UIButton action inside my UIViewController. I have setup a collapse/uncollapse for the UITableViewCells by simply changing the row height and with some priority constraint manipulation. When uncollapsing happens additional information appears underneath the cell. This far everything work flawlessly.

When I click the UIButton collapsed-default state, I change UIButton image to another one. And then when I click to cell to uncollapse UIButton image goes back to initial one. This also happens vice-versa. So, I am guessing whenever I change height of the row, UITableView recreates the cell so changes made prior is not showing.

Here is the related code:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "FavCell", for: indexPath) as? FavCell else { return UITableViewCell() }

if let data = UserDefaults.standard.data(forKey: selectedCur),
    let storedCurrencies = NSKeyedUnarchiver.unarchiveObject(with: data) as? [SelectedCurrency] {
    selectedCurrencies = storedCurrencies
    // SORT BY RANK
    selectedCurrencies.sort(by: { $0.rank! < $1.rank! })
        if selectedCurrencies.count > 0 {
             // CATCH ANY NIL VALUES AND PREVENT APP CRASHES
             let noVal = selectedCurrencies[indexPath.row].rank ?? 0
             let nameVal = selectedCurrencies[indexPath.row].name ?? "N/A"
             let symbolVal = selectedCurrencies[indexPath.row].symbol ?? "N/A"

             cell.configureCell(no: "\(noVal)", name: nameVal, symbol: symbolVal)
        }
    }
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if collapseIndex == indexPath.row {
        collapseIndex = -1
    } else {
        collapseIndex = indexPath.row
    }

    tableView.beginUpdates()
    tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
    tableView.endUpdates()
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if collapseIndex == indexPath.row {
        return 280  // When collapsed cell view displayed - Number will be adjusted after
    } else {
        return 120  // Height of initial cell contents that fits
    }
}

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}
</code>```

Below is how I change UIButtons image:

```<code>class NotificationBtn: UIButton {
var bellToggle = Int()
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if bellToggle == 1 {
        self.transform = CGAffineTransform(scaleX: 1.25, y: 1.25)             // Bounce
        self.setImage(UIImage(named: "bell_off"), for: .normal)
        UIView.animate(withDuration: 1.2, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 6, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity }, completion: nil)
        curImg = self.image(for: .normal)!
        bellToggle = 2

        super.touchesBegan(touches, with: event)

    } else {
        self.transform = CGAffineTransform(rotationAngle: 25 * 3.14/180.0)  // Rotate via 25 degree - Bell ringing animation
        self.setImage(UIImage(named: "bell_on"), for: .normal)

        UIView.animate(withDuration: 1.2, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 6, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity }, completion: nil)

        curImg = self.image(for: .normal)!
        bellToggle = 1

        super.touchesBegan(touches, with: event)
    }
}
}
</code>```

Thank you for your time.

答:
You guessed right. When you call reloadRows method, cellForRowAt is called and replace the cell which you want to reload with another cell. The cell is replaced so the appeared button is another button. That's why you have wrong image for button.

To fix it, in cellForRowAt method, check and update your button image with collapseIndex. I think it will work. For example, inside cellForRowAt, after creating cell

```<code>if collapseIndex == indexPath.row {
    // Updated button with collapse state image
} else {
    // Updated button with uncollapse state image
}
</code>```

Body:
I know subject question sounds complicated. I will do my best to simplify the issue I am having.

I have UIButton in my UITableView. UITableViewCell is configured for the UITableView. Although, I am using UIButton action inside my UIViewController. I have setup a collapse/uncollapse for the UITableViewCells by simply changing the row height and with some priority constraint manipulation. When uncollapsing happens additional information appears underneath the cell. This far everything work flawlessly.

When I click the UIButton collapsed-default state, I change UIButton image to another one. And then when I click to cell to uncollapse UIButton image goes back to initial one. This also happens vice-versa. So, I am guessing whenever I change height of the row, UITableView recreates the cell so changes made prior is not showing.

Here is the related code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "FavCell", for: indexPath) as? FavCell else { return UITableViewCell() }

if let data = UserDefaults.standard.data(forKey: selectedCur),
    let storedCurrencies = NSKeyedUnarchiver.unarchiveObject(with: data) as? [SelectedCurrency] {
    selectedCurrencies = storedCurrencies
    // SORT BY RANK
    selectedCurrencies.sort(by: { $0.rank! < $1.rank! })
        if selectedCurrencies.count > 0 {
             // CATCH ANY NIL VALUES AND PREVENT APP CRASHES
             let noVal = selectedCurrencies[indexPath.row].rank ?? 0
             let nameVal = selectedCurrencies[indexPath.row].name ?? "N/A"
             let symbolVal = selectedCurrencies[indexPath.row].symbol ?? "N/A"

             cell.configureCell(no: "\(noVal)", name: nameVal, symbol: symbolVal)
        }
    }
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if collapseIndex == indexPath.row {
        collapseIndex = -1
    } else {
        collapseIndex = indexPath.row
    }

    tableView.beginUpdates()
    tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
    tableView.endUpdates()
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if collapseIndex == indexPath.row {
        return 280  // When collapsed cell view displayed - Number will be adjusted after
    } else {
        return 120  // Height of initial cell contents that fits
    }
}

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

Below is how I change UIButtons image:

class NotificationBtn: UIButton {
var bellToggle = Int()
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if bellToggle == 1 {
        self.transform = CGAffineTransform(scaleX: 1.25, y: 1.25)             // Bounce
        self.setImage(UIImage(named: "bell_off"), for: .normal)
        UIView.animate(withDuration: 1.2, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 6, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity }, completion: nil)
        curImg = self.image(for: .normal)!
        bellToggle = 2

        super.touchesBegan(touches, with: event)

    } else {
        self.transform = CGAffineTransform(rotationAngle: 25 * 3.14/180.0)  // Rotate via 25 degree - Bell ringing animation
        self.setImage(UIImage(named: "bell_on"), for: .normal)

        UIView.animate(withDuration: 1.2, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 6, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity }, completion: nil)

        curImg = self.image(for: .normal)!
        bellToggle = 1

        super.touchesBegan(touches, with: event)
    }
}
}

Thank you for your time.

Body:
You guessed right. When you call reloadRows method, cellForRowAt is called and replace the cell which you want to reload with another cell. The cell is replaced so the appeared button is another button. That's why you have wrong image for button.

To fix it, in cellForRowAt method, check and update your button image with collapseIndex. I think it will work. For example, inside cellForRowAt, after creating cell

if collapseIndex == indexPath.row {
    // Updated button with collapse state image
} else {
    // Updated button with uncollapse state image
}


来源: stackexchange

问:
Laravel 5.5 - Only log 500 error, never send error details via api?
I made the below controller to demonstrate the issue of handling 500 errors I am having with the api. I want to be able to detect when a 500 error will be thrown so it never makes it to the client (as it is too much details to share with the client and they should only be logged by Laravel).

The methodgetUser() returns a 500 error intentionally due to the typo firsgt()

```<code>class TestController extends Controller {
  public function getUser() {
    $data = User::firsgt(); //returns 500 error
    return $data;
  }
}
</code>```

This is what the client sees:

How can we return an error message like 'Error occurred' instead of the too much details for client 'Call to undefined method App\User::firsgt()'?

Note: I don't want to handle it one by one for each controller method, but instead capture any 500 before it is returned to client, and return the custom 500 generic message 'Error occurred'

答:
Laravel already does this for you, but only if you are in production mode and the request is expecting JSON.

Anyhow, the App\Exceptions\Handler class is where all exceptions can be handled. It's also the place where all exceptions are logged and rendered by Laravel itself.

```<code>public function render($request, Exception $exception)
{
    // your logic here

    return parent::render($request, $exception);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I made the below controller to demonstrate the issue of handling 500 errors I am having with the api. I want to be able to detect when a 500 error will be thrown so it never makes it to the client (as it is too much details to share with the client and they should only be logged by Laravel).

The methodgetUser() returns a 500 error intentionally due to the typo firsgt()

class TestController extends Controller {
  public function getUser() {
    $data = User::firsgt(); //returns 500 error
    return $data;
  }
}

This is what the client sees:

How can we return an error message like 'Error occurred' instead of the too much details for client 'Call to undefined method App\User::firsgt()'?

Note: I don't want to handle it one by one for each controller method, but instead capture any 500 before it is returned to client, and return the custom 500 generic message 'Error occurred'

Body:
Laravel already does this for you, but only if you are in production mode and the request is expecting JSON.

Anyhow, the App\Exceptions\Handler class is where all exceptions can be handled. It's also the place where all exceptions are logged and rendered by Laravel itself.

public function render($request, Exception $exception)
{
    // your logic here

    return parent::render($request, $exception);
}


问:
How to send authorization header with axios
How can I send an authentication header with a token via axios.js?
I have tried a few things without success, for example:

```<code>const header = `Authorization: Bearer ${token}`;
return axios.get(URLConstants.USER_URL, { headers: { header } });
</code>```

Gives me this error:

```<code>XMLHttpRequest cannot load http://localhost:8000/accounts/user/. Request header field header is not allowed by Access-Control-Allow-Headers in preflight response.
</code>```

I have managed to get it work by setting global default, but I'm guessing this is not the best idea for a single request:

```<code>axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
</code>```

Update :

Cole's answer helped me find the problem. I am using django-cors-headers middleware which already handles authorization header by default.

But I was able to understand the error message and fixed an error in my axios request code, which should look like this

```<code>return axios.get(URLConstants.USER_URL, { headers: { Authorization: `Bearer ${data.token}` } });
</code>```

答:
You are nearly correct, just adjust your code this way

```<code>const headers = { Authorization: `Bearer ${token}` };
return axios.get(URLConstants.USER_URL, { headers });
</code>```

notice where I place the backticks, I added ' ' after Bearer, you can omit if you'll be sure to handle at the server-side

ContentLicense: CC BY-SA 4.0

Body:
How can I send an authentication header with a token via axios.js?
I have tried a few things without success, for example:

const header = `Authorization: Bearer ${token}`;
return axios.get(URLConstants.USER_URL, { headers: { header } });

Gives me this error:

XMLHttpRequest cannot load http://localhost:8000/accounts/user/. Request header field header is not allowed by Access-Control-Allow-Headers in preflight response.

I have managed to get it work by setting global default, but I'm guessing this is not the best idea for a single request:

axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;

Update :

Cole's answer helped me find the problem. I am using django-cors-headers middleware which already handles authorization header by default.

But I was able to understand the error message and fixed an error in my axios request code, which should look like this

return axios.get(URLConstants.USER_URL, { headers: { Authorization: `Bearer ${data.token}` } });

Body:
You are nearly correct, just adjust your code this way

const headers = { Authorization: `Bearer ${token}` };
return axios.get(URLConstants.USER_URL, { headers });

notice where I place the backticks, I added ' ' after Bearer, you can omit if you'll be sure to handle at the server-side


问:
Get batterylevel of more than one bluetoothdevices (beacons)
I want to get the battery level of more than one bluetooth device in android using the gatt service.
My current code is this (I am sorry that it looks a bit chaotic):

```<code>public void readCustomCharacteristic() {
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    mBluetoothAdapter.getBluetoothLeScanner().startScan(new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            //Log.i("Beacons", "callbacktype: " + String.valueOf(callbackType));
            Log.i("Beacons", "result: " + result.toString());
            BluetoothDevice btDevice = result.getDevice();
            Log.i("Beacons", "Devicescan: " + (btDevice != null));

                BluetoothGatt bluetoothGatt = btDevice.connectGatt(
                        getApplicationContext(), false, new BluetoothGattCallback() {
                            @Override
                            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                                //super.onConnectionStateChange(gatt, status, newState);
                                Log.i("Beacons", "areServicesDiscovered: " + gatt.discoverServices());
                                if(gatt.discoverServices()) {
                                    onServicesDiscovered(gatt, status);
                                }
                            }

                            @Override
                            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                                if (gatt.discoverServices()) {
                                    //if (status == BluetoothGatt.GATT_SUCCESS) {

                                            Log.d("Beacons", "Number of Services: " + gatt.getServices().size());

                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {

                                                    BluetoothGattCharacteristic chars = gatt.getServices().get(0).getCharacteristic(Battery_Level_UUID);
                                                    Log.i("Beacons", "charsstringval: " + chars.getValue().length);

                                                }
                                            });

                                }
                            }
                        });
        }
    });
}
</code>```

I have to scan more than one beacon, and when it is scanning a device and it only getssometimes a service.
The problem is when the code wants to read the characteristic the service handle is again null. I'm desperate and I hope you can help me.

答:
In short, because your runnable runs on a different thread, the value of gatt.getServices() may have changed.

I would simply retrieve the updated services list, check the size, and then only make the call if there is at least one service.

```<code>if (gatt.getServices().size() > 0) {
    BluetoothGattCharacteristic chars = gatt.getServices().get(0).getCharacteristic(Battery_Level_UUID);
    Log.i("Beacons", "charsstringval: " + chars.getValue().length);
}
</code>```

Body:
I want to get the battery level of more than one bluetooth device in android using the gatt service.
My current code is this (I am sorry that it looks a bit chaotic):

public void readCustomCharacteristic() {
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    mBluetoothAdapter.getBluetoothLeScanner().startScan(new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            //Log.i("Beacons", "callbacktype: " + String.valueOf(callbackType));
            Log.i("Beacons", "result: " + result.toString());
            BluetoothDevice btDevice = result.getDevice();
            Log.i("Beacons", "Devicescan: " + (btDevice != null));

                BluetoothGatt bluetoothGatt = btDevice.connectGatt(
                        getApplicationContext(), false, new BluetoothGattCallback() {
                            @Override
                            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                                //super.onConnectionStateChange(gatt, status, newState);
                                Log.i("Beacons", "areServicesDiscovered: " + gatt.discoverServices());
                                if(gatt.discoverServices()) {
                                    onServicesDiscovered(gatt, status);
                                }
                            }

                            @Override
                            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                                if (gatt.discoverServices()) {
                                    //if (status == BluetoothGatt.GATT_SUCCESS) {

                                            Log.d("Beacons", "Number of Services: " + gatt.getServices().size());

                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {

                                                    BluetoothGattCharacteristic chars = gatt.getServices().get(0).getCharacteristic(Battery_Level_UUID);
                                                    Log.i("Beacons", "charsstringval: " + chars.getValue().length);

                                                }
                                            });

                                }
                            }
                        });
        }
    });
}

I have to scan more than one beacon, and when it is scanning a device and it only getssometimes a service.
The problem is when the code wants to read the characteristic the service handle is again null. I'm desperate and I hope you can help me.

Body:
In short, because your runnable runs on a different thread, the value of gatt.getServices() may have changed.

I would simply retrieve the updated services list, check the size, and then only make the call if there is at least one service.

if (gatt.getServices().size() > 0) {
    BluetoothGattCharacteristic chars = gatt.getServices().get(0).getCharacteristic(Battery_Level_UUID);
    Log.i("Beacons", "charsstringval: " + chars.getValue().length);
}


问:
PHP Curl: Could not verify the provided CSRF token because your session was not found
I am trying to get an Access Token on The Taboola Backstage API according to this documentation.

Backstage API - Authentication and General API Usage.pdf

My Sample Code looks like this:

```<code>$ckfile = tempnam ("/tmp", "CURLCOOKIE");

$post = array(
    "client_id"           => "secret"
  , "client_secret"       => "secret"
  , "grant_type"          => "client_credentials"
);

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_COOKIEJAR,  $ckfile );
    curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile );
    curl_setopt($ch, CURLOPT_COOKIESESSION, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    curl_setopt($ch, CURLOPT_USERAGENT, "App Client" );
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60 );
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
          'Content-Type: application/x-www-form-urlencoded'
    ));

    curl_setopt($ch, CURLOPT_URL,"https://backstage.taboola.com/backstage/oauth/token/");
    curl_setopt($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 0);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

    $result=curl_exec ($ch);

    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($result, 0, $header_size);
    $body = substr($result, $header_size);

    var_dump($header,$body);
</code>```

If I run the code I get the error message. Could not verify the provided CSRF token because your session was not found. What iam missing, i send it with POST to the right endpoint. Have someone please a tip for me?

答:
It looks like their documentation may be slightly off.  I was able to get a proper API response by posting to /backstage/oauth/token (no trailing /).  With the trailing slash it tries to pass you through to a different non-API URL.

Also, it's necessary to pass the POST array through http_build_query() so that cURL doesn't do a multipart form post from the supplied array.  Since it's an API, there's no need to do anything with cookies.  I removed a few other unnecessary options as well.

Here is some code to get you started that worked for me:

```<code>$post = array(
    "client_id"           => "secret",
    "client_secret"       => "secret",
    "grant_type"          => "client_credentials",
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_COOKIESESSION, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "App Client" );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60 );
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/x-www-form-urlencoded',
      'Accept: application/json',
));

curl_setopt($ch, CURLOPT_URL,"https://backstage.taboola.com/backstage/oauth/token");
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_AUTOREFERER, 0);

$result=curl_exec ($ch);

$info = curl_getinfo($ch);
$response = json_decode($result, true);

if ($info['http_code'] == 200) {
    // okay
    $access_token = $response['access_token'];
    var_dump($response);
} else {
    // error
    echo $response['error'] . ': ' . $response['error_description'];
}
</code>```

Body:
I am trying to get an Access Token on The Taboola Backstage API according to this documentation.

Backstage API - Authentication and General API Usage.pdf

My Sample Code looks like this:

$ckfile = tempnam ("/tmp", "CURLCOOKIE");

$post = array(
    "client_id"           => "secret"
  , "client_secret"       => "secret"
  , "grant_type"          => "client_credentials"
);

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_COOKIEJAR,  $ckfile );
    curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile );
    curl_setopt($ch, CURLOPT_COOKIESESSION, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    curl_setopt($ch, CURLOPT_USERAGENT, "App Client" );
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60 );
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
          'Content-Type: application/x-www-form-urlencoded'
    ));

    curl_setopt($ch, CURLOPT_URL,"https://backstage.taboola.com/backstage/oauth/token/");
    curl_setopt($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 0);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

    $result=curl_exec ($ch);

    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($result, 0, $header_size);
    $body = substr($result, $header_size);

    var_dump($header,$body);

If I run the code I get the error message. Could not verify the provided CSRF token because your session was not found. What iam missing, i send it with POST to the right endpoint. Have someone please a tip for me?

Body:
It looks like their documentation may be slightly off.  I was able to get a proper API response by posting to /backstage/oauth/token (no trailing /).  With the trailing slash it tries to pass you through to a different non-API URL.

Also, it's necessary to pass the POST array through http_build_query() so that cURL doesn't do a multipart form post from the supplied array.  Since it's an API, there's no need to do anything with cookies.  I removed a few other unnecessary options as well.

Here is some code to get you started that worked for me:

$post = array(
    "client_id"           => "secret",
    "client_secret"       => "secret",
    "grant_type"          => "client_credentials",
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_COOKIESESSION, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "App Client" );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60 );
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/x-www-form-urlencoded',
      'Accept: application/json',
));

curl_setopt($ch, CURLOPT_URL,"https://backstage.taboola.com/backstage/oauth/token");
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_AUTOREFERER, 0);

$result=curl_exec ($ch);

$info = curl_getinfo($ch);
$response = json_decode($result, true);

if ($info['http_code'] == 200) {
    // okay
    $access_token = $response['access_token'];
    var_dump($response);
} else {
    // error
    echo $response['error'] . ': ' . $response['error_description'];
}


问:
Image won't be sent in Email with this technique
I'm looking to make my email "parameter-able" so it's easier to work with format and do something that looks professional.

I have this folder :

This is the content of the Message.htm :

```<code><html>
<head></head>
<body style='color:grey; font-size:15px;'>
    <font face='Helvetica, Arial, sans-serif'>

    <div style='position:absolute; height:100px; width:600px; padding:30px;'>
        <img src='logo.png' />
    </div>

    <br />
    <br />

    <div style='background-color: #ece8d4; width:600px; height:200px; padding:30px; margin-top:30px;'>

        <p>Please click the link below to login and get started.</p>
        <p>
            Username: {0}<br>
            Password: {1}<br>
        </p>
        <br />
        <p>Now get lost... cause it's just a test</p>
    </div>
    </font>
</body>
</html>
</code>```

Then in my controller, simply send it using this c# :

```<code> string body;
 using (var sr = new StreamReader(Server.MapPath("\\Email\\Message.htm") ))
 {
     body = sr.ReadToEnd();
 }

 string username = "anto";
 string password = "RandomNumber";

 string messageBody = string.Format(body, username, password);

 EnvoieCourriel("pelletier_antoine@hotmail.com", messageBody, restOfTheParams);
</code>```

Emial is sent correctly. The problem ?  is never showing. I tried a LOT of weird codes. Not been close to success yet...

EDIT :

I want the Image to be sent INSIDE the email, as inline content.

答:
Change the HTML to have a full path in the img tag:

```<code>      <html>
 <head></head>
 <body style='color:grey; font-size:15px;'>
     <font face='Helvetica, Arial, sans-serif'>

     <div style='position:absolute; height:100px; width:600px; padding:30px;'>
         <img src='http://somepath.com/images/logo.png' />
     </div>

     <br />
     <br />

     <div style='background-color: #ece8d4; width:600px; height:200px; padding:30px; margin-top:30px;'>

         <p>Please click the link below to login and get started.</p>
         <p>
             Username: {0}<br>
             Password: {1}<br>
         </p>
         <br />
         <p>Now get lost... cause it's just a test</p>
     </div>
     </font>
 </body>
 </html>
</code>```

Otherwise the receiver will never see that image.

Body:
I'm looking to make my email "parameter-able" so it's easier to work with format and do something that looks professional.

I have this folder :

This is the content of the Message.htm :

Please click the link below to login and get started.

            Username: {0}

            Password: {1}

Now get lost... cause it's just a test

Then in my controller, simply send it using this c# :

 string body;
 using (var sr = new StreamReader(Server.MapPath("\\Email\\Message.htm") ))
 {
     body = sr.ReadToEnd();
 }

 string username = "anto";
 string password = "RandomNumber";

 string messageBody = string.Format(body, username, password);

 EnvoieCourriel("pelletier_antoine@hotmail.com", messageBody, restOfTheParams);

Emial is sent correctly. The problem ?  is never showing. I tried a LOT of weird codes. Not been close to success yet...

EDIT :

I want the Image to be sent INSIDE the email, as inline content.

Body:
Change the HTML to have a full path in the img tag:

      <html>
 <head></head>
 <body style='color:grey; font-size:15px;'>
     <font face='Helvetica, Arial, sans-serif'>

     <div style='position:absolute; height:100px; width:600px; padding:30px;'>
         <img src='http://somepath.com/images/logo.png' />
     </div>

     <br />
     <br />

     <div style='background-color: #ece8d4; width:600px; height:200px; padding:30px; margin-top:30px;'>

         <p>Please click the link below to login and get started.</p>
         <p>
             Username: {0}<br>
             Password: {1}<br>
         </p>
         <br />
         <p>Now get lost... cause it's just a test</p>
     </div>
     </font>
 </body>
 </html>

Otherwise the receiver will never see that image.


问:
Output SQL messages to a Log File
I have an SQL script than runs a couple of DBBC commands. Is there a way to send the messages generated from executing these commands to a simple log file e.g "C:\log.txt"?

The messages I mean are the ones that appear in the messages box at the bottom of SQL Server 2005 Management Studio after a query has executed.

The reason for needing to do this is because I don't intend on having SQL Server Management Studio open so the messages can't be seen.

I am using SQL Server 2005 if that helps.

答:
For anyone who wasn’t aware SQLCMD is a command line tool for running T-SQL statements and scripts.

so from the command line:

```<code> sqlcmd -i script.sql -S <myserver> -E | tee "C:\log.txt"
</code>```

SQLCMD can be used to run a script or stored procedure on a local/remote SQL Server.

SQLCMD is installed with SSMS and with the database engine. And on the machine with only client or application it can be installed from the Command Line Utilities.

Supported Operating Systems -
Windows 10, Windows 7, Windows 8, Windows 8.1, Windows Server 2008, Windows Server 2008 R2, Windows Server 2008 R2 SP1, Windows Server 2012, Windows Server 2012 R2

ContentLicense: CC BY-SA 2.5

Title: Output SQL messages to a Log File

Body:
For anyone who wasn’t aware SQLCMD is a command line tool for running T-SQL statements and scripts.

so from the command line:

 sqlcmd -i script.sql -S <myserver> -E | tee "C:\log.txt"

SQLCMD can be used to run a script or stored procedure on a local/remote SQL Server.

SQLCMD is installed with SSMS and with the database engine. And on the machine with only client or application it can be installed from the Command Line Utilities.

Supported Operating Systems -
Windows 10, Windows 7, Windows 8, Windows 8.1, Windows Server 2008, Windows Server 2008 R2, Windows Server 2008 R2 SP1, Windows Server 2012, Windows Server 2012 R2


问:
Event Macro Throws an Error "Object Required"
I have this simple Event Macro, which for some reason throws me an

Object Required

error on this line If Not AppDate Is Nothing Then. Any idea what might be causing this?

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim LastRow As Integer
    Dim ThisRow As String
    Dim AppDate As Variant
    Application.EnableEvents = False

    LastRow = Cells(Rows.Count, "C").End(xlUp).Row
    If Target.Column = 3 Then
        ThisRow = Target.Row
        AppDate = Target.Value
        If Not AppDate Is Nothing Then
            (...) Recalculate Date in Column F
        Else
        End If
    End If

    Application.EnableEvents = True
End Sub
</code>```

Any suggestions would be greatly appreciated. Thank you!

答:
Is operator works with objects and not values.

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim x As Variant
    Dim y As New Collection
    Dim z As Object

    x = Target.Value

    If IsEmpty(x) Then
        MsgBox "may be use this."
    End If

    MsgBox TypeName(x)

    If y Is Nothing Then
     MsgBox "Works"
    End If

    If z Is Nothing Then
     MsgBox "Works"
    End If

    If x Is Nothing Then '/This won't work

    End If

End Sub
</code>```

Body:
I have this simple Event Macro, which for some reason throws me an

Object Required

error on this line If Not AppDate Is Nothing Then. Any idea what might be causing this?

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim LastRow As Integer
    Dim ThisRow As String
    Dim AppDate As Variant
    Application.EnableEvents = False

    LastRow = Cells(Rows.Count, "C").End(xlUp).Row
    If Target.Column = 3 Then
        ThisRow = Target.Row
        AppDate = Target.Value
        If Not AppDate Is Nothing Then
            (...) Recalculate Date in Column F
        Else
        End If
    End If

    Application.EnableEvents = True
End Sub

Any suggestions would be greatly appreciated. Thank you!

Body:
Is operator works with objects and not values.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim x As Variant
    Dim y As New Collection
    Dim z As Object

    x = Target.Value

    If IsEmpty(x) Then
        MsgBox "may be use this."
    End If

    MsgBox TypeName(x)

    If y Is Nothing Then
     MsgBox "Works"
    End If

    If z Is Nothing Then
     MsgBox "Works"
    End If

    If x Is Nothing Then '/This won't work

    End If

End Sub


问:
Implementing dropbox-content-hasher in electron node.js app
I have a fully functioning Electron App that uses node.js fs module to look at local files. I need to compare these files to files held on Dropbox. I have the Dropbox module all set up and running and have retrieved the content-hash for each file using the filesGetMetadata method and now I need to create a hash, in the same way, for each of my local files to compare to. I have found this code here: GitHub Repo written by Dropbox themselves, but being a relative newbie to Node.js and Electron I have only ever installed and 'required' node modules. This code just requires a js file (I tried to install the module, just in case!) and despite the js file I am implementing it on existing in the same directory as dropbox-content-hasher.js (like the example in the link) I can only get the error Uncaught Error: Cannot find module './dropbox-content-hasher' in my console. I've played with a few attempts at getting the right path but the error looks like it's still looking in the node_modules folder and I've no idea how to change this. Any help appreciated?!

答:
I worked it out through trial and error... making the assumption from all my other requires that 'it' starts by looking in the node_modules folder, the following ended up working:

```<code>require('../src/js/dropbox-content-hasher.js');
</code>```

Just thought I'd update this for anyone in my situation who doesn't quite know enough before embarking on a project!!

Body:
I worked it out through trial and error... making the assumption from all my other requires that 'it' starts by looking in the node_modules folder, the following ended up working:

require('../src/js/dropbox-content-hasher.js');

Just thought I'd update this for anyone in my situation who doesn't quite know enough before embarking on a project!!


问:
Open a lightbox with long text, and anchor link to section in the text
I have a lightbox with a long text, and I would like to be able to use anchor links to open the lightbox, and this way go to different sections of the text.

Hope someone can help! :)

Something like

```<code><a href="#section1">Link1</a>
<a href="#section2">Link1</a>

<div class="lightbox">
<div id="section1">
Hello world
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="section2">
Hello again world
</div>
</div>
</code>```

答:
If you want to scroll to the anchor, then I would suggest to use fancyBox3, like so:

1 Create links:

```<code><a href="#test" data-fancybox data-anchor="#section1">Link1</a>
<a href="#test" data-fancybox data-anchor="#section2">Link2</a>
</code>```

2 Create your inline content:

```<code><div id="test" style="display:none;width:300px;">
  <div id="section1">
    Hello world
  </div>
  <div style="height: 500px;background: #ccc;"></div>
  <div id="section2">
    Hello again world
  </div>
</div>
</code>```

3 Use callback to find anchor and scroll to the top position:

```<code>$('[data-fancybox]').fancybox({
  afterShow: function(instance, current) {
    var top = $( current.opts.$orig.data('anchor') ).position().top - 24;

    current.$slide.animate({ scrollTop: top }, 200 );
  }
});
</code>```

Demo - https://codepen.io/anon/pen/LOzEOj?editors=1010

Body:
I have a lightbox with a long text, and I would like to be able to use anchor links to open the lightbox, and this way go to different sections of the text.

Hope someone can help! :)

Something like

Link1
Link1

Hello world

Hello again world

Body:
If you want to scroll to the anchor, then I would suggest to use fancyBox3, like so:

1 Create links:

<a href="#test" data-fancybox data-anchor="#section1">Link1</a>
<a href="#test" data-fancybox data-anchor="#section2">Link2</a>

2 Create your inline content:

<div id="test" style="display:none;width:300px;">
  <div id="section1">
    Hello world
  </div>
  <div style="height: 500px;background: #ccc;"></div>
  <div id="section2">
    Hello again world
  </div>
</div>

3 Use callback to find anchor and scroll to the top position:

$('[data-fancybox]').fancybox({
  afterShow: function(instance, current) {
    var top = $( current.opts.$orig.data('anchor') ).position().top - 24;

    current.$slide.animate({ scrollTop: top }, 200 );
  }
});

Demo - https://codepen.io/anon/pen/LOzEOj?editors=1010


问:
Swift Any method argument Protocol Conformance Lost
```<code>protocol A { }
class B: A { }

func f(x: Any) {
    print(x is A)
}
let x: B? = B()
f(x: x) // false
</code>```

I would expect this to be true instead. Is it a bug in Swift?

Following examples work fine and return true:

```<code>// 1
func f(x: Any) {
    print(x is A)
}
let x: B = B() // not optional
f(x: x) // true

// 2
func f(x: Any) {
    print(x is B) // check for B
}
let x: B? = B()
f(x: x) // true
</code>```

答:
If you want to test if your instance conforms to protocol A you can either use :

```<code>func<T>(x: T) {
   print(x is A)
}
</code>```

Or use both functions in conjunction :

```<code>func(x: Any) {
   print(x is A)
}

func(x: Optional<Any>) {
   print(x is A)
}
</code>```

Body:
protocol A { }
class B: A { }

func f(x: Any) {
    print(x is A)
}
let x: B? = B()
f(x: x) // false

I would expect this to be true instead. Is it a bug in Swift?

Following examples work fine and return true:

// 1
func f(x: Any) {
    print(x is A)
}
let x: B = B() // not optional
f(x: x) // true

// 2
func f(x: Any) {
    print(x is B) // check for B
}
let x: B? = B()
f(x: x) // true

Body:
If you want to test if your instance conforms to protocol A you can either use :

func<T>(x: T) {
   print(x is A)
}

Or use both functions in conjunction :

func(x: Any) {
   print(x is A)
}

func(x: Optional<Any>) {
   print(x is A)
}


问:
Get dataset value from input tag upon click and display as HTML
I would like to get the value from the data-price dataset in the radio button after the user has clicked a different option and display it below in the label tag.  I am doing something wrong.  Any help would be very much appreciated.

Here is my code:

(function (){
    var radios_price = document.getElementById('lbl-011');
    console.log(radios_price.dataset.price);
    for(var i = 0; i < radios_price.length; i++){
        radios_price[i].onclick = function(){
            document.getElementById('priceLabel').innerText = this.value;
        }
    }
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="lbl-011" class="click_radio checkbox123" data-name="One Gel Pen with One Blue Light" name="product_quantity" data-val="2264" data-price="29" data-qty="1" value="1" type="radio">

<input id="lbl-011" class="click_radio" data-name="Two Gel Pens and One Blue Light" name="product_quantity" data-val="2263" data-price="39" data-qty="2" value="2" type="radio" checked="checked">

<input id="lbl-011" class="click_radio" data-name="Four Gel Pens and One Blue Light with Bonus Mouth Tray" name="product_quantity" data-val="2259" data-qty="4" data-price="49" value="4" type="radio">

<p>Price (data-price):<label id="priceLabel"> $39</label></code>```

答:
As pointed out, it's important not to assign the same ID to multiple elements. That is what classes are used for.

This is also a good case for taking advantage of event delegation. If you wrap all your input elements in a container you can create an event listener there and respond to whichever radio button was clicked. Doing this you also want to check and ensure that it was actually a radio button that was clicked, and not some other empty space in the parent element.

(function (){
    var inputs = document.getElementById('inputCollection');
    inputs.addEventListener('click', function(e){
      console.log('Collection Clicked');
      if(e.target instanceof HTMLInputElement) {
        // e.target will be the specific input button clicked
        document.getElementById('priceLabel').innerHTML = ' $' +  e.target.dataset.price;
      }
    })
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="inputCollection">
  <input id="lbl-011" class="click_radio checkbox123" data-name="One Gel Pen with One Blue Light" name="product_quantity" data-val="2264" data-price="29" data-qty="1" value="1" type="radio">

  <input id="lbl-012" class="click_radio" data-name="Two Gel Pens and One Blue Light" name="product_quantity" data-val="2263" data-price="39" data-qty="2" value="2" type="radio" checked="checked">

  <input id="lbl-013" class="click_radio" data-name="Four Gel Pens and One Blue Light with Bonus Mouth Tray" name="product_quantity" data-val="2259" data-qty="4" data-price="49" value="4" type="radio">
</div>

<p>Price (data-price):<label id="priceLabel"> $39</label></code>```

Body:
I would like to get the value from the data-price dataset in the radio button after the user has clicked a different option and display it below in the label tag.  I am doing something wrong.  Any help would be very much appreciated.

Here is my code:

(function (){
    var radios_price = document.getElementById('lbl-011');
    console.log(radios_price.dataset.price);
    for(var i = 0; i < radios_price.length; i++){
        radios_price[i].onclick = function(){
            document.getElementById('priceLabel').innerText = this.value;
        }
    }
})();

<input id="lbl-011" class="click_radio checkbox123" data-name="One Gel Pen with One Blue Light" name="product_quantity" data-val="2264" data-price="29" data-qty="1" value="1" type="radio">

<input id="lbl-011" class="click_radio" data-name="Two Gel Pens and One Blue Light" name="product_quantity" data-val="2263" data-price="39" data-qty="2" value="2" type="radio" checked="checked">

<input id="lbl-011" class="click_radio" data-name="Four Gel Pens and One Blue Light with Bonus Mouth Tray" name="product_quantity" data-val="2259" data-qty="4" data-price="49" value="4" type="radio">

Price (data-price): $39

Body:
As pointed out, it's important not to assign the same ID to multiple elements. That is what classes are used for.

This is also a good case for taking advantage of event delegation. If you wrap all your input elements in a container you can create an event listener there and respond to whichever radio button was clicked. Doing this you also want to check and ensure that it was actually a radio button that was clicked, and not some other empty space in the parent element.

(function (){
    var inputs = document.getElementById('inputCollection');
    inputs.addEventListener('click', function(e){
      console.log('Collection Clicked');
      if(e.target instanceof HTMLInputElement) {
        // e.target will be the specific input button clicked
        document.getElementById('priceLabel').innerHTML = ' $' +  e.target.dataset.price;
      }
    })
})();

<div id="inputCollection">
  <input id="lbl-011" class="click_radio checkbox123" data-name="One Gel Pen with One Blue Light" name="product_quantity" data-val="2264" data-price="29" data-qty="1" value="1" type="radio">

  <input id="lbl-012" class="click_radio" data-name="Two Gel Pens and One Blue Light" name="product_quantity" data-val="2263" data-price="39" data-qty="2" value="2" type="radio" checked="checked">

  <input id="lbl-013" class="click_radio" data-name="Four Gel Pens and One Blue Light with Bonus Mouth Tray" name="product_quantity" data-val="2259" data-qty="4" data-price="49" value="4" type="radio">
</div>

<p>Price (data-price):<label id="priceLabel"> $39</label>


答:
Just change the variables in your .env file to prevent these messages from being sent with the response.

<s>APP_ENV=production</s>

```<code>APP_DEBUG=false
</code>```

Edit: just setting APP_DEBUG to false is enough.

Update:
If you're using dingo api package, then beside setting APP_DEBUG to false you need to edit the config file.

If you haven't already done yet, publish dingo config file

```<code>php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"
</code>```

Then, open config/api.php and edit the errorFormat value to whatever message you want.

Replace :message with a generic message

Title: Laravel 5.5 - Only log 500 error, never send error details via api?

Body:
I made the below controller to demonstrate the issue of handling 500 errors I am having with the api. I want to be able to detect when a 500 error will be thrown so it never makes it to the client (as it is too much details to share with the client and they should only be logged by Laravel).

The methodgetUser() returns a 500 error intentionally due to the typo firsgt()

class TestController extends Controller {
  public function getUser() {
    $data = User::firsgt(); //returns 500 error
    return $data;
  }
}

This is what the client sees:

How can we return an error message like 'Error occurred' instead of the too much details for client 'Call to undefined method App\User::firsgt()'?

Note: I don't want to handle it one by one for each controller method, but instead capture any 500 before it is returned to client, and return the custom 500 generic message 'Error occurred'

Body:
Just change the variables in your .env file to prevent these messages from being sent with the response.

<s>APP_ENV=production</s>

APP_DEBUG=false

Edit: just setting APP_DEBUG to false is enough.

Update:
If you're using dingo api package, then beside setting APP_DEBUG to false you need to edit the config file.

If you haven't already done yet, publish dingo config file

php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"

Then, open config/api.php and edit the errorFormat value to whatever message you want.

Replace :message with a generic message


问:
PHP 5.2 - How can I solve a parse-syntax error thrown when using MVC beginner tutorial example?
I've got the following code snippet from http://requiremind.com/a-most-simple-php-mvc-beginners-tutorial/, however it throws an error:

Parse error: syntax error, unexpected '[' in /usr/home/domains/xyz.pl/public_html/my-soft/routes.php on line 20 on my hosting which has 5.2.17 PHP version.

I searched stackoverflow for a corresponding topic about 5.2 vs 5.4 array differences, but i coudldn't find anything meaningful so I can solve this particulat error (both tables are named), and final resolution should comply with this fact -> table names ('pages', 'posts') are used in conditional statement below the table intitialization.

Could you please advise me on how to solve this without changing the PHP version?

```<code> <?php
  function call($controller, $action) {
    require_once('controllers/' . $controller . '_controller.php');

    switch($controller) {
      case 'pages':
        $controller = new PagesController();
      break;
      case 'posts':
        // we need the model to query the database later in the controller
        require_once('models/post.php');
        $controller = new PostsController();
      break;
    }

    $controller->{ $action }();
  }

  // we're adding an entry for the new controller and its actions
  $controllers = array('pages' => ['home', 'error'],
                       'posts' => ['index', 'show']);

  if (array_key_exists($controller, $controllers)) {
    if (in_array($action, $controllers[$controller])) {
      call($controller, $action);
    } else {
      call('pages', 'error');
    }
  } else {
    call('pages', 'error');
  }
?>
</code>```

答:
It looks like they're trying to make a multi-dimensional array.

Try changing the code to this:

```<code>$controllers = array('pages' => array('home', 'error'),
                   'posts' => array('index', 'show'));
</code>```

Body:
I've got the following code snippet from http://requiremind.com/a-most-simple-php-mvc-beginners-tutorial/, however it throws an error:

Parse error: syntax error, unexpected '[' in /usr/home/domains/xyz.pl/public_html/my-soft/routes.php on line 20 on my hosting which has 5.2.17 PHP version.

I searched stackoverflow for a corresponding topic about 5.2 vs 5.4 array differences, but i coudldn't find anything meaningful so I can solve this particulat error (both tables are named), and final resolution should comply with this fact -> table names ('pages', 'posts') are used in conditional statement below the table intitialization.

Could you please advise me on how to solve this without changing the PHP version?

 <?php
  function call($controller, $action) {
    require_once('controllers/' . $controller . '_controller.php');

    switch($controller) {
      case 'pages':
        $controller = new PagesController();
      break;
      case 'posts':
        // we need the model to query the database later in the controller
        require_once('models/post.php');
        $controller = new PostsController();
      break;
    }

    $controller->{ $action }();
  }

  // we're adding an entry for the new controller and its actions
  $controllers = array('pages' => ['home', 'error'],
                       'posts' => ['index', 'show']);

  if (array_key_exists($controller, $controllers)) {
    if (in_array($action, $controllers[$controller])) {
      call($controller, $action);
    } else {
      call('pages', 'error');
    }
  } else {
    call('pages', 'error');
  }
?>

Body:
It looks like they're trying to make a multi-dimensional array.

Try changing the code to this:

$controllers = array('pages' => array('home', 'error'),
                   'posts' => array('index', 'show'));


问:
Linux - check if there is an empty line at the end of a file
NOTE: this question used to be worded differently, using “with/out newline” instead of “with/out empty line”

I have two files, one with an empty line and one without:

File: text_without_empty_line

```<code>$root@kali:/home#cat text_without_empty_line
This is a Testfile
This file does not contain an empty line at the end
$root@kali:/home#
</code>```

File: text_with_empty_line

```<code>$root@kali:/home#cat text_with_empty_line
This is a Testfile
This file does contain an empty line at the end

$root@kali:/home#
</code>```

Is there a command or function to check if a file has an empty line at the end?
I already found this solution, but it does not work for me. (EDIT: IGNORE: A solution with preg_match and PHP would be fine as well.)

答:
Just type:

```<code>cat -e nameofyourfile
</code>```

If there is a newline it will end with $ symbol.
If not, it will end with a % symbol.

Body:
NOTE: this question used to be worded differently, using “with/out newline” instead of “with/out empty line”

I have two files, one with an empty line and one without:

File: text_without_empty_line

$root@kali:/home#cat text_without_empty_line
This is a Testfile
This file does not contain an empty line at the end
$root@kali:/home#

File: text_with_empty_line

$root@kali:/home#cat text_with_empty_line
This is a Testfile
This file does contain an empty line at the end

$root@kali:/home#

Is there a command or function to check if a file has an empty line at the end?
I already found this solution, but it does not work for me. (EDIT: IGNORE: A solution with preg_match and PHP would be fine as well.)

Body:
Just type:

cat -e nameofyourfile

If there is a newline it will end with $ symbol.
If not, it will end with a % symbol.


问:
MDI Single Instance C#.. how to achieve that?
I found the following code in codeproject for single instance.

```<code>frmSChild objfrmSChild = frmSChild.GetChildInstance();
objfrmSChild.MdiParent = this;
objfrmSChild.Show();
objfrmSChild.BringToFront();
</code>```

It is working fine. But it only works once.

I open the that frmSChild for 2 or 3 times. it will bring forwards that form.

But if I close that form and open again. there is an error stating cannot detect an exposed ojbect.

How to modify the code to get it done?

答:
http://www.codeproject.com/KB/cs/singleinstanceforms.aspx

Using Generic to create instance

EDIT by drachenstern

```<code>   vvv click here to edit, yeah?
</code>```

Body:
I found the following code in codeproject for single instance.

frmSChild objfrmSChild = frmSChild.GetChildInstance();
objfrmSChild.MdiParent = this;
objfrmSChild.Show();
objfrmSChild.BringToFront();

It is working fine. But it only works once.

I open the that frmSChild for 2 or 3 times. it will bring forwards that form.

But if I close that form and open again. there is an error stating cannot detect an exposed ojbect.

How to modify the code to get it done?

Body:
http://www.codeproject.com/KB/cs/singleinstanceforms.aspx

Using Generic to create instance

EDIT by drachenstern

   vvv click here to edit, yeah?


问:
Code duplication in enums inheriting a common interface
I have several enums which comply to a common interface:

```<code>    interface TableColumns
    {
      String getColumnName();
      int getColumnIndex();
      ColumnType getColumnType();
      boolean isEditable();
      int getColumnWidth();
    }
</code>```

A typical implementation is:

```<code>enum PointsTableColumns implements TrendTableColumns
{
    POINTS_COLUMN("points_column", false, ColumnType.TEXT, 400, 0);

    private String columnName;
    private boolean editable;
    private ColumnType columnType;
    private int columnWidth;
    private int columnIndex;

    private PointsTableColumns (String columnName, boolean editable, ColumnType columnType,
        int columnWidth,
        int columnIndex)
    {
        this.columnName = columnName;
        this.editable = editable;
        this.columnType = columnType;
        this.columnWidth = columnWidth;
        this.columnIndex = columnIndex;
    }

    public boolean isEditable()
    {
        return editable;
    }

    public int getColumnIndex()
    {
        return columnIndex;
    }

    public String getColumnName()
    {
        return columnName;
    }

    public int getColumnWidth()
    {
        return columnWidth;
    }

    public ColumnType getcolumnType()
    {
        return columnType;
    }
}
</code>```

I have several implementaions like this (10+), each having multiple and almost different values. Now, the problem is that I see a lot of code duplication here, as the methods in all of the implementation are identical word by word.  I know that in Java this is virtually impossible as enums can't extend an implementation.
What I need here is a suggestion or a different strategy where this can be done in a cleaner way. Is there already some existing pattern regarding this?

答:
You could use composition instead of inheritance, putting the common code in a base component that becomes an attribute of your enums.
Also this solution introduces a level of indirection, and requires 4 lines of boilerplate code for each new enum class.

Example:

```<code>/*
 * Example of sharing common code between enum classes wityh same 'structure' using
 * an EnumBase component.
 * This is a work-around on the restriction that  enum cannot inherit from other classes
 */
package provajava;

/**
 *
 * The base class wich contains the shared code
 * In this example we want to define  many enums
 * which are composed of a field 'code' and a field 'name'
 */

class EnumBase {
    public EnumBase( int code, String name ) {
        theCode = code;
        theName = name;
    }

    // The attributes  can be  declared final public
    // In this case you do not need getters
    // but you still make sure that they cannot be changed  outside the constructor
    final public int theCode;
    final public String theName;

}

public class TestEnum2 {

    /**
    * A first enum class
    */

    enum BOOLEAN {
        TRUE ( 1, "True "),
        FALSE (2, "False");

        // This is boilerplate code that need to be repeated for each enum
        // Annoying, but is much shorter than shared code, especially if there are many enum values
        final public EnumBase base;
        BOOLEAN (int c, String n) {
            base = new EnumBase(c,n );
        }

    }

    /**
    * A second enum class
    */

    enum NUMBER {
        ONE ( 1, "One"),
        TWO (2, "Two"),
        THREE(3, "Three");

        // This is boilerplate code that need to be repeated for each enum
        // Annoying, but is much shorter than repeating shared code, especially if there are many enum values
        final public EnumBase base;
        NUMBER (int c, String n) {
            base = new EnumBase(c,n );
        }

    }

    public static void main(String args[] ) {

        BOOLEAN b = BOOLEAN.FALSE;
        NUMBER  n = NUMBER.TWO;

        System.out.println( b + "->" + b.base.theCode + "," + b.base.theName  );
        System.out.println( n + "->" + n.base.theCode + "," +  n.base.theName  );

        //  n.base.theCode = 2; // ERROR : cannot assign to a final variable
        // n.base = new EnumBase( 1, "TWELVE");  // ERROR : cannot assign to a final variable

    }

}
</code>```

Body:
I have several enums which comply to a common interface:

    interface TableColumns
    {
      String getColumnName();
      int getColumnIndex();
      ColumnType getColumnType();
      boolean isEditable();
      int getColumnWidth();
    }

A typical implementation is:

enum PointsTableColumns implements TrendTableColumns
{
    POINTS_COLUMN("points_column", false, ColumnType.TEXT, 400, 0);

    private String columnName;
    private boolean editable;
    private ColumnType columnType;
    private int columnWidth;
    private int columnIndex;

    private PointsTableColumns (String columnName, boolean editable, ColumnType columnType,
        int columnWidth,
        int columnIndex)
    {
        this.columnName = columnName;
        this.editable = editable;
        this.columnType = columnType;
        this.columnWidth = columnWidth;
        this.columnIndex = columnIndex;
    }

    public boolean isEditable()
    {
        return editable;
    }

    public int getColumnIndex()
    {
        return columnIndex;
    }

    public String getColumnName()
    {
        return columnName;
    }

    public int getColumnWidth()
    {
        return columnWidth;
    }

    public ColumnType getcolumnType()
    {
        return columnType;
    }
}

I have several implementaions like this (10+), each having multiple and almost different values. Now, the problem is that I see a lot of code duplication here, as the methods in all of the implementation are identical word by word.  I know that in Java this is virtually impossible as enums can't extend an implementation.
What I need here is a suggestion or a different strategy where this can be done in a cleaner way. Is there already some existing pattern regarding this?

Body:
You could use composition instead of inheritance, putting the common code in a base component that becomes an attribute of your enums.
Also this solution introduces a level of indirection, and requires 4 lines of boilerplate code for each new enum class.

Example:

/*
 * Example of sharing common code between enum classes wityh same 'structure' using
 * an EnumBase component.
 * This is a work-around on the restriction that  enum cannot inherit from other classes
 */
package provajava;

/**
 *
 * The base class wich contains the shared code
 * In this example we want to define  many enums
 * which are composed of a field 'code' and a field 'name'
 */

class EnumBase {
    public EnumBase( int code, String name ) {
        theCode = code;
        theName = name;
    }

    // The attributes  can be  declared final public
    // In this case you do not need getters
    // but you still make sure that they cannot be changed  outside the constructor
    final public int theCode;
    final public String theName;

}

public class TestEnum2 {

    /**
    * A first enum class
    */

    enum BOOLEAN {
        TRUE ( 1, "True "),
        FALSE (2, "False");

        // This is boilerplate code that need to be repeated for each enum
        // Annoying, but is much shorter than shared code, especially if there are many enum values
        final public EnumBase base;
        BOOLEAN (int c, String n) {
            base = new EnumBase(c,n );
        }

    }

    /**
    * A second enum class
    */

    enum NUMBER {
        ONE ( 1, "One"),
        TWO (2, "Two"),
        THREE(3, "Three");

        // This is boilerplate code that need to be repeated for each enum
        // Annoying, but is much shorter than repeating shared code, especially if there are many enum values
        final public EnumBase base;
        NUMBER (int c, String n) {
            base = new EnumBase(c,n );
        }

    }

    public static void main(String args[] ) {

        BOOLEAN b = BOOLEAN.FALSE;
        NUMBER  n = NUMBER.TWO;

        System.out.println( b + "->" + b.base.theCode + "," + b.base.theName  );
        System.out.println( n + "->" + n.base.theCode + "," +  n.base.theName  );

        //  n.base.theCode = 2; // ERROR : cannot assign to a final variable
        // n.base = new EnumBase( 1, "TWELVE");  // ERROR : cannot assign to a final variable

    }

}


问:
Primitive data type variables in Java
Are variables of primitive data types in Java considered objects of the wrapper class? I am new to programming so please explain.

答:
Are variables of primitive data types in Java considered objects of the wrapper class?

No. A variable with a primitive type is just a variable with a primitive type. They're completely unrelated to the wrapper classes.

The wrapper classes are used/necessary only when an object is needed, such as in a List or Map (etc.). In that case, we "wrap" a primitive value (like the int 5) in an object (like an Integer) so we can hold that object in the List or Map.

Nothing like that is needed with a variable (or parameter) that has a primitive type.

Title: Primitive data type variables in Java


问:
(Shiny R) How to dynamically generate multiple outputs in the UI?
I would like to render a varying number of plots depending on the data. Can I access the data from the ui to dynamically generate multiple plotOutput calls based on the data?

For example if we have this code:

```<code>shinyApp(
  ui <- fluidPage(
    lapply(WHAT I WANT TO ACCESS, function(patient) {
      fluidRow(column(1, tags$p(patient)),
               column(11, lapply(unique(newDT[pat == patient]$clinic),
                  function(clinic){
                    fluidRow(column(1, tags$p(clinic)),
                             column(10, plotOutput(outputId = paste(patient, clinic), height = "100%")))
                  })))

    })
  ),

  server <- function(input, output) {

    newDT2 <- reactive({
      newDT[dx.x == input$dx]
    })

    #WHAT I WANT TO ACCESS IN UI
    pats <- unique(newDT2()$pat)

    x <-reactive({max(newDT2()$dat) +0.5})
    #observe({print(x())})

    PLOT
    })
      }
    })
    }
  }
  )
</code>```

However, I cannot access the data frame in the ui like I can in the server. Are there any getarounds?

TIA!

答:
You need to do all of your processing of the data in the server and return the output to the ui.

In your example, you would place the lapply call in the server in a renderUI call and put a uiOutput in its place in the ui.

Here's an example from a shiny app of mine.

In the server:

```<code>    # dynamically creates a numeric input for each activity in the activities table
    # for the PAL helper panel
    output$activityList <- renderUI({
        act <- split(as.character(activities[order(activities$Sort, activities$Activity),
                                             "Activity"]),
                     cut2(1:nrow(activities), g=3))
        div(class = "sidebyside",
            fluidRow(column(4,lapply(as.character(act[[1]]),
                           function(x) {numericInput(x,x, value = 0, step=0.5, min = 0)})),
                     column(4,lapply(as.character(act[[2]]),
                           function(x) {numericInput(x,x, value = 0, step=0.5, min = 0)})),
                     column(4,lapply(as.character(act[[3]]),
                           function(x) {numericInput(x,x, value = 0, step=0.5, min = 0)}))
                     )
        )

})
</code>```

And in the ui:

```<code>    uiOutput("activityList")
</code>```

Body:
I would like to render a varying number of plots depending on the data. Can I access the data from the ui to dynamically generate multiple plotOutput calls based on the data?

For example if we have this code:

shinyApp(
  ui <- fluidPage(
    lapply(WHAT I WANT TO ACCESS, function(patient) {
      fluidRow(column(1, tags$p(patient)),
               column(11, lapply(unique(newDT[pat == patient]$clinic),
                  function(clinic){
                    fluidRow(column(1, tags$p(clinic)),
                             column(10, plotOutput(outputId = paste(patient, clinic), height = "100%")))
                  })))

    })
  ),

  server <- function(input, output) {

    newDT2 <- reactive({
      newDT[dx.x == input$dx]
    })

    #WHAT I WANT TO ACCESS IN UI
    pats <- unique(newDT2()$pat)

    x <-reactive({max(newDT2()$dat) +0.5})
    #observe({print(x())})

    PLOT
    })
      }
    })
    }
  }
  )

However, I cannot access the data frame in the ui like I can in the server. Are there any getarounds?

TIA!

Body:
You need to do all of your processing of the data in the server and return the output to the ui.

In your example, you would place the lapply call in the server in a renderUI call and put a uiOutput in its place in the ui.

Here's an example from a shiny app of mine.

In the server:

    # dynamically creates a numeric input for each activity in the activities table
    # for the PAL helper panel
    output$activityList <- renderUI({
        act <- split(as.character(activities[order(activities$Sort, activities$Activity),
                                             "Activity"]),
                     cut2(1:nrow(activities), g=3))
        div(class = "sidebyside",
            fluidRow(column(4,lapply(as.character(act[[1]]),
                           function(x) {numericInput(x,x, value = 0, step=0.5, min = 0)})),
                     column(4,lapply(as.character(act[[2]]),
                           function(x) {numericInput(x,x, value = 0, step=0.5, min = 0)})),
                     column(4,lapply(as.character(act[[3]]),
                           function(x) {numericInput(x,x, value = 0, step=0.5, min = 0)}))
                     )
        )

})

And in the ui:

    uiOutput("activityList")


问:
Use Bundle-NativeCode on Linux does not work
I create a plugin which includes the following folder structure:

src

native/so/libsystemcommand.so

META-INF/MANIFEST.MF

The manifest include the command

```<code>Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Commands Plug-in
Bundle-SymbolicName: de.system.commands;singleton:=true
Bundle-Version: 1.0.0
Bundle-Activator: de.system.commands.CommandsPlugin
Bundle-Localization: plugin
Bundle-NativeCode: native/so/libsystemcommand.so; osname = Linux; processor = x86
Require-Bundle: org.eclipse.core.runtime,
 org.apache.commons.logging
Eclipse-AutoStart: true
Export-Package: de.system.commands,
 de.system.commands.jni,
 de.system.commands.utils
Bundle-ClassPath: .
</code>```

The build.properties looks like

```<code>source.. = src/
output.. = bin/
bin.includes = META-INF/,\
               .,\
               native/
</code>```

In the start method of my Activator class I call

```<code>System.loadLibrary("systemcommand");
</code>```

At runtime the library is not found and a UnsatisfiedLinkError is thrown.

```<code>java.lang.UnsatisfiedLinkError: no libsystemcommand in java.library.path
</code>```

Do I have to set more attributes in the plugin? Do I have to unzip some informations on the target platform?

EDIT:

```<code>java.library.path=/opt/jdk/j2re1.4.2_16/lib/i386/client:/opt/jdk/j2re1.4.2_16/lib/i386:/opt/jdk/j2re1.4.2_16/../lib/i386::/opt/dsa/lib:/opt/dsa/lib
</code>```

答:
In a plugin fragment for linux, I use:

```<code>Bundle-NativeCode: librptlc.so; osname = linux; processor=x86
</code>```

And in the main plugin I use:

```<code>if (OS.equals(Platform.OS_LINUX)) {
    System.loadLibrary("rptlc");
}
</code>```

This should work within one plugin too.

I seem to remember having some problems with libraries in a sub folder in the jar, but I'm not sure why this would be the case. I just stuck to having the libraries in the root of a plugin fragment instead, which works for me.

You could also try getting the file system path of the library (not sure if that's easy) and loading it using:

```<code>libraryPath = "C:\eclipse\bundles\123\librptlc.so";
System.load(libraryPath);
</code>```

OwnerDisplayName: Markus Lausberg

Body:
I create a plugin which includes the following folder structure:

src

native/so/libsystemcommand.so

META-INF/MANIFEST.MF

The manifest include the command

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Commands Plug-in
Bundle-SymbolicName: de.system.commands;singleton:=true
Bundle-Version: 1.0.0
Bundle-Activator: de.system.commands.CommandsPlugin
Bundle-Localization: plugin
Bundle-NativeCode: native/so/libsystemcommand.so; osname = Linux; processor = x86
Require-Bundle: org.eclipse.core.runtime,
 org.apache.commons.logging
Eclipse-AutoStart: true
Export-Package: de.system.commands,
 de.system.commands.jni,
 de.system.commands.utils
Bundle-ClassPath: .

The build.properties looks like

source.. = src/
output.. = bin/
bin.includes = META-INF/,\
               .,\
               native/

In the start method of my Activator class I call

System.loadLibrary("systemcommand");

At runtime the library is not found and a UnsatisfiedLinkError is thrown.

java.lang.UnsatisfiedLinkError: no libsystemcommand in java.library.path

Do I have to set more attributes in the plugin? Do I have to unzip some informations on the target platform?

EDIT:

java.library.path=/opt/jdk/j2re1.4.2_16/lib/i386/client:/opt/jdk/j2re1.4.2_16/lib/i386:/opt/jdk/j2re1.4.2_16/../lib/i386::/opt/dsa/lib:/opt/dsa/lib

LastEditorDisplayName: Markus Lausberg

Body:
In a plugin fragment for linux, I use:

Bundle-NativeCode: librptlc.so; osname = linux; processor=x86

And in the main plugin I use:

if (OS.equals(Platform.OS_LINUX)) {
    System.loadLibrary("rptlc");
}

This should work within one plugin too.

I seem to remember having some problems with libraries in a sub folder in the jar, but I'm not sure why this would be the case. I just stuck to having the libraries in the root of a plugin fragment instead, which works for me.

You could also try getting the file system path of the library (not sure if that's easy) and loading it using:

libraryPath = "C:\eclipse\bundles\123\librptlc.so";
System.load(libraryPath);

OwnerDisplayName: Mike Houston


问:
Debugging 403's?
whats the best way to investigate why a server is returning a 403 for a http web request?

Can an iis server be configured to provide a more detailed internal log for 403's?

答: A nice way to start is to analyze returned headers (using curl -vvv, or inspecting the request using your favorite web browser development tool).

Title: Debugging 403's?


答:
You can collect all input type with help of classname, call in for loop to access each element.

(function (){
    var radios_price = document.getElementsByClassName('click_radio');
    for(var i = 0; i < radios_price.length; i++){
        radios_price[i].onclick = function(){
            document.getElementById('priceLabel').innerText = "$"+this.dataset.price;
        }
    }
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="lbl-011" class="click_radio checkbox123" data-name="One Gel Pen with One Blue Light" name="product_quantity" data-val="2264" data-price="29" data-qty="1" value="1" type="radio">

<input id="lbl-011" class="click_radio" data-name="Two Gel Pens and One Blue Light" name="product_quantity" data-val="2263" data-price="39" data-qty="2" value="2" type="radio" checked="checked">

<input id="lbl-011" class="click_radio" data-name="Four Gel Pens and One Blue Light with Bonus Mouth Tray" name="product_quantity" data-val="2259" data-qty="4" data-price="49" value="4" type="radio">

<p>Price (data-price):<label id="priceLabel">$39</label></code>```

Title: Get dataset value from input tag upon click and display as HTML

Body:
You can collect all input type with help of classname, call in for loop to access each element.

(function (){
    var radios_price = document.getElementsByClassName('click_radio');
    for(var i = 0; i < radios_price.length; i++){
        radios_price[i].onclick = function(){
            document.getElementById('priceLabel').innerText = "$"+this.dataset.price;
        }
    }
})();

<input id="lbl-011" class="click_radio checkbox123" data-name="One Gel Pen with One Blue Light" name="product_quantity" data-val="2264" data-price="29" data-qty="1" value="1" type="radio">

<input id="lbl-011" class="click_radio" data-name="Two Gel Pens and One Blue Light" name="product_quantity" data-val="2263" data-price="39" data-qty="2" value="2" type="radio" checked="checked">

<input id="lbl-011" class="click_radio" data-name="Four Gel Pens and One Blue Light with Bonus Mouth Tray" name="product_quantity" data-val="2259" data-qty="4" data-price="49" value="4" type="radio">

<p>Price (data-price):<label id="priceLabel">$39</label>


问:
How I can realize an animation of text typing from right to left and from bottom to top?
I want to make a text animation like typing from right to left and from bottom to top.

How can I realize animated text typing from right to left and from bottom to top.

On the top I want typing from right to left and on right from bottom to top... so it looks like typing around the screen...

here my code:

blau();

function blau(){

var elmnt = document.getElementById("myDIV");

 var divheight = elmnt.offsetHeight;
 var divwidth = elmnt.offsetWidth;
 var dh = Math.floor((divheight / 15));
 var dw = Math.floor((divwidth / 16));
 var links = dh;
 var unten = dh + dw;
 var rechts = unten + dh;
 var oben = rechts + dw;
 var ges = ((dh * 2) + (dw * 2));
 var i ;
 var a ;
 var b ;
 var c ;
 var d ;
 var txta = '';
 var txtb = '';
 var txtc = '';
  var txtd = '';

 for (a = 0; a < dh; a++) {

  txta += "#";

   document.getElementById("left").innerHTML = txta;
   document.getElementById("left").style.visibility = "hidden";
  }
  for (b = 0; b < dw; b++) {
  txtb += "  #";
    document.getElementById("bottom").innerHTML = txtb;
    document.getElementById("bottom").style.visibility = "hidden";
  }
  for (c = 0; c < dh; c++) {
  txtc += "#";
   document.getElementById("right").innerHTML = txtc;
   document.getElementById("right").style.visibility = "hidden";
 }
 for (d = 0; d < dw; d++) {
 txtd += "#  ";
   document.getElementById("top").innerHTML = txtd;
   document.getElementById("top").style.visibility = "hidden";
 }

animateLeft(dh,dw);
}

function animateLeft(dh,dw){

var character_count = $('.animated-text-left').text().length;
$('.animated-text-left').css('animation', 'left 1s steps(' + dh + ') forwards').css('font-family', 'monospace');
$('').appendTo('left');

document.getElementById("left").style.visibility = "visible";

setTimeout(
      function() {
      animateBottom(dh,dw);
      },
      1000);
}
function animateBottom(dh,dw){
var character_count = $('.animated-text-bottom').text().length;
$('.animated-text-bottom').css('animation', 'bottom 1s steps(' + (dw * 3) + ') forwards').css('font-family', 'monospace');
$('').appendTo('bottom');
document.getElementById("bottom").style.visibility = "visible";

setTimeout(
      function() {
      animateRight(dh,dw);
      },
      1000);
}
function animateRight(dh,dw){
var character_count = $('.animated-text-right').text().length;
$('.animated-text-right').css('animation', 'right 1s steps(' + dh + ') forwards').css('font-family', 'monospace').css('float', 'right');
$('').appendTo('right');
document.getElementById("right").style.visibility = "visible";

setTimeout(
      function() {
     animateTop(dh,dw);
      },
      1000);
}
function animateTop(dh,dw){
var character_count = $('.animated-text-top').text().length;
$('.animated-text-top').css('animation', 'top 1s steps(' + (dw * 3) +  ')').css('font-family', 'monospace').css('float', 'right');
$('').appendTo('top');
document.getElementById("top").style.visibility = "visible";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  html, body {
  height:100%;

  margin:0;
  padding: 0;

}
body {

   padding: 0;
   margin:0;
}

.animated-text-left {
 font-family: monospace;
 overflow: hidden;

  word-wrap: break-word;
 white-space: nowrap;

  }

.animated-text-bottom {
  font-family: monospace;
  overflow: hidden;

  word-wrap: break-word;
  white-space: nowrap;

  }

.animated-text-right {
 font-family: monospace;
 overflow: hidden;

 word-wrap: break-word;
 white-space: nowrap;

 }

.animated-text-top {
 font-family: monospace;
 overflow: hidden;

 word-wrap: break-word;
 white-space: nowrap;

 }

#myDIV {
    height: 100%;
    width: 100%;
    overflow:hidden;

    background-color: black;
}

#left {
 color: white;
    height: 100%;
    width: 10px;
    left:0px;
    position: absolute;
    float:left;
    background-color: black;
 white-space: pre-wrap;      /* CSS3 */
   white-space: -moz-pre-wrap; /* Firefox */
   white-space: -pre-wrap;     /* Opera -7 */
   white-space: -o-pre-wrap;   /* Opera 7+ */
   word-wrap: break-word;      /* IE */
}

#middle{
width: 100%;
height: 100%;
    margin-left: 10px;
margin-right: 10px;

margin-bottom: 10px;
    float: left;
    position: relative;
}

#content{
width: 100%;
height: 100%;

margin-top: 10px;
margin-bottom: 10px;

    position: absolute;
}

#top {
    height: 10px;
    width: 100%;
    text-align:right;
    color: white;
    position: absolute;
    top: 10;
    background-color: black;
}

#contenta {
    height: 90%;
    width: 100%;

    color:white;
    position: relative;
    background-color: black;

}

#contentb {
    height: 10%;
    width: 100%;

   position: relative;
    color: white;
    background-color: black;

}

#bottom {
    height: 10px;
    width: 100%;
    color: white;
    position: absolute;
    bottom: 0;
    background-color: black;
}

#right {
 color: white;
    height: 100%;
    width: 10px;
    right:0px;
    float:right;
    position: absolute;
    background-color: black;
  white-space: pre-wrap;      /* CSS3 */
   white-space: -moz-pre-wrap; /* Firefox */
   white-space: -pre-wrap;     /* Opera -7 */
   white-space: -o-pre-wrap;   /* Opera 7+ */
   word-wrap: break-word;      /* IE */
}

#right span{
   width: 10px;
    right:0px;
    bottom: 0;
    position: absolute;

}

@keyframes typing {
 from {
  width: 0;
 }

}

@keyframes left {
  from {
   height: 0;
  }

}

@keyframes bottom {
 from {
  width: 0;
 }

}

@keyframes right {
  from {
   height: 0;
  }

}

@keyframes top {
 from {
  width: 0;
 }

}

.string-highlight{
    color: rgba(253, 149, 90, 0.8);
}
.string-red{
    color: red;
}
.string-at{
    color: rgba(253, 149, 90, 0.8);
}
.string-texta{
    color: white;
}
.string-textb{
    color: red;
}
.string-textc{
    color: green;
}
.string-textd{
    color: blue;
}
.string-dot{
    color: blue;
}
.string-ok{
    color: green;
}
.string-done{
    color: green;
}
.string-connected{
    color: green;
}
.string-klammer{
    color: blue;
}
.string-sysinfo{
    color: green;
}</code>```

<!doctype html>

<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name=description content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Getippter Text mit CSS-Animationen</title>

 weiterer text

console

```

答:
Just add this css to your #top

```<code>right: 0px; direction: ltr;
</code>```

And this to your #right

```<code>bottom: 0px; direction: ltr;
</code>```

Live example:
https://jsfiddle.net/6xqpo0rv/

Body:
I want to make a text animation like typing from right to left and from bottom to top.

How can I realize animated text typing from right to left and from bottom to top.

On the top I want typing from right to left and on right from bottom to top... so it looks like typing around the screen...

here my code:

blau();

function blau(){

var elmnt = document.getElementById("myDIV");

 var divheight = elmnt.offsetHeight;
 var divwidth = elmnt.offsetWidth;
 var dh = Math.floor((divheight / 15));
 var dw = Math.floor((divwidth / 16));
 var links = dh;
 var unten = dh + dw;
 var rechts = unten + dh;
 var oben = rechts + dw;
 var ges = ((dh * 2) + (dw * 2));
 var i ;
 var a ;
 var b ;
 var c ;
 var d ;
 var txta = '';
 var txtb = '';
 var txtc = '';
  var txtd = '';

 for (a = 0; a < dh; a++) {

  txta += "#";

   document.getElementById("left").innerHTML = txta;
   document.getElementById("left").style.visibility = "hidden";
  }
  for (b = 0; b < dw; b++) {
  txtb += "  #";
    document.getElementById("bottom").innerHTML = txtb;
    document.getElementById("bottom").style.visibility = "hidden";
  }
  for (c = 0; c < dh; c++) {
  txtc += "#";
   document.getElementById("right").innerHTML = txtc;
   document.getElementById("right").style.visibility = "hidden";
 }
 for (d = 0; d < dw; d++) {
 txtd += "#  ";
   document.getElementById("top").innerHTML = txtd;
   document.getElementById("top").style.visibility = "hidden";
 }

animateLeft(dh,dw);
}

function animateLeft(dh,dw){

var character_count = $('.animated-text-left').text().length;
$('.animated-text-left').css('animation', 'left 1s steps(' + dh + ') forwards').css('font-family', 'monospace');
$('').appendTo('left');

document.getElementById("left").style.visibility = "visible";

setTimeout(
      function() {
      animateBottom(dh,dw);
      },
      1000);
}
function animateBottom(dh,dw){
var character_count = $('.animated-text-bottom').text().length;
$('.animated-text-bottom').css('animation', 'bottom 1s steps(' + (dw * 3) + ') forwards').css('font-family', 'monospace');
$('').appendTo('bottom');
document.getElementById("bottom").style.visibility = "visible";

setTimeout(
      function() {
      animateRight(dh,dw);
      },
      1000);
}
function animateRight(dh,dw){
var character_count = $('.animated-text-right').text().length;
$('.animated-text-right').css('animation', 'right 1s steps(' + dh + ') forwards').css('font-family', 'monospace').css('float', 'right');
$('').appendTo('right');
document.getElementById("right").style.visibility = "visible";

setTimeout(
      function() {
     animateTop(dh,dw);
      },
      1000);
}
function animateTop(dh,dw){
var character_count = $('.animated-text-top').text().length;
$('.animated-text-top').css('animation', 'top 1s steps(' + (dw * 3) +  ')').css('font-family', 'monospace').css('float', 'right');
$('').appendTo('top');
document.getElementById("top").style.visibility = "visible";
}

  html, body {
  height:100%;

  margin:0;
  padding: 0;

}
body {

   padding: 0;
   margin:0;
}

.animated-text-left {
 font-family: monospace;
 overflow: hidden;

  word-wrap: break-word;
 white-space: nowrap;

  }

.animated-text-bottom {
  font-family: monospace;
  overflow: hidden;

  word-wrap: break-word;
  white-space: nowrap;

  }

.animated-text-right {
 font-family: monospace;
 overflow: hidden;

 word-wrap: break-word;
 white-space: nowrap;

 }

.animated-text-top {
 font-family: monospace;
 overflow: hidden;

 word-wrap: break-word;
 white-space: nowrap;

 }

#myDIV {
    height: 100%;
    width: 100%;
    overflow:hidden;

    background-color: black;
}

#left {
 color: white;
    height: 100%;
    width: 10px;
    left:0px;
    position: absolute;
    float:left;
    background-color: black;
 white-space: pre-wrap;      /* CSS3 */
   white-space: -moz-pre-wrap; /* Firefox */
   white-space: -pre-wrap;     /* Opera -7 */
   white-space: -o-pre-wrap;   /* Opera 7+ */
   word-wrap: break-word;      /* IE */
}

#middle{
width: 100%;
height: 100%;
    margin-left: 10px;
margin-right: 10px;

margin-bottom: 10px;
    float: left;
    position: relative;
}

#content{
width: 100%;
height: 100%;

margin-top: 10px;
margin-bottom: 10px;

    position: absolute;
}

#top {
    height: 10px;
    width: 100%;
    text-align:right;
    color: white;
    position: absolute;
    top: 10;
    background-color: black;
}

#contenta {
    height: 90%;
    width: 100%;

    color:white;
    position: relative;
    background-color: black;

}

#contentb {
    height: 10%;
    width: 100%;

   position: relative;
    color: white;
    background-color: black;

}

#bottom {
    height: 10px;
    width: 100%;
    color: white;
    position: absolute;
    bottom: 0;
    background-color: black;
}

#right {
 color: white;
    height: 100%;
    width: 10px;
    right:0px;
    float:right;
    position: absolute;
    background-color: black;
  white-space: pre-wrap;      /* CSS3 */
   white-space: -moz-pre-wrap; /* Firefox */
   white-space: -pre-wrap;     /* Opera -7 */
   white-space: -o-pre-wrap;   /* Opera 7+ */
   word-wrap: break-word;      /* IE */
}

#right span{
   width: 10px;
    right:0px;
    bottom: 0;
    position: absolute;

}

@keyframes typing {
 from {
  width: 0;
 }

}

@keyframes left {
  from {
   height: 0;
  }

}

@keyframes bottom {
 from {
  width: 0;
 }

}

@keyframes right {
  from {
   height: 0;
  }

}

@keyframes top {
 from {
  width: 0;
 }

}

.string-highlight{
    color: rgba(253, 149, 90, 0.8);
}
.string-red{
    color: red;
}
.string-at{
    color: rgba(253, 149, 90, 0.8);
}
.string-texta{
    color: white;
}
.string-textb{
    color: red;
}
.string-textc{
    color: green;
}
.string-textd{
    color: blue;
}
.string-dot{
    color: blue;
}
.string-ok{
    color: green;
}
.string-done{
    color: green;
}
.string-connected{
    color: green;
}
.string-klammer{
    color: blue;
}
.string-sysinfo{
    color: green;
}

<!doctype html>

<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name=description content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Getippter Text mit CSS-Animationen</title>

 weiterer text

console

Body:
Just add this css to your #top

right: 0px; direction: ltr;

And this to your #right

bottom: 0px; direction: ltr;

Live example:
https://jsfiddle.net/6xqpo0rv/


问:
Parser in C#. How to populate a class from strings
I'm trying to do a simple parser that receive an array and return a class with populated members.

I have the following class implementing the following interface.

```<code>    public class ReturnedObject : IReturnedObject
{
        public string Source { get; set; }
        public string Destination { get; set; }
}

    public interface IReturnedObject
{
        string Source { get; set; }
        string Destination { get; set; }
}
</code>```

If for example I receive the following line:

command -source value1 -destination value2

I would like to be able to associate the source value and the destination value.

The main method look like this:

```<code>        private static IReturnedObject Parse<T>(string[] userArgs, ICommandesUtils commandUtils) where T : IReturnedObject, new()
    {
    //userArgs contains the folling array
    //command
    //-source
    //value1
    //-destination
    //value2

    //some work...

    IReturnedObject returnedObject = new T();

    returnedObject.Source = userArgs[2];
    returnedObject.Destination = userArgs[4];
    }
</code>```

What i'm looking for is a way to replace the two following lines :

```<code>returnedObject.Source = userArgs[2];
returnedObject.Destination = userArgs[4];
</code>```

I want to do something like:

For each member of the class returnedObject

Look the name of the member (for example, "Destination")

Find in the userArgs the good value to assiociate (the one after "-destination" in this example)

Associate the value.

Is that possible ?
Thank you by advance :)

答:
You can use Reflection for this.

First of all, you should store the arguments in a better way. Use a Dictionary.

Something like:

```<code>Dictionary<string, string> args; // Key = Property Name -- Value = Property Value
</code>```

Then, for your logic, do:

```<code>PropertyInfo[] props = T.GetType().GetProperties();

foreach(var prop in props)
{
    string propName = prop.GetMethod.Name;

    if (args.ContainsKey(propName))
    {
        prop.SetValue(returnedObject, args[propName]);
    }
}
</code>```

The values and logic can be edited to support any value types.

Body:
I'm trying to do a simple parser that receive an array and return a class with populated members.

I have the following class implementing the following interface.

    public class ReturnedObject : IReturnedObject
{
        public string Source { get; set; }
        public string Destination { get; set; }
}

    public interface IReturnedObject
{
        string Source { get; set; }
        string Destination { get; set; }
}

If for example I receive the following line:

command -source value1 -destination value2

I would like to be able to associate the source value and the destination value.

The main method look like this:

        private static IReturnedObject Parse<T>(string[] userArgs, ICommandesUtils commandUtils) where T : IReturnedObject, new()
    {
    //userArgs contains the folling array
    //command
    //-source
    //value1
    //-destination
    //value2

    //some work...

    IReturnedObject returnedObject = new T();

    returnedObject.Source = userArgs[2];
    returnedObject.Destination = userArgs[4];
    }

What i'm looking for is a way to replace the two following lines :

returnedObject.Source = userArgs[2];
returnedObject.Destination = userArgs[4];

I want to do something like:

For each member of the class returnedObject

Look the name of the member (for example, "Destination")

Find in the userArgs the good value to assiociate (the one after "-destination" in this example)

Associate the value.

Is that possible ?
Thank you by advance :)

Body:
You can use Reflection for this.

First of all, you should store the arguments in a better way. Use a Dictionary.

Something like:

Dictionary<string, string> args; // Key = Property Name -- Value = Property Value

Then, for your logic, do:

PropertyInfo[] props = T.GetType().GetProperties();

foreach(var prop in props)
{
    string propName = prop.GetMethod.Name;

    if (args.ContainsKey(propName))
    {
        prop.SetValue(returnedObject, args[propName]);
    }
}

The values and logic can be edited to support any value types.


问:
Inserting null to an Integer column using JDBC
I have an sql column PROTOCOL, it is nullable and has a constraint on the table

```<code>PROTOCOL IN (1, 2, 3)
</code>```

Also since it is nullable, I want to set and get null values into table

But I cannot do setInt and getInt as null. How to set a null to column as null using JDBC

```<code>setInt(4,null);
</code>```

答:
In addition to Smit's answer:

If you want to insert an Integer-object into a database that may be null, you can use

```<code>statement.setObject(4, yourObject, java.sql.Types.INTEGER);
</code>```

instead of

```<code>if (yourObject == null) {
    statement.setNull(4, java.sql.Types.INTEGER);
else {
    statement.setInt(4, yourObject);
}
</code>```

Body:
I have an sql column PROTOCOL, it is nullable and has a constraint on the table

PROTOCOL IN (1, 2, 3)

Also since it is nullable, I want to set and get null values into table

But I cannot do setInt and getInt as null. How to set a null to column as null using JDBC

setInt(4,null);

Body:
In addition to Smit's answer:

If you want to insert an Integer-object into a database that may be null, you can use

statement.setObject(4, yourObject, java.sql.Types.INTEGER);

instead of

if (yourObject == null) {
    statement.setNull(4, java.sql.Types.INTEGER);
else {
    statement.setInt(4, yourObject);
}


问:
Erase all cookies in NSURLSession iOS
How can I erase all cookies from the NSHTTPCookieStorage.sharedHTTPCookieStorage? The only methods I am aware of delete a single specified cookie, however, the cookies are handled behind the scenes by NSURLSession. (Programming in Swift)</p>

答:
This achieves the same result as the other answers but with one line of code:</p>

```<code>HTTPCookieStorage.shared.cookies?.forEach(HTTPCookieStorage.shared.deleteCookie)
</code>```

Title: Erase all cookies in NSURLSession iOS

Body:
This achieves the same result as the other answers but with one line of code:

HTTPCookieStorage.shared.cookies?.forEach(HTTPCookieStorage.shared.deleteCookie)