问:
Posting Payment Data
I've been working on this script. It's a script for auto checkout on shopify based site like this (https://www.cityblueshop.com/products/kixx_asst). My problem is everything works fine, except submitting the payment data. For some reason it won't post the payment, even though I'm correctly extracting the id for cc_verify_id. If you guys can test it out and let me know what I'm doing wrong (stuck on this step for several days), then it will be really appreciated. You can input fake contact and credit card information. P.S. I'm new to programming so it might look messy. Thanks in advance for your help.</p>

<p>[EDIT]It looks like it's not submitting the data properly from paymentdata, but I still can't pinpoint where's the problem. </p>

```<code>import requests, sys, time, re
from datetime import datetime
from bs4 import BeautifulSoup
from urllib.parse import urlparse

s = requests.session()

def UTCtoEST():
    current=datetime.now()
    return str(current) + ' EST'

home = 'cityblueshop'
###Get Session Id###
session = s.get('https://www.'+home+'.com/cart.js').json()
sessionID = session['token']
print('SessionID:', sessionID)

###ATC###
print(UTCtoEST(), 'Adding item....')
atcdata = {
    'id': '37431305678',
    'quantity': '1'
}
for atcurlRetry in range(1):
    atcURL = s.post('https://www.'+home+'.com/cart/add.js', data=atcdata, allow_redirects=True)
    match = re.findall('"quantity":1', atcURL.text)
    if match:
        print(UTCtoEST(), 'ATC successful....')
        break
    print(UTCtoEST(), 'Trying to ATC....')
    time.sleep(0)
else:
    print(UTCtoEST(), 'Could not ATC after ' + ' retries, therefore exiting the bot.')
    sys.exit(1)

###Going to Checkout Page###
for cartRetry in range(1):
    cartdata = {
        'updates[]': 1,
        'note': '',
        'checkout': 'Check Out'
    }
    atc = s.post('https://www.'+home+'.com/cart', data=cartdata, allow_redirects=True)
###Parsing URL###
    parse = urlparse(atc.url)
    storeID = parse.path.split('/')[1]
    checkoutID = parse.path.split('checkouts/')[1]
    print('Checkout Session Id:', checkoutID)
###Get Token###
    soup = BeautifulSoup(atc.text, 'lxml')
    input = soup.find_all('input')[2]
    auth_token = input.get('value')
    print('Auth_token:', auth_token)
###Get Contact info###
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.8',
        'Host': 'checkout.shopify.com',
        'Referer': 'https: //checkout.shopify.com/'+storeID+'/checkouts/'+checkoutID+'?step=contact_information',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36'
    }
    qs = {
        'utf8': '✓',
        '_method': 'patch',
        'authenticity_token': auth_token,
        'previous_step': 'contact_information',
        'checkout[email]': 'email',
        'checkout[shipping_address][first_name]': 'First',
        'checkout[shipping_address][last_name]': 'Last',
        'checkout[shipping_address][company]': '',
        'checkout[shipping_address][address1]': 'Address 1',
        'checkout[shipping_address][address2]': '',
        'checkout[shipping_address][city]': 'City',
        'checkout[shipping_address][country]': 'United States',
        'checkout[shipping_address][province]': '',
        'checkout[shipping_address][province]': '',
        'checkout[shipping_address][province]': 'New York',
        'checkout[shipping_address][zip]': 'Zip',
        'checkout[shipping_address][phone]': 'Phone',
        'checkout[remember_me]': '',
        'checkout[remember_me]': '0',
        'checkout[client_details][browser_width]': '979',
        'checkout[client_details][browser_height]': '631',
        'checkout[client_details][javascript_enabled]': '1',
        'step': 'contact_information'
    }
    GETcontact = s.get(atc.url, data=qs, headers=headers, allow_redirects=True)

###Post Contact Info###
    headers1 = {
        'Origin': 'https://checkout.shopify.com',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.8',
        'Referer': 'https://checkout.shopify.com/'+storeID+'/checkouts/'+checkoutID,
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36'
    }
    formData = {
        'utf8': '✓',
        '_method': 'patch',
        'authenticity_token': auth_token,
        'button': '',
        'checkout[email]': 'Email',
        'checkout[shipping_address][first_name]': 'First',
        'checkout[shipping_address][last_name]': 'Last',
        'checkout[shipping_address][company]': '',
        'checkout[shipping_address][address1]': 'Address 1',
        'checkout[shipping_address][address2]': '',
        'checkout[shipping_address][city]': 'City',
        'checkout[shipping_address][country]': 'United States',
        'checkout[shipping_address][province]': 'New York',
        'checkout[shipping_address][zip]': 'Zip',
        'checkout[shipping_address][phone]': 'Phone',
        'checkout[remember_me]': '0',
        'checkout[client_details][browser_width]': '979',
        'checkout[client_details][browser_height]': '631',
        'checkout[client_details][javascript_enabled]': '1',
        'previous_step': 'contact_information',
        'step': 'shipping_method'
    }
    POSTcontact = s.post(atc.url, data=formData, headers=headers1, allow_redirects=True)
    ###Parsing Shipping Method###
    soup = BeautifulSoup(POSTcontact.text, 'html.parser')
    shipping = soup.find(attrs={'class': 'radio-wrapper'})
    shipping_method = ship.get('data-shipping-method')

###Submitting Shipping Data###
    headers2 = {
        'Origin': 'https://checkout.shopify.com',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.8',
        'Referer': 'https://checkout.shopify.com/'+storeID+'/checkouts/'+checkoutID,
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36'
    }
    ShipformData = {
        'utf8': '✓',
        '_method': 'patch',
        'authenticity_token': auth_token,
        'previous_step': 'shipping_method',
        'step': 'payment_method',
        'checkout[shipping_rate][id]': shipping_method,
        'button': '',
        'checkout[client_details][browser_width]': '1280',
        'checkout[client_details][browser_height]': '368',
        'checkout[client_details][javascript_enabled]': '1'
    }
    shippingmethod = s.post(atc.url, data=ShipformData, headers=headers2, allow_redirects=True)
    ###Parsing payment_gateaway###
    soup = BeautifulSoup(shippingmethod.text, 'html.parser')
    ul = soup.find(attrs={'class': 'radio-wrapper content-box__row '})
    payment_gateaway = ul.get('data-select-gateway')

###submitting payment info###
    CCheaders = {
        'accept': 'application/json',
        'Origin': 'https://checkout.shopifycs.com',
        'Accept-Language': 'en-US,en;q=0.8',
        'Host': 'elb.deposit.shopifycs.com',
        'content-type': 'application/json',
        'Referer': 'https://checkout.shopifycs.com/number?identifier='+checkoutID+'&location=3A%2F%2Fcheckout.shopify.com%2F'+storeID+'%2Fcheckouts%2F'+checkoutID+'%3Fpreviousstep%3Dshipping_method%26step%3Dpayment_method',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36'
    }
    ccinfo = {
        'number': "0000 0000 0000 0000",
        'name': "First Last",
        'month': 5,
        'year': 2020,
        'verification_value': "000"
    }
    creditcard = s.post('https://elb.deposit.shopifycs.com/sessions', json=ccinfo, headers=CCheaders, allow_redirects=True)
    cc_verify = creditcard.json()
    cc_verify_id = cc_verify['id']

###submitting credit card info##
    paymentheaders = {
        'Origin': 'https://checkout.shopify.com',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.8',
        'Referer': 'https://checkout.shopify.com/'+storeID+'/checkouts/'+checkoutID,
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36'
    }
    paymentdata = {
        '_method': 'patch',
        'authenticity_token': auth_token,
        'checkout[buyer_accepts_marketing]': '1',
        'checkout[client_details][browser_height]': '979',
        'checkout[client_details][browser_width]': '631',
        'checkout[client_details][javascript_enabled]': '1',
        'checkout[credit_card][vault]': 'false',
        'checkout[different_billing_address]': 'false',
        'checkout[payment_gateway]': payment_gateaway,
        'checkout[total_price]': '1199',
        'complete': '1',
        'previous_step': 'payment_method',
        's': cc_verify_id,
        'step': '',
        'utf8': '✓'
      }
    submitpayment = s.post(atc.url, data=paymentdata, headers=paymentheaders, allow_redirects=True)
    print(UTCtoEST(), submitpayment.status_code, submitpayment.url)
</code>```

答:
Just a guess, but this isn't a proper key if you are trying to post JSON..

```<code>'checkout[total_price]': '1199',
</code>```

You need to rewrite as

```<code>'checkout' : {
    'total_price': '1199',
}
</code>```

And you need to apply this solution to all the other values in that format

For example

```<code> 'checkout' : {
    'remember_me' : '',
    'shipping_address' : {
        'first_name': 'First',
        "last_name': 'Last'
</code>```

And I think you can use Python False value instead of the string ' false', but that depends on the API

Title: Posting Payment Data

Body:
I've been working on this script. It's a script for auto checkout on shopify based site like this (https://www.cityblueshop.com/products/kixx_asst). My problem is everything works fine, except submitting the payment data. For some reason it won't post the payment, even though I'm correctly extracting the id for cc_verify_id. If you guys can test it out and let me know what I'm doing wrong (stuck on this step for several days), then it will be really appreciated. You can input fake contact and credit card information. P.S. I'm new to programming so it might look messy. Thanks in advance for your help.

[EDIT]It looks like it's not submitting the data properly from paymentdata, but I still can't pinpoint where's the problem.

import requests, sys, time, re
from datetime import datetime
from bs4 import BeautifulSoup
from urllib.parse import urlparse

s = requests.session()

def UTCtoEST():
    current=datetime.now()
    return str(current) + ' EST'

home = 'cityblueshop'
###Get Session Id###
session = s.get('https://www.'+home+'.com/cart.js').json()
sessionID = session['token']
print('SessionID:', sessionID)

###ATC###
print(UTCtoEST(), 'Adding item....')
atcdata = {
    'id': '37431305678',
    'quantity': '1'
}
for atcurlRetry in range(1):
    atcURL = s.post('https://www.'+home+'.com/cart/add.js', data=atcdata, allow_redirects=True)
    match = re.findall('"quantity":1', atcURL.text)
    if match:
        print(UTCtoEST(), 'ATC successful....')
        break
    print(UTCtoEST(), 'Trying to ATC....')
    time.sleep(0)
else:
    print(UTCtoEST(), 'Could not ATC after ' + ' retries, therefore exiting the bot.')
    sys.exit(1)

###Going to Checkout Page###
for cartRetry in range(1):
    cartdata = {
        'updates[]': 1,
        'note': '',
        'checkout': 'Check Out'
    }
    atc = s.post('https://www.'+home+'.com/cart', data=cartdata, allow_redirects=True)
###Parsing URL###
    parse = urlparse(atc.url)
    storeID = parse.path.split('/')[1]
    checkoutID = parse.path.split('checkouts/')[1]
    print('Checkout Session Id:', checkoutID)
###Get Token###
    soup = BeautifulSoup(atc.text, 'lxml')
    input = soup.find_all('input')[2]
    auth_token = input.get('value')
    print('Auth_token:', auth_token)
###Get Contact info###
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.8',
        'Host': 'checkout.shopify.com',
        'Referer': 'https: //checkout.shopify.com/'+storeID+'/checkouts/'+checkoutID+'?step=contact_information',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36'
    }
    qs = {
        'utf8': '✓',
        '_method': 'patch',
        'authenticity_token': auth_token,
        'previous_step': 'contact_information',
        'checkout[email]': 'email',
        'checkout[shipping_address][first_name]': 'First',
        'checkout[shipping_address][last_name]': 'Last',
        'checkout[shipping_address][company]': '',
        'checkout[shipping_address][address1]': 'Address 1',
        'checkout[shipping_address][address2]': '',
        'checkout[shipping_address][city]': 'City',
        'checkout[shipping_address][country]': 'United States',
        'checkout[shipping_address][province]': '',
        'checkout[shipping_address][province]': '',
        'checkout[shipping_address][province]': 'New York',
        'checkout[shipping_address][zip]': 'Zip',
        'checkout[shipping_address][phone]': 'Phone',
        'checkout[remember_me]': '',
        'checkout[remember_me]': '0',
        'checkout[client_details][browser_width]': '979',
        'checkout[client_details][browser_height]': '631',
        'checkout[client_details][javascript_enabled]': '1',
        'step': 'contact_information'
    }
    GETcontact = s.get(atc.url, data=qs, headers=headers, allow_redirects=True)

###Post Contact Info###
    headers1 = {
        'Origin': 'https://checkout.shopify.com',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.8',
        'Referer': 'https://checkout.shopify.com/'+storeID+'/checkouts/'+checkoutID,
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36'
    }
    formData = {
        'utf8': '✓',
        '_method': 'patch',
        'authenticity_token': auth_token,
        'button': '',
        'checkout[email]': 'Email',
        'checkout[shipping_address][first_name]': 'First',
        'checkout[shipping_address][last_name]': 'Last',
        'checkout[shipping_address][company]': '',
        'checkout[shipping_address][address1]': 'Address 1',
        'checkout[shipping_address][address2]': '',
        'checkout[shipping_address][city]': 'City',
        'checkout[shipping_address][country]': 'United States',
        'checkout[shipping_address][province]': 'New York',
        'checkout[shipping_address][zip]': 'Zip',
        'checkout[shipping_address][phone]': 'Phone',
        'checkout[remember_me]': '0',
        'checkout[client_details][browser_width]': '979',
        'checkout[client_details][browser_height]': '631',
        'checkout[client_details][javascript_enabled]': '1',
        'previous_step': 'contact_information',
        'step': 'shipping_method'
    }
    POSTcontact = s.post(atc.url, data=formData, headers=headers1, allow_redirects=True)
    ###Parsing Shipping Method###
    soup = BeautifulSoup(POSTcontact.text, 'html.parser')
    shipping = soup.find(attrs={'class': 'radio-wrapper'})
    shipping_method = ship.get('data-shipping-method')

###Submitting Shipping Data###
    headers2 = {
        'Origin': 'https://checkout.shopify.com',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.8',
        'Referer': 'https://checkout.shopify.com/'+storeID+'/checkouts/'+checkoutID,
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36'
    }
    ShipformData = {
        'utf8': '✓',
        '_method': 'patch',
        'authenticity_token': auth_token,
        'previous_step': 'shipping_method',
        'step': 'payment_method',
        'checkout[shipping_rate][id]': shipping_method,
        'button': '',
        'checkout[client_details][browser_width]': '1280',
        'checkout[client_details][browser_height]': '368',
        'checkout[client_details][javascript_enabled]': '1'
    }
    shippingmethod = s.post(atc.url, data=ShipformData, headers=headers2, allow_redirects=True)
    ###Parsing payment_gateaway###
    soup = BeautifulSoup(shippingmethod.text, 'html.parser')
    ul = soup.find(attrs={'class': 'radio-wrapper content-box__row '})
    payment_gateaway = ul.get('data-select-gateway')

###submitting payment info###
    CCheaders = {
        'accept': 'application/json',
        'Origin': 'https://checkout.shopifycs.com',
        'Accept-Language': 'en-US,en;q=0.8',
        'Host': 'elb.deposit.shopifycs.com',
        'content-type': 'application/json',
        'Referer': 'https://checkout.shopifycs.com/number?identifier='+checkoutID+'&location=3A%2F%2Fcheckout.shopify.com%2F'+storeID+'%2Fcheckouts%2F'+checkoutID+'%3Fpreviousstep%3Dshipping_method%26step%3Dpayment_method',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36'
    }
    ccinfo = {
        'number': "0000 0000 0000 0000",
        'name': "First Last",
        'month': 5,
        'year': 2020,
        'verification_value': "000"
    }
    creditcard = s.post('https://elb.deposit.shopifycs.com/sessions', json=ccinfo, headers=CCheaders, allow_redirects=True)
    cc_verify = creditcard.json()
    cc_verify_id = cc_verify['id']

###submitting credit card info##
    paymentheaders = {
        'Origin': 'https://checkout.shopify.com',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.8',
        'Referer': 'https://checkout.shopify.com/'+storeID+'/checkouts/'+checkoutID,
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36'
    }
    paymentdata = {
        '_method': 'patch',
        'authenticity_token': auth_token,
        'checkout[buyer_accepts_marketing]': '1',
        'checkout[client_details][browser_height]': '979',
        'checkout[client_details][browser_width]': '631',
        'checkout[client_details][javascript_enabled]': '1',
        'checkout[credit_card][vault]': 'false',
        'checkout[different_billing_address]': 'false',
        'checkout[payment_gateway]': payment_gateaway,
        'checkout[total_price]': '1199',
        'complete': '1',
        'previous_step': 'payment_method',
        's': cc_verify_id,
        'step': '',
        'utf8': '✓'
      }
    submitpayment = s.post(atc.url, data=paymentdata, headers=paymentheaders, allow_redirects=True)
    print(UTCtoEST(), submitpayment.status_code, submitpayment.url)

Body:
Just a guess, but this isn't a proper key if you are trying to post JSON..

'checkout[total_price]': '1199',

You need to rewrite as

'checkout' : {
    'total_price': '1199',
}

And you need to apply this solution to all the other values in that format

For example

 'checkout' : {
    'remember_me' : '',
    'shipping_address' : {
        'first_name': 'First',
        "last_name': 'Last'

And I think you can use Python False value instead of the string ' false', but that depends on the API


来源: stackexchange

问:
Which pointer value is the max for a malloc call
Fairly simple question regarding malloc. What is the max that I can set within the allocated area. For instance:</p>

```<code>char *buffer;
buffer = malloc(20);
buffer[19] = 'a'; //Is this the highest spot I can set?
buffer[20] = 'a'; //Or is this the highest spot I can set?
free(buffer);
</code>```

答:
The phrasing of your question is a bit off.  You mean "what is the maximum index I can use for an allocated block of memory".  The answer is the same as for arrays.

If you are reading or writing the memory, you may safely use indices between (and including) 0 and one less than the size of the block (in your case, that means index 19).  All up, that means you can access the 20 values that you asked for.

If you are simply obtaining the pointer for comparison with other pointers inside the same block (and you are not going to read or write to it), you may additionally obtain the pointer one-past-the-end (in your case that means index 20).

To clarify these things with examples:

Yes, buffer[19] = 'a'; is the very last value you may access in a read or write capacity.  Don't forget that if you want to store a string in this memory, and hand it to functions that expect a null-terminated string, this slot is your last chance to put that value of '\0'.

You are allowed to access buffer[20] in the following manner:

```<code>char *p;
for( p = &buffer[0]; p != &buffer[20]; ++p )
{
    putc( *p, stdout );
}
</code>```

This is useful because of the way we tend to iterate over memory and store sizes.  It would make our code quite less readable if we had to subtract 1 all over the place.

Oh, and it gives you the neat trick:

```<code>size_t buf_size = 20;
char *buffer = malloc(buf_size);
char *start = buffer;
char *end = buffer + buf_size;
size_t oops_i_forgot_the_size = end - start;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Fairly simple question regarding malloc. What is the max that I can set within the allocated area. For instance:

char *buffer;
buffer = malloc(20);
buffer[19] = 'a'; //Is this the highest spot I can set?
buffer[20] = 'a'; //Or is this the highest spot I can set?
free(buffer);

Body:
The phrasing of your question is a bit off.  You mean "what is the maximum index I can use for an allocated block of memory".  The answer is the same as for arrays.

If you are reading or writing the memory, you may safely use indices between (and including) 0 and one less than the size of the block (in your case, that means index 19).  All up, that means you can access the 20 values that you asked for.

If you are simply obtaining the pointer for comparison with other pointers inside the same block (and you are not going to read or write to it), you may additionally obtain the pointer one-past-the-end (in your case that means index 20).

To clarify these things with examples:

Yes, buffer[19] = 'a'; is the very last value you may access in a read or write capacity.  Don't forget that if you want to store a string in this memory, and hand it to functions that expect a null-terminated string, this slot is your last chance to put that value of '\0'.

You are allowed to access buffer[20] in the following manner:

char *p;
for( p = &buffer[0]; p != &buffer[20]; ++p )
{
    putc( *p, stdout );
}

This is useful because of the way we tend to iterate over memory and store sizes.  It would make our code quite less readable if we had to subtract 1 all over the place.

Oh, and it gives you the neat trick:

size_t buf_size = 20;
char *buffer = malloc(buf_size);
char *start = buffer;
char *end = buffer + buf_size;
size_t oops_i_forgot_the_size = end - start;


问:
Using different colors AND shapes in legend [Seaborn, Python]
I've read through examples on how to use different shapes and/or colors to separate data in a Seaborn plot. However, it seems that color and shapes are tied together, to show a separate variable.  For instance, in the following script (borrowed from the link above) it seems like you can only use green down arrows and grey up arrows:

```<code>g = sns.FacetGrid(tips, col="sex", hue="time", palette=pal,
                  hue_order=["Dinner", "Lunch"],
                  hue_kws=dict(marker=["^", "v"]))
g = (g.map(plt.scatter, "total_bill", "tip", **kws).add_legend())
</code>```

Is it possible to show, say, green up arrows and grey up arrows, as well as green down arrows and grey down arrows?

I've tried to define a dictionary for col in a similar fashion to what is being done for hue, but I'm still trying to wrap my head around this.

答:
I assume that you are taking advantage of some of the features of the sns.FacetGrid function. If you are just trying to make a simple scatter plot, then using plt.scatter directly is probably more straightforward.

Anyway, it seems possible to use whatever colors and symbols that you want in the FacetGrid example. I'm not a Seaborn pro, but here is one way to accomplish this:

```<code>import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
kws = dict(s=50, linewidth=.5, edgecolor="w")
pal = ['red', 'green', 'blue', 'red', 'green', 'blue',]
g = sns.FacetGrid(tips, col="sex", hue="size", palette=pal, hue_kws=dict(marker=["^", "^", "^", "v", "v", "v"]))
g = (g.map(plt.scatter, "total_bill", "tip", **kws).add_legend())

plt.show()
</code>```

Body:
I've read through examples on how to use different shapes and/or colors to separate data in a Seaborn plot. However, it seems that color and shapes are tied together, to show a separate variable.  For instance, in the following script (borrowed from the link above) it seems like you can only use green down arrows and grey up arrows:

g = sns.FacetGrid(tips, col="sex", hue="time", palette=pal,
                  hue_order=["Dinner", "Lunch"],
                  hue_kws=dict(marker=["^", "v"]))
g = (g.map(plt.scatter, "total_bill", "tip", **kws).add_legend())

Is it possible to show, say, green up arrows and grey up arrows, as well as green down arrows and grey down arrows?

I've tried to define a dictionary for col in a similar fashion to what is being done for hue, but I'm still trying to wrap my head around this.

Body:
I assume that you are taking advantage of some of the features of the sns.FacetGrid function. If you are just trying to make a simple scatter plot, then using plt.scatter directly is probably more straightforward.

Anyway, it seems possible to use whatever colors and symbols that you want in the FacetGrid example. I'm not a Seaborn pro, but here is one way to accomplish this:

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
kws = dict(s=50, linewidth=.5, edgecolor="w")
pal = ['red', 'green', 'blue', 'red', 'green', 'blue',]
g = sns.FacetGrid(tips, col="sex", hue="size", palette=pal, hue_kws=dict(marker=["^", "^", "^", "v", "v", "v"]))
g = (g.map(plt.scatter, "total_bill", "tip", **kws).add_legend())

plt.show()


问:
Enumerate or list all variables in a program of [your favorite language here]
A friend asked me last week how to enumerate or list all variables within a program/function/etc. for the purposes of debugging (essentially getting a snapshot of everything so you can see what variables are set to, or if they are set at all). I looked around a bit and found a relatively good way for Python:

```
#!/usr/bin/python
foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a",
        "2":"b"}
foo4 = "1+1"

for name in dir():
    myvalue = eval(name)
    print name, "is", type(name), "and is equal to ", myvalue
```

which will output something like:

```
__builtins__ is <type 'str'> and is equal to  <module '__builtin__' (built-in)>
__doc__ is <type 'str'> and is equal to  None
__file__ is <type 'str'> and is equal to  ./foo.py
__name__ is <type 'str'> and is equal to  __main__
foo1 is <type 'str'> and is equal to  Hello world
foo2 is <type 'str'> and is equal to  bar
foo3 is <type 'str'> and is equal to  {'1': 'a', '2': 'b'}
foo4 is <type 'str'> and is equal to  1+1
```

I have so far found a partial way in PHP (courtesy of link text) but it only lists all variables and their types, not the contents:

```
<?php
// create a few variables
$bar = 'foo';
$foo ='bar';
// create a new array object
$arrayObj = new ArrayObject(get_defined_vars());
// loop over the array object and echo variables and values
for($iterator = $arrayObj->getIterator(); $iterator->valid(); $iterator->next())
        {
        echo $iterator->key() . ' => ' . $iterator->current() . '<br />';
        }
?>
```

So I put it to you: how do you list all variables and their contents in your favorite language?

Edit by VonC: I propose this question follows the spirit of a little "code-challenge".

If you do not agree, just edit and remove the tag and the link.

答:
First, I'd simply use a debugger ;-p
Visual Studio, for example, has "Locals" and "Watch" windows that will show all the variables etc you want, fully expandable to any level.

In C# you can't really get at method variables very easily (and they many well be removed by the compiler) - but you can access fields etc via reflection:

```<code>static class Program { // formatted for minimal vertical space
    static object foo1 = "Hello world", foo2 = "bar",
                  foo3 = new[] { 1, 2, 3 }, foo4;
    static void Main() {
        foreach (var field in typeof(Program).GetFields(
                BindingFlags.Static | BindingFlags.NonPublic)) {
            var val = field.GetValue(null);
            if (val == null) {
                Console.WriteLine("{0} is null", field.Name);
            } else {
                Console.WriteLine("{0} ({1}) = {2}",
                    field.Name, val.GetType().Name, val);
            }
        }
    }
}
</code>```

OwnerDisplayName: Kurt

ContentLicense: CC BY-SA 2.5

Body:
A friend asked me last week how to enumerate or list all variables within a program/function/etc. for the purposes of debugging (essentially getting a snapshot of everything so you can see what variables are set to, or if they are set at all). I looked around a bit and found a relatively good way for Python:

#!/usr/bin/python
foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a",
        "2":"b"}
foo4 = "1+1"

for name in dir():
    myvalue = eval(name)
    print name, "is", type(name), "and is equal to ", myvalue

which will output something like:

__builtins__ is <type 'str'> and is equal to  <module '__builtin__' (built-in)>
__doc__ is <type 'str'> and is equal to  None
__file__ is <type 'str'> and is equal to  ./foo.py
__name__ is <type 'str'> and is equal to  __main__
foo1 is <type 'str'> and is equal to  Hello world
foo2 is <type 'str'> and is equal to  bar
foo3 is <type 'str'> and is equal to  {'1': 'a', '2': 'b'}
foo4 is <type 'str'> and is equal to  1+1

I have so far found a partial way in PHP (courtesy of link text) but it only lists all variables and their types, not the contents:

<?php
// create a few variables
$bar = 'foo';
$foo ='bar';
// create a new array object
$arrayObj = new ArrayObject(get_defined_vars());
// loop over the array object and echo variables and values
for($iterator = $arrayObj->getIterator(); $iterator->valid(); $iterator->next())
        {
        echo $iterator->key() . ' => ' . $iterator->current() . '
';
        }
?>

So I put it to you: how do you list all variables and their contents in your favorite language?

Edit by VonC: I propose this question follows the spirit of a little "code-challenge".

If you do not agree, just edit and remove the tag and the link.

LastEditorDisplayName: VonC

Body:
First, I'd simply use a debugger ;-p
Visual Studio, for example, has "Locals" and "Watch" windows that will show all the variables etc you want, fully expandable to any level.

In C# you can't really get at method variables very easily (and they many well be removed by the compiler) - but you can access fields etc via reflection:

static class Program { // formatted for minimal vertical space
    static object foo1 = "Hello world", foo2 = "bar",
                  foo3 = new[] { 1, 2, 3 }, foo4;
    static void Main() {
        foreach (var field in typeof(Program).GetFields(
                BindingFlags.Static | BindingFlags.NonPublic)) {
            var val = field.GetValue(null);
            if (val == null) {
                Console.WriteLine("{0} is null", field.Name);
            } else {
                Console.WriteLine("{0} ({1}) = {2}",
                    field.Name, val.GetType().Name, val);
            }
        }
    }
}

OwnerDisplayName: Marc Gravell


问:
How to access JSON element using regex or array index in PHP
I am trying to read JSON elements "unit" and "value" using PHP. However, some JSON elements ("local/sysbench-cpu-1.0.0", "m4.4xlarge-4.4.0-66-generic") may not be the same in each JSON. That is why I want to use regex or the array index to access elements rather then a particular string:

```<code>{
    "title": "cputests-sysbench-cpu-100-m4-4xlarge-20170328",
    "results": {
        "local\/sysbench-cpu-1.0.0": {
            "arguments": "cpu performance benchmark",
            "units": "seconds",
            "results": {
                "m4.4xlarge-4.4.0-66-generic": {
                    "value": "53.2386"
                }
            }
        },
        "": {
            "arguments": "Memory Usage Monitor",
            "units": "Megabytes",
            "results": {
                "m4.4xlarge-4.4.0-66-generic": {
                    "value": "1355,1356,1357,1357,1358,1359,1358,1359,1359,1358,1357,1358,1369,1370,1374,1373,1374,1376,1370,1362,1359,1360,1358,1358,1357,1358,1360,1360,1359,1359,1362,1362,1362,1363,1362,1363,1366,1365,1369,1366,1365,1363,1362,1363,1362,1363,1363,1363,1368,1374,1373,1372,1372,1373"
                }
            }
        }
    }
}
</code>```

The PHP script works if I don't use regex or array index:

```<code><?php
$string = file_get_contents("result.json"); <br>
$data = json_decode($string); <br>
//$data = json_decode($string, true);

//var_dump(json_decode($string)); <br>

print $data->{'results'}->{**'local/sysbench-cpu-1.0.0'**}->units; <br>
print "\n";<br>
print $data->{'results'}->{'local/sysbench-cpu-1.0.0'}->{'results'}->{'**m4.4xlarge-4.4.0-66-generic**'}->value; <br>

// print $data['results']['local/sysbench-cpu-1.0.0']['units']; <br>
// print "\n"; <br>
// print $data['results']['local/sysbench-cpu-1.0.0']['results']['m4.4xlarge-4.4.0-66-generic']['value']; <br>
?>
</code>```

Any attempt to use regex in place of a string or array index when using json_decode($string, true) fails.

答:
PHP's JSON parsing only returns a plain old associative array, or an object. Neither of these support using regexes as lookups. If you insist on using native PHP, you'll have to foreach your way through the keys and values.

Or, you might take a look at something like JsonPath which allows you to load up JSON, and then use a query string that looks very close to shell globbing:

```<code>$data = ['people' => [['name' => 'Joe'], ['name' => 'Jane'], ['name' => 'John']]];
$result = (new JSONPath($data))->find('$.people.*.name'); // returns new JSONPath
</code>```

So in your case, your find() string would be something like $.results.*.units for the unit values, and $.results.*.results.*.value for the values. There's probably an even fancier query string that would return both units and values at the same time.

Body:
I am trying to read JSON elements "unit" and "value" using PHP. However, some JSON elements ("local/sysbench-cpu-1.0.0", "m4.4xlarge-4.4.0-66-generic") may not be the same in each JSON. That is why I want to use regex or the array index to access elements rather then a particular string:

{
    "title": "cputests-sysbench-cpu-100-m4-4xlarge-20170328",
    "results": {
        "local\/sysbench-cpu-1.0.0": {
            "arguments": "cpu performance benchmark",
            "units": "seconds",
            "results": {
                "m4.4xlarge-4.4.0-66-generic": {
                    "value": "53.2386"
                }
            }
        },
        "": {
            "arguments": "Memory Usage Monitor",
            "units": "Megabytes",
            "results": {
                "m4.4xlarge-4.4.0-66-generic": {
                    "value": "1355,1356,1357,1357,1358,1359,1358,1359,1359,1358,1357,1358,1369,1370,1374,1373,1374,1376,1370,1362,1359,1360,1358,1358,1357,1358,1360,1360,1359,1359,1362,1362,1362,1363,1362,1363,1366,1365,1369,1366,1365,1363,1362,1363,1362,1363,1363,1363,1368,1374,1373,1372,1372,1373"
                }
            }
        }
    }
}

The PHP script works if I don't use regex or array index:

<?php
$string = file_get_contents("result.json");

$data = json_decode($string);

//$data = json_decode($string, true);

//var_dump(json_decode($string));

print $data->{'results'}->{**'local/sysbench-cpu-1.0.0'**}->units;

print "\n";

print $data->{'results'}->{'local/sysbench-cpu-1.0.0'}->{'results'}->{'**m4.4xlarge-4.4.0-66-generic**'}->value;

// print $data['results']['local/sysbench-cpu-1.0.0']['units'];

// print "\n";

// print $data['results']['local/sysbench-cpu-1.0.0']['results']['m4.4xlarge-4.4.0-66-generic']['value'];

?>

Any attempt to use regex in place of a string or array index when using json_decode($string, true) fails.

Body:
PHP's JSON parsing only returns a plain old associative array, or an object. Neither of these support using regexes as lookups. If you insist on using native PHP, you'll have to foreach your way through the keys and values.

Or, you might take a look at something like JsonPath which allows you to load up JSON, and then use a query string that looks very close to shell globbing:

$data = ['people' => [['name' => 'Joe'], ['name' => 'Jane'], ['name' => 'John']]];
$result = (new JSONPath($data))->find('$.people.*.name'); // returns new JSONPath

So in your case, your find() string would be something like $.results.*.units for the unit values, and $.results.*.results.*.value for the values. There's probably an even fancier query string that would return both units and values at the same time.


问:
Pure HTML and CSS tabs displaying incorrectly in firefox
I've created a simple tab interface using only CSS and firefox. It works well so far, particularly in Chrome, however, it is not displaying correctly in Firefox.

Here is the JS fiddle: https://jsfiddle.net/5p5dnv43/

And the code:

#tabscontainer {
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  position: relative;
  margin-top: 0.35em;
  margin-right: none;
  padding: 0;
  height: calc(100% - 0.35em);
  width: 100%;
}

/* Style the radio group that corresponds to the tabs */
#tabscontainer > [name="radiogroupfortabs"] {
  position: absolute;
  visibility: hidden;
}

/* Set Flexbox ordering of radio items within the #tabscontainer.  A unique rule has to be created for each tab. */
#tabscontainer > #radiofortab1{-webkit-box-ordinal-group:2;-webkit-order:1;-ms-flex-order:1;order:1;}
#tabscontainer > #radiofortab2{-webkit-box-ordinal-group:3;-webkit-order:2;-ms-flex-order:2;order:2;}
#tabscontainer > #radiofortab3{-webkit-box-ordinal-group:4;-webkit-order:3;-ms-flex-order:3;order:3;}
#tabscontainer > #radiofortab4{-webkit-box-ordinal-group:5;-webkit-order:4;-ms-flex-order:4;order:4;}

/* Style all radio group LABELS (by class) to look like tabs. */
#tabscontainer > [id^="tab-label"] {
  max-height: 18px;
  margin: 4px 2px 0 0;
  display: inline-block;
  padding: 5px 11px;
  border-width: 0.5px 0.5px 0.5px 0.5px;
  border-style: solid;
  border-color: dimgrey;
  background-color: lightgrey;
  -webkit-transition: all 0.2s ease-in-out;
  transition: all 0.2s ease-in-out;
}

/* Style unselected tabs (INPUT element's label) when the pointer hovers over them.  Could use the background-image attribute here instead of colors in order to give the tab any appearance. */
#tabscontainer > [id^="tab-label"]:hover {
  background: #99ccff;
}

/* Style all of the content DIVs including setting DISPLAY to None to start with.*/
#tabscontainer > [id^="tab-content"] {
    -webkit-box-ordinal-group: 999;
    -webkit-order: 999;
    -ms-flex-order: 999;
    order: 999; /*Set to a high value*/
    display: none;
    z-index: 2;
    width: 100%;
    height: calc(100% - 2.3em);
    overflow: hidden;
    border: 0.5px solid dimgrey;
    background: white;
    margin-top: -3px;
}

/* Style the currently selected tab (checked INPUT element's label)*/
#tabscontainer > [name="radiogroupfortabs"]:checked + [id^="tab-label"] {
  z-index: 4; /*brings to front*/
  margin-top: 0px;
  padding-top: 9px;
  background-color: white;
  border-color: dimgrey dimgrey white dimgrey;
  line-height:1em;
  font-weight: bold;
}

/* Display the content DIV that corresponds to the selected tab (because of the limitations of CSS selectors, this could not be done with a single rule.  A unique rule has to be created for each tab/tab content within the tab set.) */
#tabscontainer > #radiofortab1:checked ~ #tab-content1{display: block;}
#tabscontainer > #radiofortab2:checked ~ #tab-content2{display: block;}
#tabscontainer > #radiofortab3:checked ~ #tab-content3{display: block;}
#tabscontainer > #radiofortab4:checked ~ #tab-content4{display: block;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="lower-control-pane" class="row">
    <hr id="tabs-rule"/>
    <div id="tabscontainer">
    <!-- tab 1 -->
    <input type="radio" name="radiogroupfortabs" id="radiofortab1" checked/>
        <label id="tab-label1" for="radiofortab1">Status</label>
        <div id="tab-content1">
            <h2>Status</h2>
            <p>test context for first tab component</p>
        </div>
    <!-- tab 2 -->
    <input type="radio" name="radiogroupfortabs" id="radiofortab2"/>
    <label id="tab-label2" for="radiofortab2">Notes</label>
    <div id="tab-content2">
        <h2>Notes</h2>
        <p>second tab test content</p>
    </div>
    <!-- tab 3 -->
    <input type="radio" name="radiogroupfortabs" id="radiofortab3"/>
    <label id="tab-label3" for="radiofortab3">Names</label>
    <div id="tab-content3">
        <h2>Names</h2>
        <p>test context for third tab component</p>
    </div>
    <!-- tab 4 -->
    <input type="radio" name="radiogroupfortabs" id="radiofortab4"/>
    <label id="tab-label4" for="radiofortab4">Log</label>
    <div id="tab-content4">
        <h2>Log</h2>
        <p>test context for fourth tab component</p>
    </div>
</div></code>```

All the tab titles should be displayed at the top of the interface. In Chrome, this works correctly. You can see that in Firefox, only the first tab title appears where it should. The other 3 tab titles appear below the interface.

I'm not sure what is causing this issue since it seems to work well anywhere other than Firefox.

答:
If you hide the inputs, seems to behave the same in firefox and chrome. You don't need the inputs to be on the page, so you can hide them with display: none;

#tabscontainer {
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  position: relative;
  margin-top: 0.35em;
  margin-right: none;
  padding: 0;
  height: calc(100% - 0.35em);
  width: 100%;
}

/* Style the radio group that corresponds to the tabs */

#tabscontainer > [name="radiogroupfortabs"] {
  display: none;
}

/* Set Flexbox ordering of radio items within the #tabscontainer.  A unique rule has to be created for each tab. */

#tabscontainer > #radiofortab1 {
  -webkit-box-ordinal-group: 2;
  -webkit-order: 1;
  -ms-flex-order: 1;
  order: 1;
}

#tabscontainer > #radiofortab2 {
  -webkit-box-ordinal-group: 3;
  -webkit-order: 2;
  -ms-flex-order: 2;
  order: 2;
}

#tabscontainer > #radiofortab3 {
  -webkit-box-ordinal-group: 4;
  -webkit-order: 3;
  -ms-flex-order: 3;
  order: 3;
}

#tabscontainer > #radiofortab4 {
  -webkit-box-ordinal-group: 5;
  -webkit-order: 4;
  -ms-flex-order: 4;
  order: 4;
}

/* Style all radio group LABELS (by class) to look like tabs. */

#tabscontainer > [id^="tab-label"] {
  max-height: 18px;
  margin: 4px 2px 0 0;
  display: inline-block;
  padding: 5px 11px;
  border-width: 0.5px 0.5px 0.5px 0.5px;
  border-style: solid;
  border-color: dimgrey;
  background-color: lightgrey;
  -webkit-transition: all 0.2s ease-in-out;
  transition: all 0.2s ease-in-out;
}

/* Style unselected tabs (INPUT element's label) when the pointer hovers over them.  Could use the background-image attribute here instead of colors in order to give the tab any appearance. */

#tabscontainer > [id^="tab-label"]:hover {
  background: #99ccff;
}

/* Style all of the content DIVs including setting DISPLAY to None to start with.*/

#tabscontainer > [id^="tab-content"] {
  -webkit-box-ordinal-group: 999;
  -webkit-order: 999;
  -ms-flex-order: 999;
  order: 999;
  /*Set to a high value*/
  display: none;
  z-index: 2;
  width: 100%;
  height: calc(100% - 2.3em);
  overflow: hidden;
  border: 0.5px solid dimgrey;
  background: white;
  margin-top: -3px;
}

/* Style the currently selected tab (checked INPUT element's label)*/

#tabscontainer > [name="radiogroupfortabs"]:checked + [id^="tab-label"] {
  z-index: 4;
  /*brings to front*/
  margin-top: 0px;
  padding-top: 9px;
  background-color: white;
  border-color: dimgrey dimgrey white dimgrey;
  line-height: 1em;
  font-weight: bold;
}

/* Display the content DIV that corresponds to the selected tab (because of the limitations of CSS selectors, this could not be done with a single rule.  A unique rule has to be created for each tab/tab content within the tab set.) */

#tabscontainer > #radiofortab1:checked ~ #tab-content1 {
  display: block;
}

#tabscontainer > #radiofortab2:checked ~ #tab-content2 {
  display: block;
}

#tabscontainer > #radiofortab3:checked ~ #tab-content3 {
  display: block;
}

#tabscontainer > #radiofortab4:checked ~ #tab-content4 {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="lower-control-pane" class="row">
  <hr id="tabs-rule" />
  <div id="tabscontainer">
    <!-- tab 1 -->
    <input type="radio" name="radiogroupfortabs" id="radiofortab1" checked/>
    <label id="tab-label1" for="radiofortab1">Workspace Status</label>
    <div id="tab-content1">
      <h2>Workspace Status</h2>
      <p>test context for first tab component</p>
    </div>
    <!-- tab 2 -->
    <input type="radio" name="radiogroupfortabs" id="radiofortab2" />
    <label id="tab-label2" for="radiofortab2">Notes</label>
    <div id="tab-content2">
      <h2>Notes</h2>
      <p>second tab test content</p>
    </div>
    <!-- tab 3 -->
    <input type="radio" name="radiogroupfortabs" id="radiofortab3" />
    <label id="tab-label3" for="radiofortab3">Global Names</label>
    <div id="tab-content3">
      <global-names-component (internalEditRequest)=globalNameEditRequest($event)></global-names-component>
    </div>
    <!-- tab 4 -->
    <input type="radio" name="radiogroupfortabs" id="radiofortab4" />
    <label id="tab-label4" for="radiofortab4">Log</label>
    <div id="tab-content4">
      <log-component></log-component>
    </div>
  </div>
</div></code>```

Body:
I've created a simple tab interface using only CSS and firefox. It works well so far, particularly in Chrome, however, it is not displaying correctly in Firefox.

Here is the JS fiddle: https://jsfiddle.net/5p5dnv43/

And the code:

#tabscontainer {
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  position: relative;
  margin-top: 0.35em;
  margin-right: none;
  padding: 0;
  height: calc(100% - 0.35em);
  width: 100%;
}

/* Style the radio group that corresponds to the tabs */
#tabscontainer > [name="radiogroupfortabs"] {
  position: absolute;
  visibility: hidden;
}

/* Set Flexbox ordering of radio items within the #tabscontainer.  A unique rule has to be created for each tab. */
#tabscontainer > #radiofortab1{-webkit-box-ordinal-group:2;-webkit-order:1;-ms-flex-order:1;order:1;}
#tabscontainer > #radiofortab2{-webkit-box-ordinal-group:3;-webkit-order:2;-ms-flex-order:2;order:2;}
#tabscontainer > #radiofortab3{-webkit-box-ordinal-group:4;-webkit-order:3;-ms-flex-order:3;order:3;}
#tabscontainer > #radiofortab4{-webkit-box-ordinal-group:5;-webkit-order:4;-ms-flex-order:4;order:4;}

/* Style all radio group LABELS (by class) to look like tabs. */
#tabscontainer > [id^="tab-label"] {
  max-height: 18px;
  margin: 4px 2px 0 0;
  display: inline-block;
  padding: 5px 11px;
  border-width: 0.5px 0.5px 0.5px 0.5px;
  border-style: solid;
  border-color: dimgrey;
  background-color: lightgrey;
  -webkit-transition: all 0.2s ease-in-out;
  transition: all 0.2s ease-in-out;
}

/* Style unselected tabs (INPUT element's label) when the pointer hovers over them.  Could use the background-image attribute here instead of colors in order to give the tab any appearance. */
#tabscontainer > [id^="tab-label"]:hover {
  background: #99ccff;
}

/* Style all of the content DIVs including setting DISPLAY to None to start with.*/
#tabscontainer > [id^="tab-content"] {
    -webkit-box-ordinal-group: 999;
    -webkit-order: 999;
    -ms-flex-order: 999;
    order: 999; /*Set to a high value*/
    display: none;
    z-index: 2;
    width: 100%;
    height: calc(100% - 2.3em);
    overflow: hidden;
    border: 0.5px solid dimgrey;
    background: white;
    margin-top: -3px;
}

/* Style the currently selected tab (checked INPUT element's label)*/
#tabscontainer > [name="radiogroupfortabs"]:checked + [id^="tab-label"] {
  z-index: 4; /*brings to front*/
  margin-top: 0px;
  padding-top: 9px;
  background-color: white;
  border-color: dimgrey dimgrey white dimgrey;
  line-height:1em;
  font-weight: bold;
}

/* Display the content DIV that corresponds to the selected tab (because of the limitations of CSS selectors, this could not be done with a single rule.  A unique rule has to be created for each tab/tab content within the tab set.) */
#tabscontainer > #radiofortab1:checked ~ #tab-content1{display: block;}
#tabscontainer > #radiofortab2:checked ~ #tab-content2{display: block;}
#tabscontainer > #radiofortab3:checked ~ #tab-content3{display: block;}
#tabscontainer > #radiofortab4:checked ~ #tab-content4{display: block;}

    <input type="radio" name="radiogroupfortabs" id="radiofortab1" checked/>
        Status

Status

test context for first tab component

    <input type="radio" name="radiogroupfortabs" id="radiofortab2"/>
    Notes

Notes

second tab test content

    <input type="radio" name="radiogroupfortabs" id="radiofortab3"/>
    Names

Names

test context for third tab component

    <input type="radio" name="radiogroupfortabs" id="radiofortab4"/>
    Log

Log

test context for fourth tab component

All the tab titles should be displayed at the top of the interface. In Chrome, this works correctly. You can see that in Firefox, only the first tab title appears where it should. The other 3 tab titles appear below the interface.

I'm not sure what is causing this issue since it seems to work well anywhere other than Firefox.

Body:
If you hide the inputs, seems to behave the same in firefox and chrome. You don't need the inputs to be on the page, so you can hide them with display: none;

#tabscontainer {
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  position: relative;
  margin-top: 0.35em;
  margin-right: none;
  padding: 0;
  height: calc(100% - 0.35em);
  width: 100%;
}

/* Style the radio group that corresponds to the tabs */

#tabscontainer > [name="radiogroupfortabs"] {
  display: none;
}

/* Set Flexbox ordering of radio items within the #tabscontainer.  A unique rule has to be created for each tab. */

#tabscontainer > #radiofortab1 {
  -webkit-box-ordinal-group: 2;
  -webkit-order: 1;
  -ms-flex-order: 1;
  order: 1;
}

#tabscontainer > #radiofortab2 {
  -webkit-box-ordinal-group: 3;
  -webkit-order: 2;
  -ms-flex-order: 2;
  order: 2;
}

#tabscontainer > #radiofortab3 {
  -webkit-box-ordinal-group: 4;
  -webkit-order: 3;
  -ms-flex-order: 3;
  order: 3;
}

#tabscontainer > #radiofortab4 {
  -webkit-box-ordinal-group: 5;
  -webkit-order: 4;
  -ms-flex-order: 4;
  order: 4;
}

/* Style all radio group LABELS (by class) to look like tabs. */

#tabscontainer > [id^="tab-label"] {
  max-height: 18px;
  margin: 4px 2px 0 0;
  display: inline-block;
  padding: 5px 11px;
  border-width: 0.5px 0.5px 0.5px 0.5px;
  border-style: solid;
  border-color: dimgrey;
  background-color: lightgrey;
  -webkit-transition: all 0.2s ease-in-out;
  transition: all 0.2s ease-in-out;
}

/* Style unselected tabs (INPUT element's label) when the pointer hovers over them.  Could use the background-image attribute here instead of colors in order to give the tab any appearance. */

#tabscontainer > [id^="tab-label"]:hover {
  background: #99ccff;
}

/* Style all of the content DIVs including setting DISPLAY to None to start with.*/

#tabscontainer > [id^="tab-content"] {
  -webkit-box-ordinal-group: 999;
  -webkit-order: 999;
  -ms-flex-order: 999;
  order: 999;
  /*Set to a high value*/
  display: none;
  z-index: 2;
  width: 100%;
  height: calc(100% - 2.3em);
  overflow: hidden;
  border: 0.5px solid dimgrey;
  background: white;
  margin-top: -3px;
}

/* Style the currently selected tab (checked INPUT element's label)*/

#tabscontainer > [name="radiogroupfortabs"]:checked + [id^="tab-label"] {
  z-index: 4;
  /*brings to front*/
  margin-top: 0px;
  padding-top: 9px;
  background-color: white;
  border-color: dimgrey dimgrey white dimgrey;
  line-height: 1em;
  font-weight: bold;
}

/* Display the content DIV that corresponds to the selected tab (because of the limitations of CSS selectors, this could not be done with a single rule.  A unique rule has to be created for each tab/tab content within the tab set.) */

#tabscontainer > #radiofortab1:checked ~ #tab-content1 {
  display: block;
}

#tabscontainer > #radiofortab2:checked ~ #tab-content2 {
  display: block;
}

#tabscontainer > #radiofortab3:checked ~ #tab-content3 {
  display: block;
}

#tabscontainer > #radiofortab4:checked ~ #tab-content4 {
  display: block;
}

<div id="lower-control-pane" class="row">
  <hr id="tabs-rule" />
  <div id="tabscontainer">
    <!-- tab 1 -->
    <input type="radio" name="radiogroupfortabs" id="radiofortab1" checked/>
    <label id="tab-label1" for="radiofortab1">Workspace Status</label>
    <div id="tab-content1">
      <h2>Workspace Status</h2>
      <p>test context for first tab component</p>
    </div>
    <!-- tab 2 -->
    <input type="radio" name="radiogroupfortabs" id="radiofortab2" />
    <label id="tab-label2" for="radiofortab2">Notes</label>
    <div id="tab-content2">
      <h2>Notes</h2>
      <p>second tab test content</p>
    </div>
    <!-- tab 3 -->
    <input type="radio" name="radiogroupfortabs" id="radiofortab3" />
    <label id="tab-label3" for="radiofortab3">Global Names</label>
    <div id="tab-content3">
      <global-names-component (internalEditRequest)=globalNameEditRequest($event)></global-names-component>
    </div>
    <!-- tab 4 -->
    <input type="radio" name="radiogroupfortabs" id="radiofortab4" />
    <label id="tab-label4" for="radiofortab4">Log</label>
    <div id="tab-content4">
      <log-component></log-component>
    </div>
  </div>
</div>


问:
redshift/postgresql - How to find duplicates that occur within 1 second during insert?
We have a bit of an issue where one of our nodes was logging duplicate events. We use the following query to insert only unique events, however some of the events were fired within 1 second after the previous event so the following query wouldn't catch it as the date field is different.

Can someone help me update this query so it only grabs unique events even if there is 1 second difference?

```<code>INSERT INTO project_events
    SELECT * From (
         SELECT
                session,
                date,
                team,
                project,
                event_type,
                event_group,
                event_label,
                event_value,
                event_count,

                ROW_NUMBER() OVER ( PARTITION BY
                    session,
                    date,
                    team,
                    project,
                    event_type,
                    event_group,
                    event_label,
                    event_value,
                    event_count
                    ORDER BY date, project ASC
                ) rownum
         FROM tmp_table_name where record_type='update'
    ) WHERE rownum = 1;
</code>```

答:
First of all, in your example, putting the same attributes in PARTITION BY and ORDER BY makes little sense, as the values inside each group will be identical, so your query is equivalent to simply doing SELECT DISTINCT on your PARTITION BY attributes

Now, to the real question. How can you know the element is unique? Is it based on the combo of all these attributes: session,team,project,event_type,event_group,event_label,event_value,event_count ?

If so, try this:

```<code>SELECT * FROM
(
    SELECT
            session,
            date,
            team,
            project,
            event_type,
            event_group,
            event_label,
            event_value,
            event_count,
            LAG(date) OVER (
              PARTITION BY
                session,
                team,
                project,
                event_type,
                event_group,
                event_label,
                event_value,
                event_count
              ORDER BY
                date
            ) prev_date
     FROM tmp_table_name where record_type='update'
 ) sub
 WHERE prev_date IS NULL -- first event
    OR DATEDIFF(second, prev_date, date) > 1  -- events more than 1 second apart
</code>```

Body:
We have a bit of an issue where one of our nodes was logging duplicate events. We use the following query to insert only unique events, however some of the events were fired within 1 second after the previous event so the following query wouldn't catch it as the date field is different.

Can someone help me update this query so it only grabs unique events even if there is 1 second difference?

INSERT INTO project_events
    SELECT * From (
         SELECT
                session,
                date,
                team,
                project,
                event_type,
                event_group,
                event_label,
                event_value,
                event_count,

                ROW_NUMBER() OVER ( PARTITION BY
                    session,
                    date,
                    team,
                    project,
                    event_type,
                    event_group,
                    event_label,
                    event_value,
                    event_count
                    ORDER BY date, project ASC
                ) rownum
         FROM tmp_table_name where record_type='update'
    ) WHERE rownum = 1;

Body:
First of all, in your example, putting the same attributes in PARTITION BY and ORDER BY makes little sense, as the values inside each group will be identical, so your query is equivalent to simply doing SELECT DISTINCT on your PARTITION BY attributes

Now, to the real question. How can you know the element is unique? Is it based on the combo of all these attributes: session,team,project,event_type,event_group,event_label,event_value,event_count ?

If so, try this:

SELECT * FROM
(
    SELECT
            session,
            date,
            team,
            project,
            event_type,
            event_group,
            event_label,
            event_value,
            event_count,
            LAG(date) OVER (
              PARTITION BY
                session,
                team,
                project,
                event_type,
                event_group,
                event_label,
                event_value,
                event_count
              ORDER BY
                date
            ) prev_date
     FROM tmp_table_name where record_type='update'
 ) sub
 WHERE prev_date IS NULL -- first event
    OR DATEDIFF(second, prev_date, date) > 1  -- events more than 1 second apart


问:
Bootstrap modal saves but doesn't change focus back to main app
I'm using two buttons to open the form:

```<code><button class="btn btn-primary btn-xs" id="openBtn">Add Product/Event</button>
<button ng-click="vm.showUpdate(product._id)" class="btn btn-xs btn-warning">Edit</button>
</code>```

This is the modal form code:

```<code>    <div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
                <!-- Modal Header -->
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                     <h2><span ng-if="vm.addForm">Add Product/Event</span><span ng-if="vm.updateForm">Update Product/Event</span></h2>
                </div>
                <!-- Modal Body -->
                <div class="modal-body">
                    <form  ng-show="vm.addForm || vm.updateForm" name="vm.productForm" ng-submit="vm.saveProduct()" class="form">
                        <div class="form-group">
                            <label for="event">Product/Event:</label>
                            <input type="text" class="form-control" name="event" ng-model="vm.product.event" required/>
                            <div ng-show="vm.productForm.event.$dirty && vm.isSubmitted">Required field.</div>
                        </div>
                        <div class="form-group">
                            <label for="division">Division:</label>
                            <input type="text" class="form-control" name="division" ng-model="vm.product.division"/>
                        </div>
                        <div class="form-group">
                            <label for="level">Level:</label>
                            <input type="text" class="form-control" name="level" ng-model="vm.product.level"/>
                        </div>
                        <div class="form-group">
                            <label for="day">Day:</label>
                            <input type="text" class="form-control" name="day" ng-model="vm.product.day"/>
                        </div>
                        <div class="form-group">
                            <label for="group">Group:</label>
                            <input type="text" class="form-control" name="group" ng-model="vm.product.group" required/>
                            <div ng-show="vm.productForm.group.$dirty && vm.isSubmitted">Required field.</div>
                        </div>
                        <div class="form-group">
                            <label for="numberofplayers"># Players:</label>
                            <input type="number" class="form-control" ng-model="vm.product.numberofplayers" name="numberofplayers"  min="0" max="4" integer />
                            <div ng-show="vm.productForm.numberofplayers.$error.integer">The value is not a valid integer!</div>
                            <div ng-show="vm.productForm.numberofplayers.$error.min || vm.prodctForm.numberofplayers.$error.max">Players must be 0 - 4</div>
                        </div>
                        <div class="form-group">
                            <label for="price">Price:</label>
                            <input type="number" class="form-control" name="price" ng-model="vm.product.price" integer required/>
                            <div ng-show="vm.productForm.price.$dirty && vm.isSubmitted">Required field.</div>
                            <div ng-show="vm.productForm.price.$error.integer">The price must be a valid integer!</div>
                        </div>
                        <div class="form-group">
                            <label for="description">Description:</label>
                            <textarea class="form-control" name="description" ng-model="vm.product.description"></textarea>
                        </div>
                        <div class="form-group">
                            <label for="abbr">Export Abbr:</label>
                            <input type="text" class="form-control" name="abbr" ng-model="vm.product.abbr" required/>
                            <div ng-show="vm.productForm.abbr.$dirty && vm.isSubmitted">Required field.</div>
                        </div>
                        <button type="submit" class="btn btn-primary"  ng-click="vm.saveProduct()"><span ng-if="vm.addForm">Save New</span><span ng-if="vm.updateForm">Save Changes</span></button>
                    </form>
                </div>
                <!-- Modal Footer -->
                <div class="modal-footer">
                    <button type="button" data-dismiss="modal" class="btn btn-default" ng-click="vm.hideForm()">Cancel</button>
                </div>
        </div>
    </div>
</div>
</code>```

When I click Save, it saves the changes and closes the modal but does not update the main screen or return focus there (it stays grayed out).

I've tried adding data-dismiss="modal" to the save button, but that just closes the form and doesn't make any changes to the data.  I also tried some different ways to refresh the page, but I can't seem to refresh the page AND bring focus back - only one or the other.

My controller code:

```<code>//display and populate update form
    vm.showUpdate = function(id) {
        vm.addForm = false;
        vm.updateForm = true;
        //find product by ID and return to the view
        productDataFactory.productDisplay(id).then(function(response) {
            vm.product = response.data;
            console.log('Set vm.product from showUpdate', id);
        });
        $( '#myModal' ).modal('show');
    };

//save new or updated product, close modal, refresh the view
vm.saveProduct = function() {
            console.log('Product/event form saved.');
            var postData =  {
                event: vm.product.event,
                description: vm.product.description,
            };
            if(vm.productForm.$valid) {
                //save new
                if(vm.addForm) {
                    productDataFactory.postProduct(postData).then(function(response){
                        if (response.status === 201) {
                            console.log(focused);
                            $( '#myModal' ).modal( 'hide' );
                            $( focused ).focus(); // returns focus to last active element
                            $route.reload();
                        }
                    }).catch(function(error){
                        console.log(error);
                    });
                //update existing
                } else if (vm.updateForm) {
                    console.log('Updating ', vm.product._id);
                    productDataFactory.productUpdate(vm.product._id, postData).then(function(response){
                        if(response.status === 204) {
                            $( '#myModal' ).modal( 'hide' );
                            $('#product-main').element('show');
                            $route.reload();
                        }
                    }).catch(function(error){
                        console.log(error);
                    });
                }
            //show errors
            } else {
                console.log('Invalid product form');
                vm.isSubmitted = true;
            }
        };
</code>```

What am I missing here?

答:
I figured out how to get this to work, and I know a lot of other people are looking at it as well, so here is how I did it.  Thank you to glass duo for leading me in the right direction:

First, I used two different buttons to open the form:

```<code><button ng-click="vm.openForm()" class="btn btn-xs btn-primary">Edit</button>
<button ng-click="vm.openForm(product._id)" class="btn btn-xs btn-warning">Edit</button>
</code>```

I cleaned up the code in my controller, and used hidden.bs.modal to run the code to reload the page after the save:

```<code>vm.isSubmitted = false;
vm.formMode;

//set form mode to add or edit, display product info, if any, and show modal
    vm.openForm = function(id = null) {
        if(id) {
            //find product info
            vm.formMode = 'update';
            productDataFactory.productDisplay(id).then(function(response) {
            vm.product = response.data;
            console.log('Set vm.product from showUpdate', id);
            });
        } else if(id == null) {
            //populate blank form
            vm.formMode = 'add';
            vm.product = {};
            console.log('Generate blank form');
        }
        //display modal form
        $("#myModal").modal({backdrop: true});
    };

    vm.closeForm = function(){
        $('#myModal').modal('hide');
       $("#myModal").on('hidden.bs.modal', function () {
            vm.formMode = null; //reset form mode
            $route.reload();
    });

    };

    vm.saveProduct = function() {
        console.log('Product/event form save button pressed.');
        var postData =  {
            event: vm.product.event,
            division: vm.product.division,
            level: vm.product.level,
            day: vm.product.day,
            group: vm.product.group,
            numberofplayers: parseInt(vm.product.numberofplayers, 10),
            price: parseInt(vm.product.price, 10),
            description: vm.product.description,
            abbr: vm.product.abbr
        };
        if(vm.productForm.$valid) {
            //save new
            if(vm.formMode === 'add') {
                productDataFactory.postProduct(postData).then(function(response){
                    if (response.status === 201) {
                        console.log('Saved product successfully');
                    }
                }).catch(function(error){
                    console.log(error);
                });
            //update existing
            } else if (vm.formMode === 'update') {
                console.log('Updating ', vm.product._id);
                productDataFactory.productUpdate(vm.product._id, postData).then(function(response){
                    if(response.status == 204) {
                        console.log('Updated product successfully');
                    }
                }).catch(function(error){
                    console.log(error);
                });
            }
            //close form & refresh page
            vm.closeForm();
        //show errors
        } else {
            console.log('Invalid product form');
            vm.isSubmitted = true;
        }
    };
</code>```

Finally, I set the save and cancel buttons to run the appropriate code:

```<code><button type="submit" class="btn btn-primary"  ng-click="vm.saveProduct()">Save</button>
<button type="button" data-dismiss="modal" class="btn btn-default" ng-click="vm.closeForm()">Cancel</button>
</code>```

If you have the form submitting to saveProduct() along with these buttons, you'll save the model twice, so pick one or the other.

It should be noted that while I'm using angularjs, I used the regular bootstrap modal instead of angular-ui-bootstrap's modal.  Without using hidden-bs-modal, which allows you to run code AFTER the modal has closed, it just doesn't work refreshing the view with the updated code AND restoring active focus to the main view.

Body:
I'm using two buttons to open the form:

<button class="btn btn-primary btn-xs" id="openBtn">Add Product/Event</button>
<button ng-click="vm.showUpdate(product._id)" class="btn btn-xs btn-warning">Edit</button>

This is the modal form code:

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Add Product/EventUpdate Product/Event

                    <form  ng-show="vm.addForm || vm.updateForm" name="vm.productForm" ng-submit="vm.saveProduct()" class="form">

                            Product/Event:
                            <input type="text" class="form-control" name="event" ng-model="vm.product.event" required/>

Required field.

                            Division:
                            <input type="text" class="form-control" name="division" ng-model="vm.product.division"/>

                            Level:
                            <input type="text" class="form-control" name="level" ng-model="vm.product.level"/>

                            Day:
                            <input type="text" class="form-control" name="day" ng-model="vm.product.day"/>

                            Group:
                            <input type="text" class="form-control" name="group" ng-model="vm.product.group" required/>

Required field.

                            # Players:
                            <input type="number" class="form-control" ng-model="vm.product.numberofplayers" name="numberofplayers"  min="0" max="4" integer />

The value is not a valid integer!

Players must be 0 - 4

                            Price:
                            <input type="number" class="form-control" name="price" ng-model="vm.product.price" integer required/>

Required field.

The price must be a valid integer!

                            Description:
                            <textarea class="form-control" name="description" ng-model="vm.product.description"></textarea>

                            Export Abbr:
                            <input type="text" class="form-control" name="abbr" ng-model="vm.product.abbr" required/>

Required field.

                        <button type="submit" class="btn btn-primary"  ng-click="vm.saveProduct()">Save NewSave Changes</button>
                    </form>

                    <button type="button" data-dismiss="modal" class="btn btn-default" ng-click="vm.hideForm()">Cancel</button>

When I click Save, it saves the changes and closes the modal but does not update the main screen or return focus there (it stays grayed out).

I've tried adding data-dismiss="modal" to the save button, but that just closes the form and doesn't make any changes to the data.  I also tried some different ways to refresh the page, but I can't seem to refresh the page AND bring focus back - only one or the other.

My controller code:

//display and populate update form
    vm.showUpdate = function(id) {
        vm.addForm = false;
        vm.updateForm = true;
        //find product by ID and return to the view
        productDataFactory.productDisplay(id).then(function(response) {
            vm.product = response.data;
            console.log('Set vm.product from showUpdate', id);
        });
        $( '#myModal' ).modal('show');
    };

//save new or updated product, close modal, refresh the view
vm.saveProduct = function() {
            console.log('Product/event form saved.');
            var postData =  {
                event: vm.product.event,
                description: vm.product.description,
            };
            if(vm.productForm.$valid) {
                //save new
                if(vm.addForm) {
                    productDataFactory.postProduct(postData).then(function(response){
                        if (response.status === 201) {
                            console.log(focused);
                            $( '#myModal' ).modal( 'hide' );
                            $( focused ).focus(); // returns focus to last active element
                            $route.reload();
                        }
                    }).catch(function(error){
                        console.log(error);
                    });
                //update existing
                } else if (vm.updateForm) {
                    console.log('Updating ', vm.product._id);
                    productDataFactory.productUpdate(vm.product._id, postData).then(function(response){
                        if(response.status === 204) {
                            $( '#myModal' ).modal( 'hide' );
                            $('#product-main').element('show');
                            $route.reload();
                        }
                    }).catch(function(error){
                        console.log(error);
                    });
                }
            //show errors
            } else {
                console.log('Invalid product form');
                vm.isSubmitted = true;
            }
        };

What am I missing here?

Body:
I figured out how to get this to work, and I know a lot of other people are looking at it as well, so here is how I did it.  Thank you to glass duo for leading me in the right direction:

First, I used two different buttons to open the form:

<button ng-click="vm.openForm()" class="btn btn-xs btn-primary">Edit</button>
<button ng-click="vm.openForm(product._id)" class="btn btn-xs btn-warning">Edit</button>

I cleaned up the code in my controller, and used hidden.bs.modal to run the code to reload the page after the save:

vm.isSubmitted = false;
vm.formMode;

//set form mode to add or edit, display product info, if any, and show modal
    vm.openForm = function(id = null) {
        if(id) {
            //find product info
            vm.formMode = 'update';
            productDataFactory.productDisplay(id).then(function(response) {
            vm.product = response.data;
            console.log('Set vm.product from showUpdate', id);
            });
        } else if(id == null) {
            //populate blank form
            vm.formMode = 'add';
            vm.product = {};
            console.log('Generate blank form');
        }
        //display modal form
        $("#myModal").modal({backdrop: true});
    };

    vm.closeForm = function(){
        $('#myModal').modal('hide');
       $("#myModal").on('hidden.bs.modal', function () {
            vm.formMode = null; //reset form mode
            $route.reload();
    });

    };

    vm.saveProduct = function() {
        console.log('Product/event form save button pressed.');
        var postData =  {
            event: vm.product.event,
            division: vm.product.division,
            level: vm.product.level,
            day: vm.product.day,
            group: vm.product.group,
            numberofplayers: parseInt(vm.product.numberofplayers, 10),
            price: parseInt(vm.product.price, 10),
            description: vm.product.description,
            abbr: vm.product.abbr
        };
        if(vm.productForm.$valid) {
            //save new
            if(vm.formMode === 'add') {
                productDataFactory.postProduct(postData).then(function(response){
                    if (response.status === 201) {
                        console.log('Saved product successfully');
                    }
                }).catch(function(error){
                    console.log(error);
                });
            //update existing
            } else if (vm.formMode === 'update') {
                console.log('Updating ', vm.product._id);
                productDataFactory.productUpdate(vm.product._id, postData).then(function(response){
                    if(response.status == 204) {
                        console.log('Updated product successfully');
                    }
                }).catch(function(error){
                    console.log(error);
                });
            }
            //close form & refresh page
            vm.closeForm();
        //show errors
        } else {
            console.log('Invalid product form');
            vm.isSubmitted = true;
        }
    };

Finally, I set the save and cancel buttons to run the appropriate code:

<button type="submit" class="btn btn-primary"  ng-click="vm.saveProduct()">Save</button>
<button type="button" data-dismiss="modal" class="btn btn-default" ng-click="vm.closeForm()">Cancel</button>

If you have the form submitting to saveProduct() along with these buttons, you'll save the model twice, so pick one or the other.

It should be noted that while I'm using angularjs, I used the regular bootstrap modal instead of angular-ui-bootstrap's modal.  Without using hidden-bs-modal, which allows you to run code AFTER the modal has closed, it just doesn't work refreshing the view with the updated code AND restoring active focus to the main view.


答:
You can use a foreach loop to go over the results...

```<code>foreach ($json->results as $key => $results) {
  ...
  // access to $results->units

  foreach ($results as $x => $item) {
    ...
    // access to $item->value
  }
}
</code>```

Then it won't matter what they key is. Something along those lines.

Title: How to access JSON element using regex or array index in PHP

Body:
You can use a foreach loop to go over the results...

foreach ($json->results as $key => $results) {
  ...
  // access to $results->units

  foreach ($results as $x => $item) {
    ...
    // access to $item->value
  }
}

Then it won't matter what they key is. Something along those lines.


问:
spectacle-code-slide small height
I built a presentation slide with spectacle and I added spectacle-code-slide everything is working but the height of <CodeSlide> is really small. It's not fullscreen compare to this example

Anyone have this problem?

Snippet

```<code> <Deck transition={["zoom", "slide"]} transitionDuration={500} theme={theme}>
    ....
    <CodeSlide
      lang="js"
      code={require("raw-loader!../assets/code")}
      ranges={[
        { loc: [0, 1], title: "Importing React" },
        { loc: [2, 30] }, //TodoList Component
        { loc: [4, 12], title: "Contructor Method" },
        { loc: [13, 25], title: "Render Method" },
        { loc: [14, 17] }, //Creating TodoItem by mapping through the list
        { loc: [18, 24] },
        { loc: [26, 29], title: "addEvent Method" },
        { loc: [31, 36], title: "TodoItem Component" },
        { loc: [37, 72] }, //NewTodoItem Component
        { loc: [39, 47] }, //Contructor Method
        { loc: [48, 51] }, //componentDidMount
        { loc: [52, 63] }, //render
        { loc: [64, 69] }, //onChange
        { loc: [70, 75] }, //onSubmit
        { loc: [77, 78], title: "Rendering component in the DOM" },
      ]}
    />
 </Deck>
</code>```

EDIT: To anyone who is having issues remove all the transitions on your Deck component. Comments for help.

答:
I am working on a presentation myself using this tool and was having this exact issue today. I played around with the slide properties trying to make it work and noticed some weird things going on with transitions.

It is not documented anywhere but apparently for the CodeSlide to work the Deck container should have an empty array on its transition property.

Hope this works for you.

Edit: It also seems like the code slide itself won't work if it has any transitions. Not sure if this has been working this way or if it was broken by an updated depencency.

Title: spectacle-code-slide small height

Body:
I built a presentation slide with spectacle and I added spectacle-code-slide everything is working but the height of <CodeSlide> is really small. It's not fullscreen compare to this example

Anyone have this problem?

Snippet

 <Deck transition={["zoom", "slide"]} transitionDuration={500} theme={theme}>
    ....
    <CodeSlide
      lang="js"
      code={require("raw-loader!../assets/code")}
      ranges={[
        { loc: [0, 1], title: "Importing React" },
        { loc: [2, 30] }, //TodoList Component
        { loc: [4, 12], title: "Contructor Method" },
        { loc: [13, 25], title: "Render Method" },
        { loc: [14, 17] }, //Creating TodoItem by mapping through the list
        { loc: [18, 24] },
        { loc: [26, 29], title: "addEvent Method" },
        { loc: [31, 36], title: "TodoItem Component" },
        { loc: [37, 72] }, //NewTodoItem Component
        { loc: [39, 47] }, //Contructor Method
        { loc: [48, 51] }, //componentDidMount
        { loc: [52, 63] }, //render
        { loc: [64, 69] }, //onChange
        { loc: [70, 75] }, //onSubmit
        { loc: [77, 78], title: "Rendering component in the DOM" },
      ]}
    />
 </Deck>

EDIT: To anyone who is having issues remove all the transitions on your Deck component. Comments for help.


问:
PHP login issue when moving to a different server
I have a very basic log in system, which I have tested on my localhost as well as a free hosting site I use to test my projects and all worked fine.

I have just moved the site to Site Ground as a subdomain and the login has stopped working. The site is still loading content from the database I have created in this location, so I know the issue is not a result from a failure to connect to the database.

There is nothing in the .htaccess file to block a user login either, if it is an issue with moving it to a new server, how would I find a way around this? The page does NOT return any error when attempting to login

login PHP:

```<code><?php

require 'includes/connect.php';

session_start();

if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5 ($_POST['password']);

$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT COUNT(user_id) FROM nathan WHERE username='$username' AND password='$password'";
$q = $pdo->prepare($sql);
$q->execute();

$count = $q->fetchColumn();

if($count == 1){
    $_SESSION['username'] = $username;

    header('Location: admin.php');
}
}

?>
</code>```

DB connection:

```<code><?php
class Database
{
private static $dbName = "some_DB" ;
private static $dbHost = "localhost" ;
private static $username = "some_user";
private static $password = "password123";

private static $cont  = null;

public function __construct() {
    die('Init function is not allowed');
}

public static function connect()
{
   // One connection through whole application
   if ( null == self::$cont )
   {
    try
    {
      self::$cont =  new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$username, self::$password);
    }
    catch(PDOException $e)
    {
      die($e->getMessage());
    }
   }
   return self::$cont;
}

public static function disconnect()
{
    self::$cont = null;
}
}
?>
</code>```

Session PHP:

```<code><?php

session_start();

if (!isset($_SESSION['username'])){
header('Location: login.php');
};
?>
</code>```

答:
As the poster above me said it is definitely because of the cookies, refer to this post for solutions PHP Sessions across sub domains

And you shouldn't store password directly in the database, it is insecure, you should hash it with password_hash(), and then compare it with hash_equals(), on login.

Body:
I have a very basic log in system, which I have tested on my localhost as well as a free hosting site I use to test my projects and all worked fine.

I have just moved the site to Site Ground as a subdomain and the login has stopped working. The site is still loading content from the database I have created in this location, so I know the issue is not a result from a failure to connect to the database.

There is nothing in the .htaccess file to block a user login either, if it is an issue with moving it to a new server, how would I find a way around this? The page does NOT return any error when attempting to login

login PHP:

<?php

require 'includes/connect.php';

session_start();

if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5 ($_POST['password']);

$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT COUNT(user_id) FROM nathan WHERE username='$username' AND password='$password'";
$q = $pdo->prepare($sql);
$q->execute();

$count = $q->fetchColumn();

if($count == 1){
    $_SESSION['username'] = $username;

    header('Location: admin.php');
}
}

?>

DB connection:

<?php
class Database
{
private static $dbName = "some_DB" ;
private static $dbHost = "localhost" ;
private static $username = "some_user";
private static $password = "password123";

private static $cont  = null;

public function __construct() {
    die('Init function is not allowed');
}

public static function connect()
{
   // One connection through whole application
   if ( null == self::$cont )
   {
    try
    {
      self::$cont =  new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$username, self::$password);
    }
    catch(PDOException $e)
    {
      die($e->getMessage());
    }
   }
   return self::$cont;
}

public static function disconnect()
{
    self::$cont = null;
}
}
?>

Session PHP:

<?php

session_start();

if (!isset($_SESSION['username'])){
header('Location: login.php');
};
?>


问:
Json aggregation of data with missing values
I have a simple table of supplements

```<code>create table consumption (
    account bigint not null,
    date date not null,
    supplement text not null check (supplement in ('multiVitamin', 'calMag', 'omega3', 'potassium', 'salt', 'antiOxidant', 'enzymes')),
    quantity integer not null default 0
);
</code>```

And I want to fetch what people have consumed per day. This would be an exmaple of my desired output

```<code>[
    {
        "date" : "2016-01-01",
        "multiVitamin" : 7,
        "calMag" : 0,
        "omega3" : 3,
        "potassium" : 3,
        "salt" : 2,
        "antiOxidant" : 0,
        "enzymes" : 1
    },
    {
        "date" : "2016-01-02",
        "multiVitamin" : 2,
        "calMag" : 1,
        "omega3" : 1,
        "potassium" : 2,
        "salt" : 2,
        "antiOxidant" : 0,
        "enzymes" : 1
    }
]
</code>```

I'm confused how to get those values into a json object and coalesce so that I return 0 if there aren't any supplements entered for that day. So everyday should return all supplements. This is what I have so far but its very far from complete - it's at least fetching for the dates selected though.

```<code>WITH duration_amount AS (
SELECT date_trunc('day', date)::date AS date_group,     json_build_object('quantity', SUM(consumption.quantity) )::jsonb->'quantity' as supplement
FROM consumption
WHERE account = 1667
GROUP BY date_group
)
SELECT DISTINCT date_group, supplement
FROM (
SELECT generate_series(date_trunc('day', '2016-10-20'::date), '2016-10-28'::date, '1 day') AS date_group
) x
LEFT JOIN duration_amount
USING (date_group)
ORDER BY date_group DESC
</code>```

答:
Example data:

```<code>insert into consumption values
(1667, '2016-10-21', 'multiVitamin', 1),
(1667, '2016-10-21', 'calMag', 2),
(1667, '2016-10-22', 'multiVitamin', 3),
(1667, '2016-10-22', 'calMag', 4),
(1667, '2016-10-22', 'omega3', 5);
</code>```

You should prepare a template table containing rows for all possible values. In the example it will contain 14 rows (cross join 2 days with 7 supplements). Next, left join to it your table using coalesce() for missing values:

```<code>select
    date_group::date as date,
    supplement_group as supplement,
    coalesce(quantity, 0) quantity
from generate_series('2016-10-21'::date, '2016-10-22', '1 day') as date_group
cross join (
    values
        ('multiVitamin'), ('calMag'), ('omega3'),
        ('potassium'), ('salt'), ('antiOxidant'), ('enzymes')
    ) as supplements(supplement_group)
left join consumption
    on date_group = date
    and supplement = supplement_group
    and account = 1667;

    date    |  supplement  | quantity
------------+--------------+----------
 2016-10-21 | multiVitamin |        1
 2016-10-21 | calMag       |        2
 2016-10-21 | omega3       |        0
 2016-10-21 | potassium    |        0
 2016-10-21 | salt         |        0
 2016-10-21 | antiOxidant  |        0
 2016-10-21 | enzymes      |        0
 2016-10-22 | multiVitamin |        3
 2016-10-22 | calMag       |        4
 2016-10-22 | omega3       |        5
 2016-10-22 | potassium    |        0
 2016-10-22 | salt         |        0
 2016-10-22 | antiOxidant  |        0
 2016-10-22 | enzymes      |        0
(14 rows)
</code>```

The result can be easily aggregated to jsonb, see the full example here.

Body:
I have a simple table of supplements

create table consumption (
    account bigint not null,
    date date not null,
    supplement text not null check (supplement in ('multiVitamin', 'calMag', 'omega3', 'potassium', 'salt', 'antiOxidant', 'enzymes')),
    quantity integer not null default 0
);

And I want to fetch what people have consumed per day. This would be an exmaple of my desired output

[
    {
        "date" : "2016-01-01",
        "multiVitamin" : 7,
        "calMag" : 0,
        "omega3" : 3,
        "potassium" : 3,
        "salt" : 2,
        "antiOxidant" : 0,
        "enzymes" : 1
    },
    {
        "date" : "2016-01-02",
        "multiVitamin" : 2,
        "calMag" : 1,
        "omega3" : 1,
        "potassium" : 2,
        "salt" : 2,
        "antiOxidant" : 0,
        "enzymes" : 1
    }
]

I'm confused how to get those values into a json object and coalesce so that I return 0 if there aren't any supplements entered for that day. So everyday should return all supplements. This is what I have so far but its very far from complete - it's at least fetching for the dates selected though.

WITH duration_amount AS (
SELECT date_trunc('day', date)::date AS date_group,     json_build_object('quantity', SUM(consumption.quantity) )::jsonb->'quantity' as supplement
FROM consumption
WHERE account = 1667
GROUP BY date_group
)
SELECT DISTINCT date_group, supplement
FROM (
SELECT generate_series(date_trunc('day', '2016-10-20'::date), '2016-10-28'::date, '1 day') AS date_group
) x
LEFT JOIN duration_amount
USING (date_group)
ORDER BY date_group DESC

Body:
Example data:

insert into consumption values
(1667, '2016-10-21', 'multiVitamin', 1),
(1667, '2016-10-21', 'calMag', 2),
(1667, '2016-10-22', 'multiVitamin', 3),
(1667, '2016-10-22', 'calMag', 4),
(1667, '2016-10-22', 'omega3', 5);

You should prepare a template table containing rows for all possible values. In the example it will contain 14 rows (cross join 2 days with 7 supplements). Next, left join to it your table using coalesce() for missing values:

select
    date_group::date as date,
    supplement_group as supplement,
    coalesce(quantity, 0) quantity
from generate_series('2016-10-21'::date, '2016-10-22', '1 day') as date_group
cross join (
    values
        ('multiVitamin'), ('calMag'), ('omega3'),
        ('potassium'), ('salt'), ('antiOxidant'), ('enzymes')
    ) as supplements(supplement_group)
left join consumption
    on date_group = date
    and supplement = supplement_group
    and account = 1667;

    date    |  supplement  | quantity
------------+--------------+----------
 2016-10-21 | multiVitamin |        1
 2016-10-21 | calMag       |        2
 2016-10-21 | omega3       |        0
 2016-10-21 | potassium    |        0
 2016-10-21 | salt         |        0
 2016-10-21 | antiOxidant  |        0
 2016-10-21 | enzymes      |        0
 2016-10-22 | multiVitamin |        3
 2016-10-22 | calMag       |        4
 2016-10-22 | omega3       |        5
 2016-10-22 | potassium    |        0
 2016-10-22 | salt         |        0
 2016-10-22 | antiOxidant  |        0
 2016-10-22 | enzymes      |        0
(14 rows)

The result can be easily aggregated to jsonb, see the full example here.


问:
Sending mail with attachments programmatically in ASP.NET
I am dynamically generating a number of different types of files based upon a GridView in ASP.NET - an Excel spreadsheet and a HTML file. I am doing so using this code (this is just for the Excel spreadsheet):

```<code>  Response.Clear();
  Response.AddHeader("content-disposition", "attachment;filename=InvoiceSummary" + Request.QueryString["id"] + ".xls");
  Response.Charset = "";

  Response.ContentType = "application/vnd.xls";
  System.IO.StringWriter stringWrite = new System.IO.StringWriter();
  System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
  contents.RenderControl(htmlWrite);
  //GridView1.RenderControl(htmlWrite);
  Response.Write(stringWrite.ToString());
  Response.End();
</code>```

I would like to give users the options of emailing the generated file as an attachment to either an email address they specify or one linked with their account on the database. But I don't want the user to have to save the file, then attach it in a form - I'd like to automatically attach the generated file. Is this possible, and how easy is it?

Of course, I'll be using the System.Net.Mail class to send mail...if it's possible anyway!

答:
```<code>    protected void btnSend_OnClick(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();
        byte[] data = new byte[1024];
        MemoryStream stream = new MemoryStream(data);
        Attachment attach = new Attachment(stream, "Attachment file name");
        mail.Attachments.Add(attach);
        new SmtpClient().Send(mail);
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am dynamically generating a number of different types of files based upon a GridView in ASP.NET - an Excel spreadsheet and a HTML file. I am doing so using this code (this is just for the Excel spreadsheet):

  Response.Clear();
  Response.AddHeader("content-disposition", "attachment;filename=InvoiceSummary" + Request.QueryString["id"] + ".xls");
  Response.Charset = "";

  Response.ContentType = "application/vnd.xls";
  System.IO.StringWriter stringWrite = new System.IO.StringWriter();
  System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
  contents.RenderControl(htmlWrite);
  //GridView1.RenderControl(htmlWrite);
  Response.Write(stringWrite.ToString());
  Response.End();

I would like to give users the options of emailing the generated file as an attachment to either an email address they specify or one linked with their account on the database. But I don't want the user to have to save the file, then attach it in a form - I'd like to automatically attach the generated file. Is this possible, and how easy is it?

Of course, I'll be using the System.Net.Mail class to send mail...if it's possible anyway!