问:
editing a JSON file
First of all yes I did check other options, questions and answers but sadly those didn't work for me.

So I'm currently working on a small project including a shopping cart system.
The shopping cart system is created by a PHP session and everything works fine. Products can be added, rows can be deleted and the cart can be cleared completely.

Now I would like to add some functions like counting the items in the cart, calculating the total price and VAT prices. Since the session is stored as a JSON object I'm able to use angularjs and $http.get() to read the JSON cart object and redefine the data so it's usable in an ng-repeat for the view.

So when the visitor clicks on the "add to cart" button the following code is creating the session:

```<code>session_start();

$product_id = $_REQUEST['product_id'];
$product_name = $_REQUEST['product_name'];
$product_price = round($_REQUEST['product_price'], 2);
$product_size = $_REQUEST['product_size'];
$product_quantity = $_REQUEST['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);
// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price,
    "total_items" => 0
);

/*
 * check if the 'cart' session array was created
 * if it is NOT, create the 'cart' session array
 */
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
}

// check if the item is in the array, if it is, do not add
if(array_key_exists($product_id and $product_size, $_SESSION['cart'])){
    // redirect to product list and tell the user it was added to cart
    echo "<script> alert('Dit product staat al in de winkelwagen')</script>])";
}

// else, add the item to the array
else{
    $_SESSION['cart']["cartItems"][$product_id]=$cartProduct;
}
</code>```

So my first attempt was to add the following to the section "add the item to the array"

```<code>    $arr = json_decode($_SESSION['cart']['cartItems'][$product_id], true);
    $total_items['total_items'] = count($_SESSION['cart']);
    array_push($arr['cartItems'], $total_items);
</code>```

But sadly this didn't work. I also tried adding this to the getCart section.

```<code>session_start();

$json = json_encode($_SESSION['cart']["cartItems"]);
echo($json);
</code>```

Sadly also without any result.

So my question is how am I able to add the total_items calculation to the array. And how am I able to calculate the total price, VAT prices etc?

PS: the JSON outcome of one product:

```<code>{"16":{"id":"16","name":"TestDatumProduct","price":1000,"size":"M","quantity":"4","total_product_price":4000,"total_items":0}}
</code>```

UPDATE

So an update to combine the progress of the last few days:

So currently my code is based on the answer of @devionNL since i like the action method and the answer of @FranciscoRodríguez was barely an answer since he only adviced me about the counting method, (didn't work)

So using the action examples from @devionNL i've made some small changes and came up with the following code.

```<code><?php
session_start();
$cartItemID = $_REQUEST['cartItem_id'];
$product_id = $_REQUEST['product_id'];
$product_name = $_REQUEST['product_name'];
$product_price = round($_REQUEST['product_price'], 2);
$product_size = $_REQUEST['product_size'];
$product_quantity = $_REQUEST['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);

// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price
);

// If the session is empty create an empty array
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
}

// Add to cart
if ($_REQUEST['action'] == 'addToCart')
{
    if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
    {
        $_SESSION['cart']['cartItems']['totalItems']++;
    }
    else
    {
        $_SESSION['cart']['cartItems']['totalItems']++;
        array_push($_SESSION['cart']['cartItems'], $cartProduct );
    }
}

// RemoveRow
else if ($_REQUEST['action'] == 'removeRow') // If you want a delete action
{
    if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
    {
        if ($_SESSION['cart']['cartItems']['totalItems'] > 1)
        {
            foreach ($cartDecode as $key => $cartItem)
            {
                // IF THE TITLE MATCHES THE SIGNAL STRING
                if ($cartItem->{"id"} == $cartItemID)
                {
                    // REMOVE THIS OBJECT
                    unset($cartDecode[$key]);
                }

            }
            $_SESSION['cart']['cartItems']['totalItems']--; // Deduct by 1.
        }
    else
        {
            $_SESSION['cart']['cartItems'] = $cartProduct;
        }
    }

    $_SESSION['cart']['cartItems']['totalPrice'] = array_sum(array_map(function($item) {
        return $item['price'] * $item['totalItems'];
    },
        $_SESSION['cart']['cartItems']));

}
$cart = json_encode($_SESSION['cart']['cartItems']);
echo ($cart);
</code>```

So adding to the cart, and calculating the cartItems is working as expected. But i still can't find the way of removing a row. inside the cart. Next to that i'm still struggling with getting the total price of the cart. The JSON outcome is as following:

```<code>{"totalItems":2,"0":{"id":"7","name":"Bedrukt jurkje van chiffon","price":20.5,"size":"M","quantity":"3","total_product_price":61.5},"1":{"id":"5","name":"Bedrukte Zomerjurk","price":30.5,"size":"M","quantity":"3","total_product_price":91.5}}
</code>```

The full cart in JSON would then be:

```<code>{"cartItems":{"totalItems":2,"0":{"id":"7","name":"Bedrukt jurkje van chiffon","price":20.5,"size":"M","quantity":"3","total_product_price":61.5},"1":{"id":"5","name":"Bedrukte Zomerjurk","price":30.5,"size":"M","quantity":"3","total_product_price":91.5}}}
</code>```

So my questions are?
1. How am i able to delete a single row (ID == "", Then delete)
2. How am i able to calculate the full price of the cart?
3. For placing the order inside the dabatase, how would i be able to select each row? (id, name, etc). I was thinking in the way of using a foreach() statement?

If there are any questions please ask them in the comments.

As always, Thanks in advance!

答:
Ok I believe i make it work at least with my test data. I have put comments in code at every point i believe that requires a change. Also note that totalItems and totalPrice has to be in $_SESSION['cart'] and $_SESSION['cart']["cartItems"] has to maintain only the items array elese the array_map function that you want to make the sum will not work. Hope that helps you a bit.

```<code>session_start();
    $cartItemID = $_REQUEST['cartItem_id'];
    $product_id = intval($_REQUEST['product_id']); //if product_id is integer use intval
    $product_name = $_REQUEST['product_name'];
    $product_price = round(doubleval($_REQUEST['product_price']), 2);//if product_price is double use doubleval will help for the calculations
    $product_size = $_REQUEST['product_size'];
    $product_quantity = intval($_REQUEST['product_quantity']); //if product_quantity is integer use intval will help for the calculations
    $total_product_price = $product_price*$product_quantity;
    round($total_product_price, 2);

    // Add new item to session
    $cartProduct = array(
        "id" => $product_id,
        "name" => $product_name,
        "price" => $product_price,
        "size" => $product_size,
        "quantity" => $product_quantity,
        "total_product_price" => $total_product_price
    );

    // If the session is empty create an empty array
    if(empty($_SESSION['cart']["cartItems"])){
        $_SESSION['cart']["cartItems"] = array();
    }

    // Add to cart
    if ($_REQUEST['action'] == 'addToCart')
    {
        if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
        {
            //$_SESSION['cart']['totalItems']++; //this line can cause problems when removing item out of the cart, when the user adds an item and you increment the total items value, you have to increment the value for the specific product in order to substract the correct number in the removal,
            //you can use 2 approaches depending what you trying to achieve,
            //1. if $_SESSION['cart']['totalItems'] is the items by type then you don't need to increment if item exists , just comment your line
            //2. if $_SESSION['cart']['totalItems'] represents the total number of items by adding the quantity of every product then this has to change use the following which i recommend
            $_SESSION['cart']['cartItems'][$product_id]['quantity']+=$product_quantity;
            $_SESSION['cart']['cartItems'][$product_id]['total_product_price']+=$total_product_price;
        }
        else
        {
            //$_SESSION['cart']['totalItems']++;
            //use this line for 2nd apporach
            $_SESSION['cart']['cartItems'][$product_id] = $cartProduct ; //array_push is wrong here you need a key that is the product id not the next available index, array_push will just give you the next available index, that's why the rest not working

        }
        //use this line for 2nd apporach
        $_SESSION['cart']['totalItems']+=$product_quantity;
    }

    // RemoveRow
    else if ($_REQUEST['action'] == 'removeRow') // If you want a delete action
    {
        if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
        {
            if ($_SESSION['cart']['totalItems'] > 1)
            {
                /*foreach ($cartDecode as $key => $cartItem)
                {
                    // IF THE TITLE MATCHES THE SIGNAL STRING
                    if ($cartItem->{"id"} == $cartItemID)
                    {
                        // REMOVE THIS OBJECT
                        unset($cartDecode[$key]);
                    }

                }*///cannot understand what you are trying to achieve here, but seems not wokring

                //$_SESSION['cart']['totalItems']--; // Deduct by 1. //again use this if you want 1st approach

                //use the following if you want the 2nd approach which i recommend
                $_SESSION['cart']['totalItems']-=$_SESSION['cart']['cartItems'][$product_id]['quantity'];
                unset($_SESSION['cart']['cartItems'][$product_id]); //this lines is working
            }
            else
            {
                $_SESSION['cart']['cartItems'] = $cartProduct;//what this line do, it seems a bit strange, not to say wrong...
            }
        }
    }

    $_SESSION['cart']['totalPrice'] = array_sum(array_map(function($item) {
        return $item['price'] * $item['quantity']; //it's quantity not totla_items
    }, //this calculation has to be outside of the else if ($_REQUEST['action'] == 'removeRow') in order to make the toal sum calculation in every pass
    $_SESSION['cart']['cartItems']));
    $cart = json_encode($_SESSION['cart']);
    echo ($cart);
</code>```

And here are the test data i have used to check the code.

```<code>$_REQUEST['action'] = "addToCart";
//unset( $_SESSION['cart']);
/*$product_id = 7;
$product_name = "Bedrukt jurkje van chiffon";
$product_price = 20.5;
$product_size = "M";
$product_quantity = 1;
$total_product_price = 20.5;
*/
$product_id = 5;
$product_name = "Bedrukte Zomerjurk";
$product_price = 30.5;
$product_size = "M";
$product_quantity = 1;
$total_product_price = 30.5;
</code>```

every time i run the script i comment / un comment and a product, change the $_REQUEST['action'] to removeRow in order to check the delete functionality.

Title: editing a JSON file

Body:
First of all yes I did check other options, questions and answers but sadly those didn't work for me.

So I'm currently working on a small project including a shopping cart system.
The shopping cart system is created by a PHP session and everything works fine. Products can be added, rows can be deleted and the cart can be cleared completely.

Now I would like to add some functions like counting the items in the cart, calculating the total price and VAT prices. Since the session is stored as a JSON object I'm able to use angularjs and $http.get() to read the JSON cart object and redefine the data so it's usable in an ng-repeat for the view.

So when the visitor clicks on the "add to cart" button the following code is creating the session:

session_start();

$product_id = $_REQUEST['product_id'];
$product_name = $_REQUEST['product_name'];
$product_price = round($_REQUEST['product_price'], 2);
$product_size = $_REQUEST['product_size'];
$product_quantity = $_REQUEST['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);
// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price,
    "total_items" => 0
);

/*
 * check if the 'cart' session array was created
 * if it is NOT, create the 'cart' session array
 */
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
}

// check if the item is in the array, if it is, do not add
if(array_key_exists($product_id and $product_size, $_SESSION['cart'])){
    // redirect to product list and tell the user it was added to cart
    echo "])";
}

// else, add the item to the array
else{
    $_SESSION['cart']["cartItems"][$product_id]=$cartProduct;
}

So my first attempt was to add the following to the section "add the item to the array"

    $arr = json_decode($_SESSION['cart']['cartItems'][$product_id], true);
    $total_items['total_items'] = count($_SESSION['cart']);
    array_push($arr['cartItems'], $total_items);

But sadly this didn't work. I also tried adding this to the getCart section.

session_start();

$json = json_encode($_SESSION['cart']["cartItems"]);
echo($json);

Sadly also without any result.

So my question is how am I able to add the total_items calculation to the array. And how am I able to calculate the total price, VAT prices etc?

PS: the JSON outcome of one product:

{"16":{"id":"16","name":"TestDatumProduct","price":1000,"size":"M","quantity":"4","total_product_price":4000,"total_items":0}}

UPDATE

So an update to combine the progress of the last few days:

So currently my code is based on the answer of @devionNL since i like the action method and the answer of @FranciscoRodríguez was barely an answer since he only adviced me about the counting method, (didn't work)

So using the action examples from @devionNL i've made some small changes and came up with the following code.

<?php
session_start();
$cartItemID = $_REQUEST['cartItem_id'];
$product_id = $_REQUEST['product_id'];
$product_name = $_REQUEST['product_name'];
$product_price = round($_REQUEST['product_price'], 2);
$product_size = $_REQUEST['product_size'];
$product_quantity = $_REQUEST['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);

// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price
);

// If the session is empty create an empty array
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
}

// Add to cart
if ($_REQUEST['action'] == 'addToCart')
{
    if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
    {
        $_SESSION['cart']['cartItems']['totalItems']++;
    }
    else
    {
        $_SESSION['cart']['cartItems']['totalItems']++;
        array_push($_SESSION['cart']['cartItems'], $cartProduct );
    }
}

// RemoveRow
else if ($_REQUEST['action'] == 'removeRow') // If you want a delete action
{
    if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
    {
        if ($_SESSION['cart']['cartItems']['totalItems'] > 1)
        {
            foreach ($cartDecode as $key => $cartItem)
            {
                // IF THE TITLE MATCHES THE SIGNAL STRING
                if ($cartItem->{"id"} == $cartItemID)
                {
                    // REMOVE THIS OBJECT
                    unset($cartDecode[$key]);
                }

            }
            $_SESSION['cart']['cartItems']['totalItems']--; // Deduct by 1.
        }
    else
        {
            $_SESSION['cart']['cartItems'] = $cartProduct;
        }
    }

    $_SESSION['cart']['cartItems']['totalPrice'] = array_sum(array_map(function($item) {
        return $item['price'] * $item['totalItems'];
    },
        $_SESSION['cart']['cartItems']));

}
$cart = json_encode($_SESSION['cart']['cartItems']);
echo ($cart);

So adding to the cart, and calculating the cartItems is working as expected. But i still can't find the way of removing a row. inside the cart. Next to that i'm still struggling with getting the total price of the cart. The JSON outcome is as following:

{"totalItems":2,"0":{"id":"7","name":"Bedrukt jurkje van chiffon","price":20.5,"size":"M","quantity":"3","total_product_price":61.5},"1":{"id":"5","name":"Bedrukte Zomerjurk","price":30.5,"size":"M","quantity":"3","total_product_price":91.5}}

The full cart in JSON would then be:

{"cartItems":{"totalItems":2,"0":{"id":"7","name":"Bedrukt jurkje van chiffon","price":20.5,"size":"M","quantity":"3","total_product_price":61.5},"1":{"id":"5","name":"Bedrukte Zomerjurk","price":30.5,"size":"M","quantity":"3","total_product_price":91.5}}}

So my questions are?
1. How am i able to delete a single row (ID == "", Then delete)
2. How am i able to calculate the full price of the cart?
3. For placing the order inside the dabatase, how would i be able to select each row? (id, name, etc). I was thinking in the way of using a foreach() statement?

If there are any questions please ask them in the comments.

As always, Thanks in advance!

Body:
Ok I believe i make it work at least with my test data. I have put comments in code at every point i believe that requires a change. Also note that totalItems and totalPrice has to be in $_SESSION['cart'] and $_SESSION['cart']["cartItems"] has to maintain only the items array elese the array_map function that you want to make the sum will not work. Hope that helps you a bit.

session_start();
    $cartItemID = $_REQUEST['cartItem_id'];
    $product_id = intval($_REQUEST['product_id']); //if product_id is integer use intval
    $product_name = $_REQUEST['product_name'];
    $product_price = round(doubleval($_REQUEST['product_price']), 2);//if product_price is double use doubleval will help for the calculations
    $product_size = $_REQUEST['product_size'];
    $product_quantity = intval($_REQUEST['product_quantity']); //if product_quantity is integer use intval will help for the calculations
    $total_product_price = $product_price*$product_quantity;
    round($total_product_price, 2);

    // Add new item to session
    $cartProduct = array(
        "id" => $product_id,
        "name" => $product_name,
        "price" => $product_price,
        "size" => $product_size,
        "quantity" => $product_quantity,
        "total_product_price" => $total_product_price
    );

    // If the session is empty create an empty array
    if(empty($_SESSION['cart']["cartItems"])){
        $_SESSION['cart']["cartItems"] = array();
    }

    // Add to cart
    if ($_REQUEST['action'] == 'addToCart')
    {
        if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
        {
            //$_SESSION['cart']['totalItems']++; //this line can cause problems when removing item out of the cart, when the user adds an item and you increment the total items value, you have to increment the value for the specific product in order to substract the correct number in the removal,
            //you can use 2 approaches depending what you trying to achieve,
            //1. if $_SESSION['cart']['totalItems'] is the items by type then you don't need to increment if item exists , just comment your line
            //2. if $_SESSION['cart']['totalItems'] represents the total number of items by adding the quantity of every product then this has to change use the following which i recommend
            $_SESSION['cart']['cartItems'][$product_id]['quantity']+=$product_quantity;
            $_SESSION['cart']['cartItems'][$product_id]['total_product_price']+=$total_product_price;
        }
        else
        {
            //$_SESSION['cart']['totalItems']++;
            //use this line for 2nd apporach
            $_SESSION['cart']['cartItems'][$product_id] = $cartProduct ; //array_push is wrong here you need a key that is the product id not the next available index, array_push will just give you the next available index, that's why the rest not working

        }
        //use this line for 2nd apporach
        $_SESSION['cart']['totalItems']+=$product_quantity;
    }

    // RemoveRow
    else if ($_REQUEST['action'] == 'removeRow') // If you want a delete action
    {
        if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
        {
            if ($_SESSION['cart']['totalItems'] > 1)
            {
                /*foreach ($cartDecode as $key => $cartItem)
                {
                    // IF THE TITLE MATCHES THE SIGNAL STRING
                    if ($cartItem->{"id"} == $cartItemID)
                    {
                        // REMOVE THIS OBJECT
                        unset($cartDecode[$key]);
                    }

                }*///cannot understand what you are trying to achieve here, but seems not wokring

                //$_SESSION['cart']['totalItems']--; // Deduct by 1. //again use this if you want 1st approach

                //use the following if you want the 2nd approach which i recommend
                $_SESSION['cart']['totalItems']-=$_SESSION['cart']['cartItems'][$product_id]['quantity'];
                unset($_SESSION['cart']['cartItems'][$product_id]); //this lines is working
            }
            else
            {
                $_SESSION['cart']['cartItems'] = $cartProduct;//what this line do, it seems a bit strange, not to say wrong...
            }
        }
    }

    $_SESSION['cart']['totalPrice'] = array_sum(array_map(function($item) {
        return $item['price'] * $item['quantity']; //it's quantity not totla_items
    }, //this calculation has to be outside of the else if ($_REQUEST['action'] == 'removeRow') in order to make the toal sum calculation in every pass
    $_SESSION['cart']['cartItems']));
    $cart = json_encode($_SESSION['cart']);
    echo ($cart);

And here are the test data i have used to check the code.

$_REQUEST['action'] = "addToCart";
//unset( $_SESSION['cart']);
/*$product_id = 7;
$product_name = "Bedrukt jurkje van chiffon";
$product_price = 20.5;
$product_size = "M";
$product_quantity = 1;
$total_product_price = 20.5;
*/
$product_id = 5;
$product_name = "Bedrukte Zomerjurk";
$product_price = 30.5;
$product_size = "M";
$product_quantity = 1;
$total_product_price = 30.5;

every time i run the script i comment / un comment and a product, change the $_REQUEST['action'] to removeRow in order to check the delete functionality.


来源: stackexchange

问:
Separate a string with different delimiters in python
I came across a csv file which made me wonder what should be the correct processes to get the info out of it. I want to read each line and then each row in variables lastname, firstname and department but,

structure of the csv file is like this

```<code>lastname, firstname (department)
</code>```

lets say we have a name Jean-Claude Van Damme

```<code>Van Damme, Jean-Claude (Karate-Master)
</code>```

what would be the best way to separate such string and store in variables lastname, firstname and the department?

```<code>import csv
import string
import re

file = open('path/testing_delimiters.csv', 'rb')
reader = csv.reader(file)
for row in reader:
    data = map(string.strip, row)
print data
# output so far
# ['Van Damme', 'Jean-Claude (Karate-Master)']
</code>```

task is to separate Jean-Claude and (Karate-Master)

```<code># expected output
# ['Van Damme', 'Jean-Claude', 'Karate-Master']
</code>```

答:
You could use regular expressions and capturing groups:</p>

```<code>import re
s = 'Van Damme, Jean-Claude (Karate-Master)'
m = re.match(r'([^,]*),\s+([^,]+)\s+\(([^\(\)]*)\)', s)
lastname, firstname, department = m.groups()
# [^,]*   any non-comma, zero or more
# [^\(\)]*   any non-(), zero or more
# \s+   any whitespace char, one or more
# (...) capturing group
# \( \) match parenthesees, escaped because of special meaning
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I came across a csv file which made me wonder what should be the correct processes to get the info out of it. I want to read each line and then each row in variables lastname, firstname and department but,

structure of the csv file is like this

lastname, firstname (department)

lets say we have a name Jean-Claude Van Damme

Van Damme, Jean-Claude (Karate-Master)

what would be the best way to separate such string and store in variables lastname, firstname and the department?

import csv
import string
import re

file = open('path/testing_delimiters.csv', 'rb')
reader = csv.reader(file)
for row in reader:
    data = map(string.strip, row)
print data
# output so far
# ['Van Damme', 'Jean-Claude (Karate-Master)']

task is to separate Jean-Claude and (Karate-Master)

# expected output
# ['Van Damme', 'Jean-Claude', 'Karate-Master']

Body:
You could use regular expressions and capturing groups:

import re
s = 'Van Damme, Jean-Claude (Karate-Master)'
m = re.match(r'([^,]*),\s+([^,]+)\s+\(([^\(\)]*)\)', s)
lastname, firstname, department = m.groups()
# [^,]*   any non-comma, zero or more
# [^\(\)]*   any non-(), zero or more
# \s+   any whitespace char, one or more
# (...) capturing group
# \( \) match parenthesees, escaped because of special meaning


问:
DNN : Change Portals/0 to Portals/<random> for security measures
We want to make a DNN 9 more secure.

Is it possible and feasible to change the default "portals/0" to "portals/

Would the correct way be to update the Folders.StorageLocation?

What problems would I run into?

答:
Changing the portal ID to a random number would be difficult since they are database keys in the Portals table.

But I doubt it would help much. When you view the source the randomized portal path will still be visible. If you want to work with secure files that are not part of a Skin or Container, create a module that stores the files in the (external) database or randomize the file names and track them in a table.

And as Joe Craig mentioned, Modules that have hard coded paths to the portals folder will not work anymore.


问:
Aggregate function AVG and SUM is changing my data type size column in SybaseIQ
I m reciving a error in Sybase Iq because the Aggregation funtion (AVG and SUM) is changing the size of my column, and when I insert the values of my aggregation funtion column in the destination column ,the results are so big for the destination column.

example:

```<code>            Salary
          -----------
            0,4565
            0,4555
            0,4399
             ..
             ..
</code>```

In my procedure i need to write

```<code>        SUM(salary)/AVG(salary)
</code>```

when I write it

```<code>       select  SUM(salary)/AVG(salary) as AVG_Salary
          from mytable
             group by salary
</code>```

I recive that as result

```<code>                AVG_Salary
             ----------------
            0,425000000000000000000000000
            0,455000000000000000000000000
            0,442132124300000000000000000
            1,545646464743879540386969949
              ...
              ...
</code>```

Why is that? and if a try to round it, it doesnt work either,

what can I do?

Thanks for your kinds Answers.

AS suggestion i try to do the

```<code>   cast(AVG_Salary) as decimal (12,9)  --the size of my destination column
</code>```

it doesnt work either.
I recive the error   "Data type conversion is not possible"

答:
as stander SybaseIQ with the aggregation function shows the full result, but
decimal should be not a problem in your destination table.
if you tried the convertor

```<code>    cast(AVG_Salary) as decimal (12,9)
</code>```

and you are having the problem of "Data type conversion is not possible"  its simply because your data is too big.

I mean its possible to do that:

```<code>            AVG_Salary           cast(AVG_Salary) as decimal (12,9)
        ------------------      ------------------------------------
          1,6655040959559          1,665504095    --ok
          12,666664554543          12,666664554   --ok
          1123,8190832083          --Error
</code>```

the problem comes from your aggregation function SUM, probably it makes the result so big, and in that case "Cast" doesnt work, because cast reduce(round)  decimals but its not the way to reduce your number. thats why you are receiving  the problem of the "Data type conversion"
its not a decimal problem it is a problem that your number is too big.

Body:
I m reciving a error in Sybase Iq because the Aggregation funtion (AVG and SUM) is changing the size of my column, and when I insert the values of my aggregation funtion column in the destination column ,the results are so big for the destination column.

example:

            Salary
          -----------
            0,4565
            0,4555
            0,4399
             ..
             ..

In my procedure i need to write

        SUM(salary)/AVG(salary)

when I write it

       select  SUM(salary)/AVG(salary) as AVG_Salary
          from mytable
             group by salary

I recive that as result

                AVG_Salary
             ----------------
            0,425000000000000000000000000
            0,455000000000000000000000000
            0,442132124300000000000000000
            1,545646464743879540386969949
              ...
              ...

Why is that? and if a try to round it, it doesnt work either,

what can I do?

Thanks for your kinds Answers.

AS suggestion i try to do the

   cast(AVG_Salary) as decimal (12,9)  --the size of my destination column

it doesnt work either.
I recive the error   "Data type conversion is not possible"

Body:
as stander SybaseIQ with the aggregation function shows the full result, but
decimal should be not a problem in your destination table.
if you tried the convertor

    cast(AVG_Salary) as decimal (12,9)

and you are having the problem of "Data type conversion is not possible"  its simply because your data is too big.

I mean its possible to do that:

            AVG_Salary           cast(AVG_Salary) as decimal (12,9)
        ------------------      ------------------------------------
          1,6655040959559          1,665504095    --ok
          12,666664554543          12,666664554   --ok
          1123,8190832083          --Error

the problem comes from your aggregation function SUM, probably it makes the result so big, and in that case "Cast" doesnt work, because cast reduce(round)  decimals but its not the way to reduce your number. thats why you are receiving  the problem of the "Data type conversion"
its not a decimal problem it is a problem that your number is too big.


问:
Setting page state on load (during a GET request)?
Currently, my navigation bar uses AJAX to load new pages and window.pushState() to update the URL if the AJAX is successful.

I've realised I need to push the page state on get requests so back/forward events will have a state for my popstate listener to handle.

Should I simply inject the following script into the HTML my server responds with?

```<code><script>
    window.pushState(state, null, null);
</script>
</code>```

Or is there a way to push the state with the response (to GET)?

EDIT: An use case would be, user enters domain.com/ -> then follows a link in the navbar (which AJAX loads new content), currently if the user hits the back button nothing happens.

答:
You are quite close to the solution. You can change the url using window.history.pushState.

```<code>// Call this function when you get response with url
function processAjax(response, url){
     // Get whatever you want from response and push it in state
     document.title = response.pageTitle;
     // You can push other information here also
     window.history.pushState({"pageTitle": response.pageTitle}, response.pageTitle, url);
}
</code>```

For setting the state on load, just call window.history.pushState without third parameter which is url.

Note that, using pushState will change the url without reloading the page, which is what I think you want according to my understanding.

After this you can listen to window.onpopstate event to detect navigation changes:

```<code>window.onpopstate = function(e) {
     if (e.state) {
        var pageTitle = e.state.pageTitle;
        // Or alternatively get other information and do whatever you want with it
     }
}
</code>```

Ref: MDN

Body:
Currently, my navigation bar uses AJAX to load new pages and window.pushState() to update the URL if the AJAX is successful.

I've realised I need to push the page state on get requests so back/forward events will have a state for my popstate listener to handle.

Should I simply inject the following script into the HTML my server responds with?

Or is there a way to push the state with the response (to GET)?

EDIT: An use case would be, user enters domain.com/ -> then follows a link in the navbar (which AJAX loads new content), currently if the user hits the back button nothing happens.

Body:
You are quite close to the solution. You can change the url using window.history.pushState.

// Call this function when you get response with url
function processAjax(response, url){
     // Get whatever you want from response and push it in state
     document.title = response.pageTitle;
     // You can push other information here also
     window.history.pushState({"pageTitle": response.pageTitle}, response.pageTitle, url);
}

For setting the state on load, just call window.history.pushState without third parameter which is url.

Note that, using pushState will change the url without reloading the page, which is what I think you want according to my understanding.

After this you can listen to window.onpopstate event to detect navigation changes:

window.onpopstate = function(e) {
     if (e.state) {
        var pageTitle = e.state.pageTitle;
        // Or alternatively get other information and do whatever you want with it
     }
}

Ref: MDN


问:
How to open Google Maps to show route using Swift
I read around the Internet but couldn't find a legit answer. I need to open Google Maps when the user clicks a button to show directions. Start and destination must be automatically filled.

How can I achieve this in Swift?

If anyone has a solution, please provide me with a sample code. The start is always going to be the user's current location.

答: For those that the solution for the accepted answer didn't work for them, remember to add comgooglemaps to LSApplicationQueriesSchemes in the info.plist.


问:
server crash issue in nodejs
I have a set of api and I am posting the data to the database, in response I am fetching the required response in json form from the database. The issue that I am facing is ,when I post data for first time it will get posted and for second time my server will get crashed and gives Error: Can't set headers after they are sent.  I don't know why I am getting this error. Please let me know where I am going wrong

```<code>router.post('/addcustomerskills', function(req,res) {
    var skill = req.body.skill;
    var skill_id = req.body.skill_id;
    var skill_name = req.body.skill_name;
    var rating = req.body.rating;
    var response = {};

    if (typeof skill ==='undefined') {
        response.token = '2ewerr4';
        response.success = false,
        response.skill = null;
        response.mssg = 'fields cannot be empty';
        res.json(response);
    } else {
        var j =1;
        for (i in skill) {
            var skillObj=skill[i];
            db.query('INSERT into skill(skill_id,skill_name,rating) values(?,?,?)', [skillObj.skill_id, skillObj.skill_name, skillObj.rating], function(error, rows) {
                if (error) {
                    res.json(error);
                } else {
                    db.query('select id,skill_id,skill_name,rating FROM skills WHERE skill_id = ?', [skillObj.skill_id], function(error, rows) {
                        response.success = true,
                        //response.skills = rows;
                        response.skills = skill;
                        response.mssg = 'Successfully Updated';
                        if(j === 1) {
                            j = 0;
                            res.json(response);
                        }
                    })
                }
            });
        }
    }
});
</code>```

答:
Since, db.query() works in async way you're experiencing this issue.

So, try this

```<code>router.post('/addcustomerskills', function(req,res) {
    var skill = req.body.skill;
    var skill_id = req.body.skill_id;
    var skill_name = req.body.skill_name;
    var rating = req.body.rating;
    var response = {};

    if (typeof skill ==='undefined') {
        response.token = '2ewerr4';
        response.success = false,
        response.skill = null;
        response.mssg = 'fields cannot be empty';
        res.json(response);
    } else {
        var i, count = 0;
        // var j = 1;
        var result = [];
        for (i in skill) {
            count++;
            var skillObj=skill[i];
            db.query('INSERT into skill(skill_id,skill_name,rating) values(?,?,?)', [skillObj.skill_id, skillObj.skill_name, skillObj.rating], function(error, rows) {
                if (error) {
                    result.push(response);
                    response = {};
                    if(count == skill.length){
                        res.json(result);
                    }
                } else {
                    db.query('select id,skill_id,skill_name,rating FROM skills WHERE skill_id = ?', [skillObj.skill_id], function(innerError, innerRows) {
                        response.success = true,
                        //response.skills = innerRows;
                        response.skills = skill;
                        response.mssg = 'Successfully Updated';

                        // I don't understand why you have used the variable 'j', so I commented it
                        // if(j === 1) {
                        //     j = 0;
                        //     res.json(response);
                        // }

                        result.push(response);
                        response = {};
                        if(count == skill.length){
                            res.json(result);
                        }
                    });
                }
            });
        }
    }
});
</code>```

And also, you should use a seperate variable name when you're nesting the db.query()

Title: server crash issue in nodejs

Body:
I have a set of api and I am posting the data to the database, in response I am fetching the required response in json form from the database. The issue that I am facing is ,when I post data for first time it will get posted and for second time my server will get crashed and gives Error: Can't set headers after they are sent.  I don't know why I am getting this error. Please let me know where I am going wrong

router.post('/addcustomerskills', function(req,res) {
    var skill = req.body.skill;
    var skill_id = req.body.skill_id;
    var skill_name = req.body.skill_name;
    var rating = req.body.rating;
    var response = {};

    if (typeof skill ==='undefined') {
        response.token = '2ewerr4';
        response.success = false,
        response.skill = null;
        response.mssg = 'fields cannot be empty';
        res.json(response);
    } else {
        var j =1;
        for (i in skill) {
            var skillObj=skill[i];
            db.query('INSERT into skill(skill_id,skill_name,rating) values(?,?,?)', [skillObj.skill_id, skillObj.skill_name, skillObj.rating], function(error, rows) {
                if (error) {
                    res.json(error);
                } else {
                    db.query('select id,skill_id,skill_name,rating FROM skills WHERE skill_id = ?', [skillObj.skill_id], function(error, rows) {
                        response.success = true,
                        //response.skills = rows;
                        response.skills = skill;
                        response.mssg = 'Successfully Updated';
                        if(j === 1) {
                            j = 0;
                            res.json(response);
                        }
                    })
                }
            });
        }
    }
});

Body:
Since, db.query() works in async way you're experiencing this issue.

So, try this

router.post('/addcustomerskills', function(req,res) {
    var skill = req.body.skill;
    var skill_id = req.body.skill_id;
    var skill_name = req.body.skill_name;
    var rating = req.body.rating;
    var response = {};

    if (typeof skill ==='undefined') {
        response.token = '2ewerr4';
        response.success = false,
        response.skill = null;
        response.mssg = 'fields cannot be empty';
        res.json(response);
    } else {
        var i, count = 0;
        // var j = 1;
        var result = [];
        for (i in skill) {
            count++;
            var skillObj=skill[i];
            db.query('INSERT into skill(skill_id,skill_name,rating) values(?,?,?)', [skillObj.skill_id, skillObj.skill_name, skillObj.rating], function(error, rows) {
                if (error) {
                    result.push(response);
                    response = {};
                    if(count == skill.length){
                        res.json(result);
                    }
                } else {
                    db.query('select id,skill_id,skill_name,rating FROM skills WHERE skill_id = ?', [skillObj.skill_id], function(innerError, innerRows) {
                        response.success = true,
                        //response.skills = innerRows;
                        response.skills = skill;
                        response.mssg = 'Successfully Updated';

                        // I don't understand why you have used the variable 'j', so I commented it
                        // if(j === 1) {
                        //     j = 0;
                        //     res.json(response);
                        // }

                        result.push(response);
                        response = {};
                        if(count == skill.length){
                            res.json(result);
                        }
                    });
                }
            });
        }
    }
});

And also, you should use a seperate variable name when you're nesting the db.query()


问:
Regex to allow max 10 digits followed by only one comma and 3 more digits
I am working on a regex for allowing only max 10 digits before comma and max 3 digits after comma.

So far i have come up with this:

```<code>^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})?$.
</code>```

I am going to validate input in javascript.

I am using sap.m.input control, and user's keystroke is captured on live change event.

Following examples are accepted as user input:

1234567890,123

  4,1

   234,45

  56457

Input must always begin with a natural number and only comma should be appear.

Using the above mentioned regex, i am able to avoid first digit as zero but it is not considering this input value - 1,23.

I have added the following code in the application:

```<code>var input = oEvent.getSource().getValue();
        var isValid = false;
        var regex = /^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})?$/;
        isValid = regex.test(input);
        if (isValid == false) {
            //  oEvent.getSource().setValueState("Error");
            input = input.replace(/[^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})]/g,"");
            oEvent.getSource().setValue(input);
            return;
        }
</code>```

I also want to avoid blank entry and space in the input field. I want replace unwanted characters with space on live change event. As of now, i am unable to replace other characters using the above mentioned code.

Please suggest ways to form perfect regex to handle this scenario.

Thanks.

答:
```<code>^[1-9]\d{0,9}(,\d{0,3})?$
</code>```

[1-9] - first number must be 1-9

\d{0,9} - after first number, there can be 0 - 9 digits

,\d{0,3} - 3 more digits after comma

()? - the comma part is optional

Try this online: https://regex101.com/r/YsaXvo/1

Body:
I am working on a regex for allowing only max 10 digits before comma and max 3 digits after comma.

So far i have come up with this:

^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})?$.

I am going to validate input in javascript.

I am using sap.m.input control, and user's keystroke is captured on live change event.

Following examples are accepted as user input:

1234567890,123

  4,1

   234,45

  56457

Input must always begin with a natural number and only comma should be appear.

Using the above mentioned regex, i am able to avoid first digit as zero but it is not considering this input value - 1,23.

I have added the following code in the application:

var input = oEvent.getSource().getValue();
        var isValid = false;
        var regex = /^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})?$/;
        isValid = regex.test(input);
        if (isValid == false) {
            //  oEvent.getSource().setValueState("Error");
            input = input.replace(/[^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})]/g,"");
            oEvent.getSource().setValue(input);
            return;
        }

I also want to avoid blank entry and space in the input field. I want replace unwanted characters with space on live change event. As of now, i am unable to replace other characters using the above mentioned code.

Please suggest ways to form perfect regex to handle this scenario.

Thanks.

Body:
^[1-9]\d{0,9}(,\d{0,3})?$

[1-9] - first number must be 1-9

\d{0,9} - after first number, there can be 0 - 9 digits

,\d{0,3} - 3 more digits after comma

()? - the comma part is optional

Try this online: https://regex101.com/r/YsaXvo/1


答:
You is almost ok, except of not allowing 1 number before coma, and starting minus.

Try this one:

```<code>var regex = /^-?[1-9][0-9]{0,9}(,[0-9]{0,3})?$/;
</code>```

Title: Regex to allow max 10 digits followed by only one comma and 3 more digits

Body:
You is almost ok, except of not allowing 1 number before coma, and starting minus.

Try this one:

var regex = /^-?[1-9][0-9]{0,9}(,[0-9]{0,3})?$/;


问:
Play youtube video on hover
I just need to play the youtube video only when hovered

I have here a fiddle and can't get it to work.

```<code>$(document).ready(function(){
  $(function() {

      var playersrc = jQuery(iframe).attr('src');

          $('div').hover(function(){
          $('iframe').attr('src',playersrc+'&autoplay=1');
      }, function(){
          $('iframe').attr('src',playersrc);
      });
  });
});
</code>```

https://jsfiddle.net/rhr5p0pg/2/

updated fiddle: https://jsfiddle.net/rhr5p0pg/4/

now it plays all and when your mouse leaves the it does not go back to its originial video

答:
It is easier to use the Youtube video API.
With the API you have more controle over the videos.

https://developers.google.com/youtube/iframe_api_reference

Title: Play youtube video on hover

Body:
I just need to play the youtube video only when hovered

I have here a fiddle and can't get it to work.

$(document).ready(function(){
  $(function() {

      var playersrc = jQuery(iframe).attr('src');

          $('div').hover(function(){
          $('iframe').attr('src',playersrc+'&autoplay=1');
      }, function(){
          $('iframe').attr('src',playersrc);
      });
  });
});

https://jsfiddle.net/rhr5p0pg/2/

updated fiddle: https://jsfiddle.net/rhr5p0pg/4/

now it plays all and when your mouse leaves the it does not go back to its originial video


问:
How to add textbox on plot in plotly R?
I would like to add a text-box or information text on plot generated with plotly.
It seems like that now.
without text

I want to make it with text-box as follows (no need to circle:))).

with text-box

The code so far:

```<code>p <- plot_ly(data=data.mosann, x = ~Combined, y = ~Actual)%>%
  layout(shapes=list(type='line', x0= 0, x1= 235, y0=0, y1=235, line=list(color='red',width=3)),
         title = 'Scatter Plot Measurements-Combined Improvements MinT',
         xaxis = list(title = "Combined MinT", showgrid = TRUE),
         yaxis = list(title = "Measurements", showgrid = TRUE))
p
</code>```

答:
Try this. Change the x and y for layout annotation based on where you want your text.

```<code>p <- plot_ly(data=data.mosann, x = ~Combined, y = ~Actual)%>%
  layout(xaxis = ~Combined, yaxis = ~Actual,
         annotations = list(text = "YOUR TEXT HERE",  x = 200, y = 30,showarrow=FALSE ),
         shapes=list(type='line', x0= 0, x1= 235, y0=0, y1=235, line=list(color='red',width=3)),
         title = 'Scatter Plot Measurements-Combined Improvements MinT',
         xaxis = list(title = "Combined MinT", showgrid = TRUE),
         yaxis = list(title = "Measurements", showgrid = TRUE))
</code>```

Title: How to add textbox on plot in plotly R?

Body:
I would like to add a text-box or information text on plot generated with plotly.
It seems like that now.
without text

I want to make it with text-box as follows (no need to circle:))).

with text-box

The code so far:

p <- plot_ly(data=data.mosann, x = ~Combined, y = ~Actual)%>%
  layout(shapes=list(type='line', x0= 0, x1= 235, y0=0, y1=235, line=list(color='red',width=3)),
         title = 'Scatter Plot Measurements-Combined Improvements MinT',
         xaxis = list(title = "Combined MinT", showgrid = TRUE),
         yaxis = list(title = "Measurements", showgrid = TRUE))
p

Body:
Try this. Change the x and y for layout annotation based on where you want your text.

p <- plot_ly(data=data.mosann, x = ~Combined, y = ~Actual)%>%
  layout(xaxis = ~Combined, yaxis = ~Actual,
         annotations = list(text = "YOUR TEXT HERE",  x = 200, y = 30,showarrow=FALSE ),
         shapes=list(type='line', x0= 0, x1= 235, y0=0, y1=235, line=list(color='red',width=3)),
         title = 'Scatter Plot Measurements-Combined Improvements MinT',
         xaxis = list(title = "Combined MinT", showgrid = TRUE),
         yaxis = list(title = "Measurements", showgrid = TRUE))


问:
SDWebImage - Ignores set value of MaxCacheSize
I'm working on an iOS app and have just started implementing the amazing cache plugin SDWebImage. The thing I'm stuck at now is that I'm trying to implement a cache with a "limited size" of 200 or 500 MB and I've found the function setMaxCacheSize and I'm entering the descried number. When I print the value with NSLog in the app and simulator it shows correctly BUT the thing is that my cache still can go beyond this size... It's like the code is ignoring the max size and just keeps adding files without removing to make space..?

Is it something that I'm missing? Something that needs to be called on to make it autoClean memory when the limit is exceeded?

Thanks in advance!

答:
you could have a look at this property.

/**
 * Decompressing images that are downloaded and cached can improve performance but can consume lot of memory.
 * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption.
 */
@property (assign, nonatomic) BOOL shouldDecompressImages;


问:
How can Split PDO query based on the condition in PHP .I want to execute only part of query and another part to be executed based on the php condition
```<code>  ##  I want to Convert this Mysqli code to the Pdo
</code>```

<p>##
This is Mysqli code in which i splited the Query based on the condition
i want to do it in PDO</p>

```<code>    $query="UPDATE sitetext SET text1 = '$sitetext', email = '$email'";
    if(isset($logo))
     {
       $query.=",logo='$logo' WHERE id = 1";
     }
   else
   {
      $query.=" WHERE id = 1";
    }
     $result=mysqli_query($conn,$query);
</code>```

答:
Simply change the mysqli_exec with a PDO::exec ?    </p>

```<code>$query="UPDATE sitetext SET text1 = '$sitetext', email = '$email'";

if(isset($logo))
{
   $query.=",logo='$logo' WHERE id = 1";
}
else
{
   $query.=" WHERE id = 1";
}

$result= $PDO_Object->exec($query);
</code>```

Body:
  ##  I want to Convert this Mysqli code to the Pdo

##
This is Mysqli code in which i splited the Query based on the condition
i want to do it in PDO

    $query="UPDATE sitetext SET text1 = '$sitetext', email = '$email'";
    if(isset($logo))
     {
       $query.=",logo='$logo' WHERE id = 1";
     }
   else
   {
      $query.=" WHERE id = 1";
    }
     $result=mysqli_query($conn,$query);

Body:
Simply change the mysqli_exec with a PDO::exec ?

$query="UPDATE sitetext SET text1 = '$sitetext', email = '$email'";

if(isset($logo))
{
   $query.=",logo='$logo' WHERE id = 1";
}
else
{
   $query.=" WHERE id = 1";
}

$result= $PDO_Object->exec($query);


问:
Decompression of bz2 file fails with error
So far I've tried to decompress using mac command line tool bzip2 -dc , it throws this error : 'huff+mtf data integrity (CRC) error in data', I've even tried recovering files using bzip2recover command it converted my 4 mb file into 6000 small bz2 files with success message however decompression of all those files failed with the same error

Using python bz2 package : this throws error 'IO error Invalid data stream'

Using Apache nifi, It says Java.io.exception unexpected end of stream.

Data was fed to GSC bucket using this chain 'Palo alto block' -> 'pubsub' -> 'GCS bucket'.

All this indicates that data might be corrupt but I am not sure(can't simply blame Pub Sub). has anyone ever faced similar situation?
any kind of help will be appreciated.

you can find a sample bz2 file here

答:
Maybe it is already decompressed?

Can you do a "tar -tf file.bz2"?

Or can you try to get the file type, for example with "file.bz2"


问:
select statement
what select statement would I use to add the excel spreadsheet to an existing table, as i am getting an error trying to create a new table on the database? please can you assist me.
Thanks</p>

答:
you can also do it with OPENROWSET</p>

```<code>INSERT INTO SOMETABLE SELECT * FROM OPENROWSET( 'Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\testing.xls','SELECT * FROM [Sheet1$]')
</code>```

OwnerDisplayName: Fiona

ContentLicense: CC BY-SA 2.5

Title: select statement

Body:
you can also do it with OPENROWSET

INSERT INTO SOMETABLE SELECT * FROM OPENROWSET( 'Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\testing.xls','SELECT * FROM [Sheet1$]')

OwnerDisplayName: SQLMenace

LastEditorDisplayName: SQLMenace


问:
How do I make ES6 generators wait for promises, like in redux-saga?
I've read that generators don't wait for promises. How come this is not the case with generators in redux-saga, and how do I make my own generators wait?

For example, this saga:

takeLatest('FETCH_USER_REQUESTED', function*() {
  const fetchPromise = yield put(fetchUser());
  const user = yield fetchPromise;
  console.log(user)
  yield 1
  console.log(1)
})
```

<p>will output:</p>

```Promise
Object // <= user data fetched asynchronously
1
```

<p>instead of:</p>

```Promise
undefined
1
```

答:
How come this is not the case with generators in redux-saga, and how do I make my own generators wait?

This very popular belief, however generators in itself have no relation to Promises or asynchronous functions. Generators is just about make interruptible function with delegating some resources and responsibility to upper level function.

In case of redux-saga, there is two parts: independent saga runner process and scheduler (https://github.com/redux-saga/redux-saga/blob/master/src/internal/runSaga.js) , which is launched by sagaMiddleware.run() command, and effects reactions, which delegates actions into main saga process.

So, simplest process manager in ES6, which emulates redux-saga behavior, will be like that (very simplified):

```<code>const ProcessManager = (() => {
let context = new WeakMap();
function PM(rootSaga, lastValue) {
    if(!context.has(rootSaga)) {
        context.set(rootSaga, rootSaga())
    }
    const iterator = context.get(rootSaga);
    const { done, value } = iterator.next(lastValue);
    if(done) {
        context.delete(rootSaga)
        return;
    }
    if(Promise.resolve(value) === value) {
        value.then((asyncValue) => PM(rootSaga, asyncValue))
    } else {
        PM(rootSaga, value)
    }
}
return PM;
})()

const rootSaga = function* () {
    yield new Promise(resolve => setTimeout(resolve, 500));
    console.log('This will be printed after 500 ms from start');
    yield new Promise(resolve => setTimeout(resolve, 500));
    console.log('This will be printed after 1000 ms from start');
}

ProcessManager(rootSaga);
</code>```

Body:
I've read that generators don't wait for promises. How come this is not the case with generators in redux-saga, and how do I make my own generators wait?

For example, this saga:

takeLatest('FETCH_USER_REQUESTED', function*() {
  const fetchPromise = yield put(fetchUser());
  const user = yield fetchPromise;
  console.log(user)
  yield 1
  console.log(1)
})

will output:

Promise
Object // <= user data fetched asynchronously
1

instead of:

Promise
undefined
1

Body:
How come this is not the case with generators in redux-saga, and how do I make my own generators wait?

This very popular belief, however generators in itself have no relation to Promises or asynchronous functions. Generators is just about make interruptible function with delegating some resources and responsibility to upper level function.

In case of redux-saga, there is two parts: independent saga runner process and scheduler (https://github.com/redux-saga/redux-saga/blob/master/src/internal/runSaga.js) , which is launched by sagaMiddleware.run() command, and effects reactions, which delegates actions into main saga process.

So, simplest process manager in ES6, which emulates redux-saga behavior, will be like that (very simplified):

const ProcessManager = (() => {
let context = new WeakMap();
function PM(rootSaga, lastValue) {
    if(!context.has(rootSaga)) {
        context.set(rootSaga, rootSaga())
    }
    const iterator = context.get(rootSaga);
    const { done, value } = iterator.next(lastValue);
    if(done) {
        context.delete(rootSaga)
        return;
    }
    if(Promise.resolve(value) === value) {
        value.then((asyncValue) => PM(rootSaga, asyncValue))
    } else {
        PM(rootSaga, value)
    }
}
return PM;
})()

const rootSaga = function* () {
    yield new Promise(resolve => setTimeout(resolve, 500));
    console.log('This will be printed after 500 ms from start');
    yield new Promise(resolve => setTimeout(resolve, 500));
    console.log('This will be printed after 1000 ms from start');
}

ProcessManager(rootSaga);


问:
Spawn 2 enemies per second in GLUT
I'm making a game in openGL and I want to spawn 2 enemies per second on the screen. The problem is, I'm calling the spawn function inside idle:

```<code>idle
{
    // ...
    world.spawnEnemy();
}
</code>```

And then, in the spawnEnemy function:

```<code>void World::spawnEnemy()
{
    Enemy newEnemy, newEnemy2;

    float start;

    start = glutGet(GLUT_ELAPSED_TIME);

    // 1/2 a second passes
    while ( (glutGet(GLUT_ELAPSED_TIME) - start) <= 500 )
    {
        ;
    }

    // create enemy
    newEnemy();
    pushToEnemyList(newEnemy);

    // another 1/2 second passes
    while ( (glutGet(GLUT_ELAPSED_TIME) - start) <= 1000 )
    {
        ;
    }

    // create enemy
    newEnemy2();
    pushToEnemyList(newEnemy2);
}
</code>```

And this is not working, of course. Probably because idle is called everytime and I'm calling a function inside idle that waits for a certain amount of time to pass and then everything starts going wrong. The solution is to do the spawning in the idle function (without calling any function, doing all the logic inside idle), but I don't like this idea. I need to do more things in a certain number of time, for example, my enemies have guns and they will have to shoot n times every second. And if I do all of these directly inside of idle it will become a mess. So, basically, how do I make this work:

```<code>idle
{
    // ...
    world.spawnEnemy();
    world.enemyShoot();
    // another functionalities that depend on time
}
</code>```

instead of this:

```<code>idle
{
   // ...
   // logic of spawnEnemy directly here in the idle function
   // logic of enemyShoot directly here in the idle function
   // logic of another functionalities that depend on time directly here in the idle function
}
</code>```

答:
There is quite a few ways to do this here the most common:

Measure elapsed time

Simply remember time of last spawn t0 and on each (idle) iteration get current time t. If t0+T<=t then spawn new enemy ans set t0=t. The T is the period of spawning in the same units as the measured time. In your case 500ms.

As mentioned OnIdle Event will take 100% of one CPU core for itself. To remedy this use Sleep(x);  where x<<T that will ease up on the CPU load (even Sleep(1); will be a big difference).

To measure time use any OS routine you got available (with high enough accuracy) I am using PerformanceCounter on Windows but there are other alternatives like RDTSC etc ...

Timers

Modern messaging based OS provides timer function which will fire your event periodically (usually with ~1ms accuracy). Just study your API to implement it. Then you just spawn your enemy inside timer event without any other logic or timing code ...

In case you do not have any timers you can fake this by creating thread with code like this inside:

```<code>for (;!spawn_exit;)
 {
 if (spawn_enabled) spawn();
 Sleep(T);
 }
</code>```

where volatile bool spawn_enabled=true,spawn_exit=false; are used to control the spawning and stop the thread (before App shutdown) But in this case be careful with multi threaded access in the spawn() function ...

Title: Spawn 2 enemies per second in GLUT

Body:
I'm making a game in openGL and I want to spawn 2 enemies per second on the screen. The problem is, I'm calling the spawn function inside idle:

idle
{
    // ...
    world.spawnEnemy();
}

And then, in the spawnEnemy function:

void World::spawnEnemy()
{
    Enemy newEnemy, newEnemy2;

    float start;

    start = glutGet(GLUT_ELAPSED_TIME);

    // 1/2 a second passes
    while ( (glutGet(GLUT_ELAPSED_TIME) - start) <= 500 )
    {
        ;
    }

    // create enemy
    newEnemy();
    pushToEnemyList(newEnemy);

    // another 1/2 second passes
    while ( (glutGet(GLUT_ELAPSED_TIME) - start) <= 1000 )
    {
        ;
    }

    // create enemy
    newEnemy2();
    pushToEnemyList(newEnemy2);
}

And this is not working, of course. Probably because idle is called everytime and I'm calling a function inside idle that waits for a certain amount of time to pass and then everything starts going wrong. The solution is to do the spawning in the idle function (without calling any function, doing all the logic inside idle), but I don't like this idea. I need to do more things in a certain number of time, for example, my enemies have guns and they will have to shoot n times every second. And if I do all of these directly inside of idle it will become a mess. So, basically, how do I make this work:

idle
{
    // ...
    world.spawnEnemy();
    world.enemyShoot();
    // another functionalities that depend on time
}

instead of this:

idle
{
   // ...
   // logic of spawnEnemy directly here in the idle function
   // logic of enemyShoot directly here in the idle function
   // logic of another functionalities that depend on time directly here in the idle function
}

Body:
There is quite a few ways to do this here the most common:

Measure elapsed time

Simply remember time of last spawn t0 and on each (idle) iteration get current time t. If t0+T<=t then spawn new enemy ans set t0=t. The T is the period of spawning in the same units as the measured time. In your case 500ms.

As mentioned OnIdle Event will take 100% of one CPU core for itself. To remedy this use Sleep(x);  where x<<T that will ease up on the CPU load (even Sleep(1); will be a big difference).

To measure time use any OS routine you got available (with high enough accuracy) I am using PerformanceCounter on Windows but there are other alternatives like RDTSC etc ...

Timers

Modern messaging based OS provides timer function which will fire your event periodically (usually with ~1ms accuracy). Just study your API to implement it. Then you just spawn your enemy inside timer event without any other logic or timing code ...

In case you do not have any timers you can fake this by creating thread with code like this inside:

for (;!spawn_exit;)
 {
 if (spawn_enabled) spawn();
 Sleep(T);
 }

where volatile bool spawn_enabled=true,spawn_exit=false; are used to control the spawning and stop the thread (before App shutdown) But in this case be careful with multi threaded access in the spawn() function ...


问:
PHP: “Notice: Undefined variable”, “warning: A non-numeric value encountered”
I am running a PHP script, and keep getting errors like:
Notice: Undefined variable: price in C:\xampp\htdocs\alenayahpharmacy\cart.php on line 128

Warning: A non-numeric value encountered in C:\xampp\htdocs\alenayahpharmacy\cart.php on line 129

Line 128 and 129 looks like this:

```<code>$pricetotal=$price*$each_item['quantity'];
$carttotal=$pricetotal+$carttotal;
</code>```

答: It simply means $price does not exist and therefore its null which leads to the second error.</p>

Body:
I am running a PHP script, and keep getting errors like:
Notice: Undefined variable: price in C:\xampp\htdocs\alenayahpharmacy\cart.php on line 128

Warning: A non-numeric value encountered in C:\xampp\htdocs\alenayahpharmacy\cart.php on line 129

Line 128 and 129 looks like this:

$pricetotal=$price*$each_item['quantity'];
$carttotal=$pricetotal+$carttotal;


问:
WMODE and Flash Video - stability and performance
for a business reasons I need to overly Flash video player with HTML content. This requires the WMODE to be set as "opaque".

However Flash Player Engineering Tinic Uro warns us over lower performance and couple years ago he even mentioned serious instability and Adobe TechNote 15523 states "the WMODE parameter is supported only on some browser/Flash Player version combinations".

In addition there is whole bunch of bugs associated directly with the WMODE option (search for "wmode" and "opaque" in Adobe Flash Player Bug and Issue Management System)

To my knowledge even YouTube tries to avoid using the WMODE "opaque" at any cost, just have a look at the design of the account drop down menu above expanded video.

My question is:

Do you have any experience with lower performance, bugs or instability regarding Flash video and WMODE "opaque"? Can you share any good reading on this topic?

答:
Yes, wmode opaque can hinder performance. "transparent" is even worse. However,

1) It's not as bad as it was a while ago (when sometimes it wouldn't work at all).

2) Most importantly, performance hit is only on certain situations. I have ran into two different situations: a) you have a part of your SWF that is being redraw, and that part of the SWF (dirty rectangle) is close to some HTML content. This forces the browser to redraw the HTML content every time the SWF part is redrawn, thus losing performance; and b) user events like a mouse rolling over a button that is close to HTML content can also be a problem... the browser seems to lose a few frames every time you move the mouse (to determine what's below the cursor, maybe?) so if you have a quick rollover (say, something that takes 0.3s) it's very easy to notice the animation 'lagging' as you move the mouse and it loses some frames.

Point is, if you can avoid situations where you are interacting with animated content below the HTML area, or if you can disable the HTML content sometimes, using opaque is ok.

Performance also vary between browsers, so be sure to test well.


答:
Error: Can't set headers after they are sent.

has simple meaning that you are sending res multiple time.

@SRK the error here is this

You have for loop in which you are sending res back every time when you query to database .

Send response back after the for loop finish .

```<code>router.post('/addcustomerskills', function(req,res) {
    var skill = req.body.skill;
    var skill_id = req.body.skill_id;
    var skill_name = req.body.skill_name;
    var rating = req.body.rating;
    var response = {};

    if (typeof skill ==='undefined') {
        response.token = '2ewerr4';
        response.success = false,
        response.skill = null;
        response.mssg = 'fields cannot be empty';
        res.json(response);
    } else {
        var j =1;
        for (i in skill) {
            var skillObj=skill[i];
            db.query('INSERT into skill(skill_id,skill_name,rating) values(?,?,?)', [skillObj.skill_id, skillObj.skill_name, skillObj.rating], function(error, rows) {
                if (error) {

                } else {
                    db.query('select id,skill_id,skill_name,rating FROM skills WHERE skill_id = ?', [skillObj.skill_id], function(error, rows) {
                        response.success = true,
                        //response.skills = rows;
                        response.skills = skill;
                        response.mssg = 'Successfully Updated';
                        if(j === 1) {
                            j = 0;

                        }
                    })
                }
            });
        }
    res.json({"message":"what you want to send"});
    }
});
</code>```

If you want to handle crush add this in your main node.js file

```<code>process.on('uncaughtException', (err) => {
  console.log("error",error);
});
</code>```

Title: server crash issue in nodejs

Body:
Error: Can't set headers after they are sent.

has simple meaning that you are sending res multiple time.

@SRK the error here is this

You have for loop in which you are sending res back every time when you query to database .

Send response back after the for loop finish .

router.post('/addcustomerskills', function(req,res) {
    var skill = req.body.skill;
    var skill_id = req.body.skill_id;
    var skill_name = req.body.skill_name;
    var rating = req.body.rating;
    var response = {};

    if (typeof skill ==='undefined') {
        response.token = '2ewerr4';
        response.success = false,
        response.skill = null;
        response.mssg = 'fields cannot be empty';
        res.json(response);
    } else {
        var j =1;
        for (i in skill) {
            var skillObj=skill[i];
            db.query('INSERT into skill(skill_id,skill_name,rating) values(?,?,?)', [skillObj.skill_id, skillObj.skill_name, skillObj.rating], function(error, rows) {
                if (error) {

                } else {
                    db.query('select id,skill_id,skill_name,rating FROM skills WHERE skill_id = ?', [skillObj.skill_id], function(error, rows) {
                        response.success = true,
                        //response.skills = rows;
                        response.skills = skill;
                        response.mssg = 'Successfully Updated';
                        if(j === 1) {
                            j = 0;

                        }
                    })
                }
            });
        }
    res.json({"message":"what you want to send"});
    }
});

If you want to handle crush add this in your main node.js file

process.on('uncaughtException', (err) => {
  console.log("error",error);
});


问:
How to add extra fields to Firebase auth? Age & Gender
So far I'm really impressed with Firebase. But I would like to know how would I go about customizing my user email authentication. I would like to add the following fields: Age and Gender for users to fill out when registering.

here's my SignUpActivity.java.

```<code>public class SignUpActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword, signupInputUsername, signupInputAge;
private Button btnLinkLogin, btnSignUp, btnResetPassword;
private ProgressBar progressBar;
private FirebaseAuth auth;
private Spinner sexSpinner;
String defaultTextForSpinner = "Sex";
String[] arrayForSpinner = {"Male", "Female"};

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

    //Get Firebase auth instance
    auth = FirebaseAuth.getInstance();

    inputEmail = (EditText) findViewById(R.id.signup_input_email);
    signupInputUsername = (EditText) findViewById(R.id.signup_input_username);
    inputPassword = (EditText) findViewById(R.id.signup_input_password);
    signupInputAge = (EditText) findViewById(R.id.signup_input_birthday);
    sexSpinner = (Spinner)findViewById(R.id.spinner);
    sexSpinner.setAdapter(new CustomSpinnerAdapter(this, R.layout.spinner_row, arrayForSpinner, defaultTextForSpinner));

    btnSignUp = (Button) findViewById(R.id.btnSignUp2);
    btnLinkLogin = (Button) findViewById(R.id.btnorlogin);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    EditText edittext = (EditText) findViewById(R.id.signup_input_birthday);

    edittext.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            //To show current date in the datepicker
            Calendar mcurrentDate = Calendar.getInstance();
            int mYear = mcurrentDate.get(Calendar.YEAR);
            int mMonth = mcurrentDate.get(Calendar.MONTH);
            int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);

            DatePickerDialog mDatePicker=new DatePickerDialog(SignUpActivity.this, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
                    // TODO Auto-generated method stub
                /*      Your code   to get date and time    */
                }
            },mYear, mMonth, mDay);
            mDatePicker.setTitle("Select birthday");
            mDatePicker.show();  }
    });

    btnSignUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String email = inputEmail.getText().toString().trim();
            String password = inputPassword.getText().toString().trim();

            if (TextUtils.isEmpty(email)) {
                Toast.makeText(getApplicationContext(), "Enter email address.", Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(password)) {
                Toast.makeText(getApplicationContext(), "Enter password.", Toast.LENGTH_SHORT).show();
                return;
            }

            if (password.length() < 6) {
                Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters.", Toast.LENGTH_SHORT).show();
                return;
            }

            progressBar.setVisibility(View.VISIBLE);
            //create user
            auth.createUserWithEmailAndPassword(email, password)
                    .addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            Toast.makeText(SignUpActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                            progressBar.setVisibility(View.GONE);
                            // If sign in fails, display a message to the user. If sign in succeeds
                            // the auth state listener will be notified and logic to handle the
                            // signed in user can be handled in the listener.
                            if (!task.isSuccessful()) {
                                Toast.makeText(SignUpActivity.this, "Authentication failed." + task.getException(),
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                startActivity(new Intent(SignUpActivity.this, MainActivity.class));
                                finish();
                            }
                        }
                    });

        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    progressBar.setVisibility(View.GONE);
}

public class CustomSpinnerAdapter extends ArrayAdapter<String> {

    Context context;
    String[] objects;
    String firstElement;
    boolean isFirstTime;

    public CustomSpinnerAdapter(Context context, int textViewResourceId, String[] objects, String defaultText) {
        super(context, textViewResourceId, objects);
        this.context = context;
        this.objects = objects;
        this.isFirstTime = true;
        setDefaultText(defaultText);
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if(isFirstTime) {
            objects[0] = firstElement;
            isFirstTime = false;
        }
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        notifyDataSetChanged();
        return getCustomView(position, convertView, parent);
    }

    public void setDefaultText(String defaultText) {
        this.firstElement = objects[0];
        objects[0] = defaultText;
    }

    public View getCustomView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.spinner_row, parent, false);
        TextView label = (TextView) row.findViewById(R.id.spinner_text);
        label.setText(objects[position]);

        return row;
    }

}
</code>```

答:
In general, after sign up, you can create a node tree for user like picture.
Then, you can get the info with user key that can get by calling FirebaseUser.
I hope it helps. If you have any questions, let me know.

Body:
So far I'm really impressed with Firebase. But I would like to know how would I go about customizing my user email authentication. I would like to add the following fields: Age and Gender for users to fill out when registering.

here's my SignUpActivity.java.

public class SignUpActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword, signupInputUsername, signupInputAge;
private Button btnLinkLogin, btnSignUp, btnResetPassword;
private ProgressBar progressBar;
private FirebaseAuth auth;
private Spinner sexSpinner;
String defaultTextForSpinner = "Sex";
String[] arrayForSpinner = {"Male", "Female"};

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

    //Get Firebase auth instance
    auth = FirebaseAuth.getInstance();

    inputEmail = (EditText) findViewById(R.id.signup_input_email);
    signupInputUsername = (EditText) findViewById(R.id.signup_input_username);
    inputPassword = (EditText) findViewById(R.id.signup_input_password);
    signupInputAge = (EditText) findViewById(R.id.signup_input_birthday);
    sexSpinner = (Spinner)findViewById(R.id.spinner);
    sexSpinner.setAdapter(new CustomSpinnerAdapter(this, R.layout.spinner_row, arrayForSpinner, defaultTextForSpinner));

    btnSignUp = (Button) findViewById(R.id.btnSignUp2);
    btnLinkLogin = (Button) findViewById(R.id.btnorlogin);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    EditText edittext = (EditText) findViewById(R.id.signup_input_birthday);

    edittext.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            //To show current date in the datepicker
            Calendar mcurrentDate = Calendar.getInstance();
            int mYear = mcurrentDate.get(Calendar.YEAR);
            int mMonth = mcurrentDate.get(Calendar.MONTH);
            int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);

            DatePickerDialog mDatePicker=new DatePickerDialog(SignUpActivity.this, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
                    // TODO Auto-generated method stub
                /*      Your code   to get date and time    */
                }
            },mYear, mMonth, mDay);
            mDatePicker.setTitle("Select birthday");
            mDatePicker.show();  }
    });

    btnSignUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String email = inputEmail.getText().toString().trim();
            String password = inputPassword.getText().toString().trim();

            if (TextUtils.isEmpty(email)) {
                Toast.makeText(getApplicationContext(), "Enter email address.", Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(password)) {
                Toast.makeText(getApplicationContext(), "Enter password.", Toast.LENGTH_SHORT).show();
                return;
            }

            if (password.length() < 6) {
                Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters.", Toast.LENGTH_SHORT).show();
                return;
            }

            progressBar.setVisibility(View.VISIBLE);
            //create user
            auth.createUserWithEmailAndPassword(email, password)
                    .addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            Toast.makeText(SignUpActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                            progressBar.setVisibility(View.GONE);
                            // If sign in fails, display a message to the user. If sign in succeeds
                            // the auth state listener will be notified and logic to handle the
                            // signed in user can be handled in the listener.
                            if (!task.isSuccessful()) {
                                Toast.makeText(SignUpActivity.this, "Authentication failed." + task.getException(),
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                startActivity(new Intent(SignUpActivity.this, MainActivity.class));
                                finish();
                            }
                        }
                    });

        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    progressBar.setVisibility(View.GONE);
}

public class CustomSpinnerAdapter extends ArrayAdapter<String> {

    Context context;
    String[] objects;
    String firstElement;
    boolean isFirstTime;

    public CustomSpinnerAdapter(Context context, int textViewResourceId, String[] objects, String defaultText) {
        super(context, textViewResourceId, objects);
        this.context = context;
        this.objects = objects;
        this.isFirstTime = true;
        setDefaultText(defaultText);
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if(isFirstTime) {
            objects[0] = firstElement;
            isFirstTime = false;
        }
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        notifyDataSetChanged();
        return getCustomView(position, convertView, parent);
    }

    public void setDefaultText(String defaultText) {
        this.firstElement = objects[0];
        objects[0] = defaultText;
    }

    public View getCustomView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.spinner_row, parent, false);
        TextView label = (TextView) row.findViewById(R.id.spinner_text);
        label.setText(objects[position]);

        return row;
    }

}


问:
Joining two tables where id does not equal
I'm struggling getting this query to produce the results I want.

I have:

table1, columns=empid, alt_id

table2, columns=empid, alt_id

I want to get the empid, and alt_id from table 1 where the alt_id does not match the alt_id in table2. They will both have alt_id numbers I just want to get the ones that do not match.

Any ideas?

答:
```<code>select *
from [Login] L inner join Employee E
on l.EmployeeID = e.EmployeeID
where l.EmployeeID not in (select EmployeeID from Employee)
</code>```

ContentLicense: CC BY-SA 4.0


问:
Go array initialization
```<code>func identityMat4() [16]float {
    return {
        1, 0, 0, 0,
        0, 1, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1 }
}
</code>```

I hope you get the idea of what I'm trying to do from the example. How do I do this in Go?

Title: Go array initialization

Body:
func identityMat4() [16]float {
    return {
        1, 0, 0, 0,
        0, 1, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1 }
}

I hope you get the idea of what I'm trying to do from the example. How do I do this in Go?

Body:
func identityMat4() [16]float64 {
    return [...]float64{
        1, 0, 0, 0,
        0, 1, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1 }
}

(Click to play)


问:
PrimeFaces p:ajax event=change and p:commandButton action
I am having some trouble with my application. I have a
 with a
 listener for the change event. I also have a
 on my page. Both the ajax listener and
 work as expected when only attempting to invoke one. The problem occurs when user edits
 and while still focused on the field, attempts to press the
 which triggers the change event ajax listener (expected) but the
 is not invoked (not expected).

Here is my code:

```<code><p:inputText id="code"
             value="#{myBean.code}" >
    <p:ajax event="change"
            listener="#{myBean.method1(myBean.code)}"
            update="@(form :input:not(button))" />
</p:inputText>

<p:commandButton id="searchButton"
                 value="Click me"
                 action="#{myBean.method2(myBean.code)}"
                 process="@this code"
                 update="@form"
                 oncomplete="PF('myDlg').show()" />
</code>```

I have read this question but the answer didn't seem to solve the issue for me.

I have tried processing the button on the ajax listener and I tried putting the button in a different form and not updating that form from the ajax listener but I can't figure it out. Is what I am trying to do even possible?

Thanks in advance for any help.

答:
If your project is running on JSF 2.2 runtime, you can utilize passthrough attributes from namespace http://xmlns.jcp.org/jsf/passthrough

I had the same issue (button doesnt work on 1st press, on next presses it works) and solved it on following way:

Add namespace to your page

```<code>xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"
</code>```

Add oninput attribute to p:inputText (no need for p:ajax)

```<code><p:inputText id="code" value="#{myBean.code}" pt:oninput="onTextChanged()"/>
</code>```

Add p:remoteCommand bellow

```<code><p:remoteCommand delay="300" name="onTextChanged"
                 actionListener="#{myBean.method1(myBean.code)}"
                 update="@(form :input:not(button))" />
</code>```

(Delay is not necessary but it gives better performance if text is typed fast.)

oninput attribute will help your input fields to detect any kind of change event: typing, deleting, copying, pasting, cutting,etc... and via p:remoteCommand to pass them to managed bean.

And you will also solve "button" issue.

Body:
I am having some trouble with my application. I have a
 with a
 listener for the change event. I also have a
 on my page. Both the ajax listener and
 work as expected when only attempting to invoke one. The problem occurs when user edits
 and while still focused on the field, attempts to press the
 which triggers the change event ajax listener (expected) but the
 is not invoked (not expected).

Here is my code:

I have read this question but the answer didn't seem to solve the issue for me.

I have tried processing the button on the ajax listener and I tried putting the button in a different form and not updating that form from the ajax listener but I can't figure it out. Is what I am trying to do even possible?

Thanks in advance for any help.

Body:
If your project is running on JSF 2.2 runtime, you can utilize passthrough attributes from namespace http://xmlns.jcp.org/jsf/passthrough

I had the same issue (button doesnt work on 1st press, on next presses it works) and solved it on following way:

Add namespace to your page

xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"

Add oninput attribute to p:inputText (no need for p:ajax)

<p:inputText id="code" value="#{myBean.code}" pt:oninput="onTextChanged()"/>

Add p:remoteCommand bellow

<p:remoteCommand delay="300" name="onTextChanged"
                 actionListener="#{myBean.method1(myBean.code)}"
                 update="@(form :input:not(button))" />

(Delay is not necessary but it gives better performance if text is typed fast.)

oninput attribute will help your input fields to detect any kind of change event: typing, deleting, copying, pasting, cutting,etc... and via p:remoteCommand to pass them to managed bean.

And you will also solve "button" issue.