答:
Being NumPy tagged and since input is mentioned as list/array, you can simply use builtin numpy.insert -

```<code>np.insert(original_list, insertion_indices, new_numbers)
</code>```

To roll out the theory as a custom made one (mostly for performance), we could use mask, like so -

```<code>def insert_numbers(original_list,insertion_indices, new_numbers):
    # Length of output array
    n = len(original_list)+len(insertion_indices)

    # Setup mask array to selecrt between new and old numbers
    mask = np.ones(n,dtype=bool)
    mask[insertion_indices+np.arange(len(insertion_indices))] = 0

    # Setup output array for assigning values from old and new lists/arrays
    # by using mask and inverted mask version
    out = np.empty(n,dtype=int)
    out[mask] = original_list
    out[~mask] = new_numbers
    return out
</code>```

For list output, append .tolist().

Sample run -

```<code>In [83]: original_list = [0, 1, 2, 3, 4, 5, 6, 7]
    ...: insertion_indices = [1, 4, 5]
    ...: new_numbers = [8, 9, 10]
    ...:

In [85]: np.insert(original_list, insertion_indices, new_numbers)
Out[85]: array([ 0,  8,  1,  2,  3,  9,  4, 10,  5,  6,  7])

In [86]: np.insert(original_list, insertion_indices, new_numbers).tolist()
Out[86]: [0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7]
</code>```

Runtime test on a 10000x scaled dataset -

```<code>In [184]: original_list = range(70000)
     ...: insertion_indices = np.sort(np.random.choice(len(original_list), 30000, replace=0)).tolist()
     ...: new_numbers = np.random.randint(0,10, len(insertion_indices)).tolist()
     ...: out1 = np.insert(original_list, insertion_indices, new_numbers)
     ...: out2 = insert_numbers(original_list, insertion_indices, new_numbers)
     ...: print np.allclose(out1, out2)
True

In [185]: %timeit np.insert(original_list, insertion_indices, new_numbers)
100 loops, best of 3: 5.37 ms per loop

In [186]: %timeit insert_numbers(original_list, insertion_indices, new_numbers)
100 loops, best of 3: 4.8 ms per loop
</code>```

Let's test out with arrays as inputs -

```<code>In [190]: original_list = np.arange(70000)
     ...: insertion_indices = np.sort(np.random.choice(len(original_list), 30000, replace=0))
     ...: new_numbers = np.random.randint(0,10, len(insertion_indices))
     ...: out1 = np.insert(original_list, insertion_indices, new_numbers)
     ...: out2 = insert_numbers(original_list, insertion_indices, new_numbers)
     ...: print np.allclose(out1, out2)
True

In [191]: %timeit np.insert(original_list, insertion_indices, new_numbers)
1000 loops, best of 3: 1.48 ms per loop

In [192]: %timeit insert_numbers(original_list, insertion_indices, new_numbers)
1000 loops, best of 3: 1.07 ms per loop
</code>```

The performance just shoots up, because there's no runtime overhead on conversion to list.

Title: In place insertion into list (or array)

Body:
I'm running a script in Python, where I need to insert new numbers into an array  (or list) at certain index locations. The problem is that obviously as I insert new numbers, the index locations are invalidated. Is there a clever way to insert the new values at the index locations all at once? Or is the only solution to increment the index number (first value of the pair) as I add?

Sample test code snippets:

original_list = [0, 1, 2, 3, 4, 5, 6, 7]
insertion_indices = [1, 4, 5]
new_numbers = [8, 9, 10]
pairs = [(insertion_indices[i], new_numbers[i]) for i in range(len(insertion_indices))]

for pair in pairs:
    original_list.insert(pair[0], pair[1])

Results in:

[0, 8, 1, 2, 9, 10, 3, 4, 5, 6, 7]

whereas I want:

[0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7]

Body:
Being NumPy tagged and since input is mentioned as list/array, you can simply use builtin numpy.insert -

np.insert(original_list, insertion_indices, new_numbers)

To roll out the theory as a custom made one (mostly for performance), we could use mask, like so -

def insert_numbers(original_list,insertion_indices, new_numbers):
    # Length of output array
    n = len(original_list)+len(insertion_indices)

    # Setup mask array to selecrt between new and old numbers
    mask = np.ones(n,dtype=bool)
    mask[insertion_indices+np.arange(len(insertion_indices))] = 0

    # Setup output array for assigning values from old and new lists/arrays
    # by using mask and inverted mask version
    out = np.empty(n,dtype=int)
    out[mask] = original_list
    out[~mask] = new_numbers
    return out

For list output, append .tolist().

Sample run -

In [83]: original_list = [0, 1, 2, 3, 4, 5, 6, 7]
    ...: insertion_indices = [1, 4, 5]
    ...: new_numbers = [8, 9, 10]
    ...:

In [85]: np.insert(original_list, insertion_indices, new_numbers)
Out[85]: array([ 0,  8,  1,  2,  3,  9,  4, 10,  5,  6,  7])

In [86]: np.insert(original_list, insertion_indices, new_numbers).tolist()
Out[86]: [0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7]

Runtime test on a 10000x scaled dataset -

In [184]: original_list = range(70000)
     ...: insertion_indices = np.sort(np.random.choice(len(original_list), 30000, replace=0)).tolist()
     ...: new_numbers = np.random.randint(0,10, len(insertion_indices)).tolist()
     ...: out1 = np.insert(original_list, insertion_indices, new_numbers)
     ...: out2 = insert_numbers(original_list, insertion_indices, new_numbers)
     ...: print np.allclose(out1, out2)
True

In [185]: %timeit np.insert(original_list, insertion_indices, new_numbers)
100 loops, best of 3: 5.37 ms per loop

In [186]: %timeit insert_numbers(original_list, insertion_indices, new_numbers)
100 loops, best of 3: 4.8 ms per loop

Let's test out with arrays as inputs -

In [190]: original_list = np.arange(70000)
     ...: insertion_indices = np.sort(np.random.choice(len(original_list), 30000, replace=0))
     ...: new_numbers = np.random.randint(0,10, len(insertion_indices))
     ...: out1 = np.insert(original_list, insertion_indices, new_numbers)
     ...: out2 = insert_numbers(original_list, insertion_indices, new_numbers)
     ...: print np.allclose(out1, out2)
True

In [191]: %timeit np.insert(original_list, insertion_indices, new_numbers)
1000 loops, best of 3: 1.48 ms per loop

In [192]: %timeit insert_numbers(original_list, insertion_indices, new_numbers)
1000 loops, best of 3: 1.07 ms per loop

The performance just shoots up, because there's no runtime overhead on conversion to list.


来源: stackexchange

问:
How we can connect firefox os emulator or simulator to appium tool?
I'm not able to get the list of connected devices using ADB commands..In Appium its possible connect firefox os emulator or simulator.</p>

答:
Connecting FirefoxOS device should be an easy thing, check you did it right.

But I doubt if Appium still supports Firefox OS, as Mozilla stopped Firefox OS support back in 2016.
However it is still in the list of platformName capability, so you may try it out but use old server version (back in the days of 2014) when it was supported.

ContentLicense: CC BY-SA 3.0


问:
Create a PDF file on the fly and stream it while it is not yet finished?
We want to merge a lot of PDF files into one big file and send it to the client. However, the resources on our production server are very restricted, so merging all files in memory first and then sending the finished PDF file results in our script being killed because it exhausts its available memory.

The only solution (besides getting a better server, obviously) would be starting to stream the PDF file before it is fully created to bypass the memory limit.

However I wonder if that is even possible. Can PDF files be streamed before they're fully created? Or doesn't the PDF file format allow streaming unfinished files because some headers or whatever have to be set after the full contents are certain?

If it is possible, which PDF library supports creating a file as a stream? Most libraries that I know of (like TCPDF) seem to create the full file in memory and then in the end output this finished result somewhere (i. e. via the $tcpdf->Output() method).

答:
The PDF file format is entirely able to be streamed. There's certainly nothing that'll prevent it anyway.

As an example, we recently had a customer that required reading a single page over a HTTP connection to a remote PDF, without downloading or reading the whole PDF. We're able to do this by making many small HTTP requests for specific content within the PDF. We use the trailer at the end of the PDF and the cross reference table to find the required content without having to parse the whole PDF.

If I understand your problem, it looks like your current library you're using loads each PDF in memory before creating or streaming out the merged document.

If we look at this problem a different way, the better solution would be for the PDF library to only take references to the PDFs to be merged, then when the merged PDF is being created or streamed, pull in the content and resources from the PDFs to be merged, as-and-when required.

I'm not sure how many PHP libraries there are that can do this as I'm not too up-to-date with PHP, but I know there are probably a few C/C++ libraries that may be able to do this. I understand PHP can use extensions to call these libraries. Only downside is that they'll likely have commercial licenses.

Disclaimer: I work for the Mako SDK R&D group, hence why I know for sure there are some libraries which will do this. :)


问:
Alternative for OpenID?
Is there any alternative for OpenID,what i means is a site which provide our details fully, and we can log in to a site with that ID?

Update

suppose think that i am developing a site which have openID integration, i will have only a username not so much details,thats why i am asking

答:
IndieAuth is a "spiritual successor" to OpenID, with a very similar workflow for the end-user. It also supports identity delegation, a unique feature of OpenID 2.0.

But, it does not provide or enforce extra details from the user.

ContentLicense: CC BY-SA 2.5

Title: Alternative for OpenID?


问:
Undefined property: GuzzleHttp\Exception\ConnectException::$status
I keep getting this error when trying to get the status of the request.

This is my code

```<code>ExpenseRepository.php

<?php

namespace Expensetrim\Api\v1\Repositories;

use Auth;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Expensetrim\Models\Company;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ExpenseRepository
{
    private $api_url;

    const API_GET = 'GET';
    const API_POST = 'POST';
    const API_PUT = 'PUT';

    function __construct()
    {
        $this->api_url = "http://xxx-xxx-xxx/api/v1/";
    }

    public function api_call($method, $uri, $request = NULL)
{
    try {

        $url=$this->api_url.$uri;
        $client = new Client(['base_uri' => $this->api_url]);
        $response = ($request) ? $client->request($method, $uri, $request) : $client->request($method, $uri);
    }
    catch (RequestException $e) {
        return $e;
    }
    return $this->formatResponseBody($response);
}

public static function formatResponseBody($response)
{
    $body = $response->getBody(true)->getContents();
    return json_decode($body);
}

public function addExpenseType($data)
{
    $uri = 'expense/types/add';
    $response = $this->api_call(self::API_POST, $uri, ['form_params' => $data]);
    return $response;

}
</code>```

Also CompanyRepository.php

```<code>public function addExpenseType($company_id, $data)
    {
        $data['company_id'] = $company_id;
        $expense = new ExpenseRepository;
        $done = $expense->addExpenseType($data);
        if($done->status == 'success') {
          return true;
        }

        return true;
    }
</code>```

I need to check if the status is a success or not but keep getting this error: Undefined property: GuzzleHttp\Exception\ConnectException::$status.
Please what am i doing wrong?

答:
There is an exception thrown at this line:

```<code>catch (RequestException $e) {
    return $e;
}
</code>```

and you are returning the exception. The return value of the method addExpenseType is actually an exception thrown by Guzzle.

throw the exception to see the error.
change your code to

```<code>catch (RequestException $e) {
        throw $e;
    }
</code>```

Body:
I keep getting this error when trying to get the status of the request.

This is my code

ExpenseRepository.php

<?php

namespace Expensetrim\Api\v1\Repositories;

use Auth;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Expensetrim\Models\Company;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ExpenseRepository
{
    private $api_url;

    const API_GET = 'GET';
    const API_POST = 'POST';
    const API_PUT = 'PUT';

    function __construct()
    {
        $this->api_url = "http://xxx-xxx-xxx/api/v1/";
    }

    public function api_call($method, $uri, $request = NULL)
{
    try {

        $url=$this->api_url.$uri;
        $client = new Client(['base_uri' => $this->api_url]);
        $response = ($request) ? $client->request($method, $uri, $request) : $client->request($method, $uri);
    }
    catch (RequestException $e) {
        return $e;
    }
    return $this->formatResponseBody($response);
}

public static function formatResponseBody($response)
{
    $body = $response->getBody(true)->getContents();
    return json_decode($body);
}

public function addExpenseType($data)
{
    $uri = 'expense/types/add';
    $response = $this->api_call(self::API_POST, $uri, ['form_params' => $data]);
    return $response;

}

Also CompanyRepository.php

public function addExpenseType($company_id, $data)
    {
        $data['company_id'] = $company_id;
        $expense = new ExpenseRepository;
        $done = $expense->addExpenseType($data);
        if($done->status == 'success') {
          return true;
        }

        return true;
    }

I need to check if the status is a success or not but keep getting this error: Undefined property: GuzzleHttp\Exception\ConnectException::$status.
Please what am i doing wrong?

Body:
There is an exception thrown at this line:

catch (RequestException $e) {
    return $e;
}

and you are returning the exception. The return value of the method addExpenseType is actually an exception thrown by Guzzle.

throw the exception to see the error.
change your code to

catch (RequestException $e) {
        throw $e;
    }


问:
Python to transform rows to columns with delimeter, data contain *** need to delimit according to that
```<code>**START
IB    1107518415
BI    Paperback
BC    JHBC
CO    United Kingdom
ED    Alvarez, R. Michael
**
IB   0415836662
BI   Paperback
AU   Pituch, Keenan A.
AU    Stevens, James P.
BC   JHBC
CO   United Kingdom
EI    6 Rev ed
</code>```

Please find above sample data, i need under IB->"1107518415" as first row and "0415836662" as second row and so on, please help me.

答:
Not entirely clear what you want. If you want a list with the values in all the IB lines, try

```<code>res = [line.split(maxsplit=1)[1] for line in data.splitlines() if line.startswith("IB")]
# ['1107518415', '0415836662']
</code>```

with data being a multi-line string holding your data. (Can also be a file, of course.) If you want to split the lines into groups separated by those **, you can use a for loop, appending to a nested list instead.

```<code>res = []
for line in data.splitlines():
    if line.startswith("**"):
        res.append([])
    else:
        res[-1].append(line.split(maxsplit=1)[1])
# [['1107518415', 'Paperback', 'JHBC', 'United Kingdom', 'Alvarez, R. Michael'],
#  ['0415836662', 'Paperback', 'Pituch, Keenan A.', 'Stevens, James P.', 'JHBC', 'United Kingdom', '6 Rev ed']]
</code>```

Or as a "one-liner" using itertools.groupby, same result:

```<code>res = [[line.split(maxsplit=1)[1] for line in group]
       for key, group in itertools.groupby(data.splitlines(),
                                           key=lambda line: line.startswith("**"))
       if key == False]
</code>```

Body:
**START
IB    1107518415
BI    Paperback
BC    JHBC
CO    United Kingdom
ED    Alvarez, R. Michael
**
IB   0415836662
BI   Paperback
AU   Pituch, Keenan A.
AU    Stevens, James P.
BC   JHBC
CO   United Kingdom
EI    6 Rev ed

Please find above sample data, i need under IB->"1107518415" as first row and "0415836662" as second row and so on, please help me.

Body:
Not entirely clear what you want. If you want a list with the values in all the IB lines, try

res = [line.split(maxsplit=1)[1] for line in data.splitlines() if line.startswith("IB")]
# ['1107518415', '0415836662']

with data being a multi-line string holding your data. (Can also be a file, of course.) If you want to split the lines into groups separated by those **, you can use a for loop, appending to a nested list instead.

res = []
for line in data.splitlines():
    if line.startswith("**"):
        res.append([])
    else:
        res[-1].append(line.split(maxsplit=1)[1])
# [['1107518415', 'Paperback', 'JHBC', 'United Kingdom', 'Alvarez, R. Michael'],
#  ['0415836662', 'Paperback', 'Pituch, Keenan A.', 'Stevens, James P.', 'JHBC', 'United Kingdom', '6 Rev ed']]

Or as a "one-liner" using itertools.groupby, same result:

res = [[line.split(maxsplit=1)[1] for line in group]
       for key, group in itertools.groupby(data.splitlines(),
                                           key=lambda line: line.startswith("**"))
       if key == False]


问:
Reducing spaces between the character python
I am trying to print the staircase pattern. I have written the code as follows:

```<code>def StairCase(n):
    for i in range(1, n + 1):
        stair_array = []
        j = 1
        while (j <= n):
            if (j <= i):
                stair_array.append('#')
            else:
                stair_array.append(' ')
            j = j + 1

        reversed_array = list(reversed(stair_array))
        for element in reversed_array:
            print "{}".format(element),
        print

_n = int(raw_input().strip("\n"))
StairCase(_n)
</code>```

I got the output as:

```<code>6
          #
        # #
      # # #
    # # # #
  # # # # #
# # # # # #
</code>```

The expected output is:

```<code>6
     #
    ##
   ###
  ####
 #####
######
</code>```

As one can see my output is with spaces and is not acceptable as per original pattern. Kindly help.

答:
If you insist:

```<code>def StairCase(n):
    for i in range(1, n + 1):
        stair_array = []
        j = 1
        while (j <= n):
            if (j <= i):
                stair_array.append('#')
            else:
                stair_array.append(' ')
            j = j + 1

        reversed_array = list(reversed(stair_array))
        print ''.join(reversed_array)
</code>```

but a much simpler way is to just:

```<code>def StairCase_new(n):
    for i in range(1, n + 1):
        print ' '*(n-i) + '#'*i
</code>```

Body:
I am trying to print the staircase pattern. I have written the code as follows:

def StairCase(n):
    for i in range(1, n + 1):
        stair_array = []
        j = 1
        while (j <= n):
            if (j <= i):
                stair_array.append('#')
            else:
                stair_array.append(' ')
            j = j + 1

        reversed_array = list(reversed(stair_array))
        for element in reversed_array:
            print "{}".format(element),
        print

_n = int(raw_input().strip("\n"))
StairCase(_n)

I got the output as:

6
          #
        # #
      # # #
    # # # #
  # # # # #
# # # # # #

The expected output is:

6
     #
    ##
   ###
  ####
 #####
######

As one can see my output is with spaces and is not acceptable as per original pattern. Kindly help.

Body:
If you insist:

def StairCase(n):
    for i in range(1, n + 1):
        stair_array = []
        j = 1
        while (j <= n):
            if (j <= i):
                stair_array.append('#')
            else:
                stair_array.append(' ')
            j = j + 1

        reversed_array = list(reversed(stair_array))
        print ''.join(reversed_array)

but a much simpler way is to just:

def StairCase_new(n):
    for i in range(1, n + 1):
        print ' '*(n-i) + '#'*i


问:
Tax rounding issue when having multiple tax classes in woocommerce
I have a problem with rounding of tax class amounts in WooCommerce 3.2.3 on Wordpress 4.8.3.

The sums of each of the 2 tax classes are both correctly displayed with 2 decimal points when displayed in the cart and checkout page.

However, during calculation of the cart total sum, the tax class sums are added together in the tax subtotal sum using 4 decimal point values and then rounded up.

This can cause a 0,01 rounding error, as explained in the example below, where if you add the item subtotal together with the displayed tax class sums, you get 221,61 €, and not the displayed 221,62 €.

Example (prices without tax, no shipping involved):

Product XXX (belong to 19% tax class):  161,28 €

Product YYY (belong to 7% tax class): 27,75 €

Product items subtotal = 189,03 €

MwSt. 19%     30,64 €

MwSt. 7%     1,94 €

Cart sum total: 221,62 €

The question:

How can I force WooCommerce to use 2 decimal points for the tax class sums when adding them together for calculating the cart total sum?

Setup:

we use the plugin "woocommerce germanized" version 1.9.5. Problem exist with and without it enabled.

we use a shipping calculator plugin, and the problem exist with and without it.

disabled all plugins to no effect.

tested with twentyseventeen theme, with same result.

the shop is in Germany, and sells to companies and to private customers, hence the prices are entered without tax.

products are associated with either the 19% or 7% tax class.

currency is EUR using 2 decimals.

"display tax totals" setting is set to "itemized".

prices are entered without tax.

prices are shown without tax.

I understand the reasoning behind using 4dp precision in the calculations, but it is not needed in our use case.

I added some debug output in the WC code, and saw that the individual tax class sums in the above example are stored with 4 decimals:

MwSt. 19%     30,6432

MwSt. 7%     1,9425

The tax subtotal here is 32,5857 which is rounded up to 32,59 € during cart sum total calculation, as opposed to 32,58 €, causing the 0,01 difference.

In my search for a solution to this issue, I found a lot of different tax calculation issues, but no exactly similar use case.

I have attempted to modify the WooCommerce code, but I have been unsuccessful in finding the right spot in WooCommerce where I can set / hard code the precision-calculation to use 2dp rather than 4dp, but that might not have been the most ideal solution anyway.

Note: If I change the "display tax total" setting to "Total" instead of "Itemized", then the displayed tax subtotal is 32,59 €.

In this setup the total cart sum 221,62 € equals the sum of the listed subtotals, but the customer requires the taxes to be shown itemized.

Sorry for the long description. In my recent experience, it appears to be necessary in order to properly explain tax calculation related issues.

Does anyone have a suggestion to resolve this issue?

Many thanks for your advice and time!

Muskat

答:
First you have to search how the tax are calculated in Woocommerce… If you go in WooCommerce WC_Cart  class code, you will see that WC_Tax class is responsible for this…

In the source code WC_Tax the methods that make calculations are (with the corresponding available filter hooks to alter that calculations):

calc_tax() with available filter hook woocommerce_calc_tax.

calc_shipping_tax() with available filter hook woocommerce_calc_shipping_tax.

round() with available filter hook woocommerce_tax_round.

calc_inclusive_tax() with available filter hook woocommerce_price_inc_tax_amount.

calc_exclusive_tax() with available filter hook woocommerce_price_ex_tax_amount.

and may be some others…

Here is an example to change the round() behavior to return rounding to .5 cents:

```<code>add_filter( 'woocommerce_tax_round', 'euro_5cent_rounding' );
function euro_5cent_rounding( $in ) {
    return round( $in / 5, 2 ) * 5;
}
</code>```

Code goes in function.php file of your active child theme or active theme (or also in any plugin file).

As your problem is very specific and difficult to reproduce, you will have to find which hook is going to make the trick to solve your issue…

Body:
First you have to search how the tax are calculated in Woocommerce… If you go in WooCommerce WC_Cart  class code, you will see that WC_Tax class is responsible for this…

In the source code WC_Tax the methods that make calculations are (with the corresponding available filter hooks to alter that calculations):

calc_tax() with available filter hook woocommerce_calc_tax.

calc_shipping_tax() with available filter hook woocommerce_calc_shipping_tax.

round() with available filter hook woocommerce_tax_round.

calc_inclusive_tax() with available filter hook woocommerce_price_inc_tax_amount.

calc_exclusive_tax() with available filter hook woocommerce_price_ex_tax_amount.

and may be some others…

Here is an example to change the round() behavior to return rounding to .5 cents:

add_filter( 'woocommerce_tax_round', 'euro_5cent_rounding' );
function euro_5cent_rounding( $in ) {
    return round( $in / 5, 2 ) * 5;
}

Code goes in function.php file of your active child theme or active theme (or also in any plugin file).

As your problem is very specific and difficult to reproduce, you will have to find which hook is going to make the trick to solve your issue…


问:
javascript confirm dialog issues
I have some troubles with confirm dialog not working with Firefox, but working with Chrome.

html code looks like this:

```<code><input type="submit" name="Odjava" value="Remove selected link" onclick="return odjava(somelink,'Do you really want to remove ')"/>
</code>```

javascript code looks like this:

```<code>function odjava(link,text)
{
    if(link=="" || text=="")
        return false;
    return confirm(text + link + " ?");
}
</code>```

With Chrome, everything is ok - onClick generates "confirm" dialog, and if user answer with "yes", form is submitted, otherwise it's not. Firefox doesen't show "confirm" dialog, it just submits the form.

Why's that? What am i doing wrong?

****EDIT:
I got it! I just changed my javascript to look like this:

```<code>function odjava(text)
{
    var linkovi = document.getElementById('linkovi');
    link = linkovi.options[linkovi.selectedIndex].text
    if(link=="" || text=="")
        return false;
    return confirm(text + link + " ?");
}
</code>```

and it's working. It turn out that Chrome can find element in document even without document.getElementById, FF can't (won't)!

答:
Never seen this before, but did a bit of googling, and came up with the following:
http://www.tek-tips.com/viewthread.cfm?qid=1431250&page=10

Seems a little hokey to me, but thought I would point it out anyway. Looks like they recommend putting an extra "return false;" in the onclick after the function call.

Title: javascript confirm dialog issues

Body:
I have some troubles with confirm dialog not working with Firefox, but working with Chrome.

html code looks like this:

<input type="submit" name="Odjava" value="Remove selected link" onclick="return odjava(somelink,'Do you really want to remove ')"/>

javascript code looks like this:

function odjava(link,text)
{
    if(link=="" || text=="")
        return false;
    return confirm(text + link + " ?");
}

With Chrome, everything is ok - onClick generates "confirm" dialog, and if user answer with "yes", form is submitted, otherwise it's not. Firefox doesen't show "confirm" dialog, it just submits the form.

Why's that? What am i doing wrong?

****EDIT:
I got it! I just changed my javascript to look like this:

function odjava(text)
{
    var linkovi = document.getElementById('linkovi');
    link = linkovi.options[linkovi.selectedIndex].text
    if(link=="" || text=="")
        return false;
    return confirm(text + link + " ?");
}

and it's working. It turn out that Chrome can find element in document even without document.getElementById, FF can't (won't)!


问:
Inline email image shown in production not development
I am sending html emails through the action mailer and something strange occur: an inline image does appear on the email sent from the production deploy but not from local develomment.

professionnel_mailer.rb

```<code>class ProfessionnelMailer < ApplicationMailer

    layout 'professionnelmailer'

    def notification(professionnel)
        attachments.inline['image200.png'] = File.read("#{Rails.root}/app/assets/images/image200.png")
        @professionnel = professionnel
        mail(to: @professionnel.email, subject: "You have received a notification !")
    end
end
</code>```

notification.html.erb

```<code><%= image_tag(attachments['image200.png'].url)%>
<h1>Hello <%= @professionnel.first_name %> !</h1>
</code>```

Of course image200.png is present locally and remotely. And email is received in both cases, then my Amazon AWS SES setup is corrrect in both environments.. Not very sure where it breaks..

答:
Basically, these images have a localhost:3000 url in them when it's in development mode, while it will have the server's IP or the domain name on production.

To fix this issue, and since you're using Amazon SES, add the needed image to an S3 bucket, and read the image from that bucket directly in your email,

This will help you see the image whether it's from development or production.

Body:
I am sending html emails through the action mailer and something strange occur: an inline image does appear on the email sent from the production deploy but not from local develomment.

professionnel_mailer.rb

class ProfessionnelMailer < ApplicationMailer

    layout 'professionnelmailer'

    def notification(professionnel)
        attachments.inline['image200.png'] = File.read("#{Rails.root}/app/assets/images/image200.png")
        @professionnel = professionnel
        mail(to: @professionnel.email, subject: "You have received a notification !")
    end
end

notification.html.erb

<%= image_tag(attachments['image200.png'].url)%>

Hello <%= @professionnel.first_name %> !

Of course image200.png is present locally and remotely. And email is received in both cases, then my Amazon AWS SES setup is corrrect in both environments.. Not very sure where it breaks..


问:
android.content.res.Resources$NotFoundException: Resource ID #0x7f0a003b type #0x5 is not valid
I am trying to use the Linphone library for Android. I have installed all the libraries as specified and when I am trying to run the project, I am getting the below error.

```<code>  Process: org.linphone, PID: 13440
   java.lang.RuntimeException: Unable to start activity ComponentInfo{org.linphone/org.linphone.LinphoneLauncherActivity}: android.content.res.Resources$NotFoundException: Resource ID #0x7f0a003b type #0x5 is not valid
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
       at android.app.ActivityThread.access$800(ActivityThread.java:151)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:135)
       at android.app.ActivityThread.main(ActivityThread.java:5254)
       at java.lang.reflect.Method.invoke(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
    Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f0a003b type #0x5 is not valid
       at android.content.res.Resources.getBoolean(Resources.java:999)
       at org.linphone.LinphoneLauncherActivity.onCreate(LinphoneLauncherActivity.java:50)
       at android.app.Activity.performCreate(Activity.java:5990)
       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
       at android.app.ActivityThread.access$800(ActivityThread.java:151)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:135)
       at android.app.ActivityThread.main(ActivityThread.java:5254)
       at java.lang.reflect.Method.invoke(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>```

Please let me know how can I resolve this as my work is stuck because of this.
Thanks in advance !!.

答:
Regarding this ans:

Android Resources$NotFoundException: Resource ID #0x7f030027

You can check your R file for Resources$NotFoundException: Resource ID #0x7f030027. It'll tell you which resource was creating problem. As an alternative sollution I think you might have setText or any content just an int.And as you know here compiler will look for corresponding resource value. So, just concat an empty string there as ""

Body:
I am trying to use the Linphone library for Android. I have installed all the libraries as specified and when I am trying to run the project, I am getting the below error.

  Process: org.linphone, PID: 13440
   java.lang.RuntimeException: Unable to start activity ComponentInfo{org.linphone/org.linphone.LinphoneLauncherActivity}: android.content.res.Resources$NotFoundException: Resource ID #0x7f0a003b type #0x5 is not valid
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
       at android.app.ActivityThread.access$800(ActivityThread.java:151)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:135)
       at android.app.ActivityThread.main(ActivityThread.java:5254)
       at java.lang.reflect.Method.invoke(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
    Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f0a003b type #0x5 is not valid
       at android.content.res.Resources.getBoolean(Resources.java:999)
       at org.linphone.LinphoneLauncherActivity.onCreate(LinphoneLauncherActivity.java:50)
       at android.app.Activity.performCreate(Activity.java:5990)
       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
       at android.app.ActivityThread.access$800(ActivityThread.java:151)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:135)
       at android.app.ActivityThread.main(ActivityThread.java:5254)
       at java.lang.reflect.Method.invoke(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Please let me know how can I resolve this as my work is stuck because of this.
Thanks in advance !!.


问:
Validation in Constructor and Constructor Violation
I was doing some reading here(1,2) and I was wondering if making sure the parameters provided during initialization are correct, violates the guideline that constructors shouldn't do work.

For example (Python):

```<code>class Employee:
    def __init__(self, empFirstname, empLastname, empEmail):

        self._validate_employee(empFirstname, "First Name")
        self._validate_employee(empLastname, "Last name")
        self._validate_employee(empEmail, "Email")
        self._validate_email(empEmail, "Email")

        self.empFirstname = empFirstname
        self.empLastname = empLastname
        self.empEmail = empEmail

    @property
    def email(self):
        return self.empEmail

    def _validate_employee(self, parameter, error_message):
        if not parameter:
            raise TypeError("{0} {1}" .format(error_message, "is missing"))

    def _validate_email(self, email, parameter):
        if "@" not in email or "." not in email:
            raise TypeError("{0} {1}" .format(parameter, " is invalid"))
</code>```

In my example, I check to make sure the first and last names aren't blank and that the email is valid. Did I violate the guideline?

Update:
I'm not asking if it should throw, I'm asking if I'm violating the guideline that constructors shouldn't do work when it validates my parameters.

答:
The requirement to provide arguments that satisfy certain conditions is a part of Design by Contract, namely it corresponds to preconditions. The client (of a constructor in your case) should guarantee that the arguments are as expected. If this is not the case, the supplier (the constructor in your case) cannot ensure the resulting object is in a valid state after the constructor returns. In languages that support Design by Contract natively, one would associate a class invariant stating that the names are not empty and the email address follows the naming convention. This could be achieved only when the arguments passed to the constructor are valid.

The conditions you mention would be written as preconditions and could be turned on or off depending on the policy established in the software development process. When enabled, they are checked on entry to the constructor, before its real body is executed. From this point of view, your code is not doing any additional work, but makes sure the arguments are correct. After program verification that ensures the preconditions are satisfied all the time, or extensive testing that gives the feeling that the preconditions are not violated by the client, they can be disabled, thus removing any "additional work".

To summarize:

the "additional code" in your examples are preconditions

preconditions are part of software contracts

the checks of the contracts can be enabled or disabled depending on the adopted policy, it is safe to disable them as soon as all clients guarantee the preconditions are never violated, thus removing any "additional work" from the constructor (or any other software component)

Body:
I was doing some reading here(1,2) and I was wondering if making sure the parameters provided during initialization are correct, violates the guideline that constructors shouldn't do work.

For example (Python):

class Employee:
    def __init__(self, empFirstname, empLastname, empEmail):

        self._validate_employee(empFirstname, "First Name")
        self._validate_employee(empLastname, "Last name")
        self._validate_employee(empEmail, "Email")
        self._validate_email(empEmail, "Email")

        self.empFirstname = empFirstname
        self.empLastname = empLastname
        self.empEmail = empEmail

    @property
    def email(self):
        return self.empEmail

    def _validate_employee(self, parameter, error_message):
        if not parameter:
            raise TypeError("{0} {1}" .format(error_message, "is missing"))

    def _validate_email(self, email, parameter):
        if "@" not in email or "." not in email:
            raise TypeError("{0} {1}" .format(parameter, " is invalid"))

In my example, I check to make sure the first and last names aren't blank and that the email is valid. Did I violate the guideline?

Update:
I'm not asking if it should throw, I'm asking if I'm violating the guideline that constructors shouldn't do work when it validates my parameters.


问:
Entering login info with AppleScript
I am using AppleScript to enter login information and after the script enters the information into the password field and a "keystroke return" is performed the form tells me my password is incorrect even though I am sure that I am passing the correct password in my script.

Does anyone know why this is occurring?

```<code>tell application "Safari"
    activate
    open location "https://thewebsite.com"
end tell

delay 10
clickClassName("login", 0)
delay 2

tell application "Safari"
    tell application "System Events" to tell process "Safari"
        keystroke tab
        keystroke "MyPassword"
        keystroke return
    end tell
end tell
</code>```

答:
```<code>tell application "Safari"
    activate
    open location "https://thewebsite.com"
end tell

delay 10
clickClassName("login", 0)
delay 2

tell application "Safari"
    tell application "System Events" to tell process "Safari"
        keystroke tab
delay 0.2
        keystroke "MyPassword"
0.5 -- you need the delay because it does not type instantly and the password is probably cut short.
        keystroke return
    end tell
end tell
</code>```

Title: Entering login info with AppleScript

Body:
I am using AppleScript to enter login information and after the script enters the information into the password field and a "keystroke return" is performed the form tells me my password is incorrect even though I am sure that I am passing the correct password in my script.

Does anyone know why this is occurring?

tell application "Safari"
    activate
    open location "https://thewebsite.com"
end tell

delay 10
clickClassName("login", 0)
delay 2

tell application "Safari"
    tell application "System Events" to tell process "Safari"
        keystroke tab
        keystroke "MyPassword"
        keystroke return
    end tell
end tell


问:
Does OpenGL care if I work with large numbers?
For example, I could relate the positions where I draw my entities to the screen before sending them to OpenGL - or: I give OpenGL the direct coordinates, relative to the game world, which are of course in a much larger scale.

Is drawing with large vertex coordinates slow?

答:
The floating point pipeline has constant speed on operations, regardless of the size of the operands.

The only danger is getting abnormally large or small numbers where the error gets out of hand and you end up with subnormal numbers.


问:
save data in codeigniter with array
I have an array recieved by the code

```<code>$logged_in=$this->session->userdata('logged_in');
</code>```

In this I have an element gid. I want to set value in this session with gid=2. How can I set this ??

答:
use set_userdata() function as follows

```<code>$this->session->set_userdata('gid', 1);
</code>```

if you want to set more than one value in session, use array method as follows

```<code>$session_array = array('gid' => 2, 'name' => 'john') ;
$this->session->set_userdata($session_array);
</code>```

Title: save data in codeigniter with array

Body:
I have an array recieved by the code

$logged_in=$this->session->userdata('logged_in');

In this I have an element gid. I want to set value in this session with gid=2. How can I set this ??

Body:
use set_userdata() function as follows

$this->session->set_userdata('gid', 1);

if you want to set more than one value in session, use array method as follows

$session_array = array('gid' => 2, 'name' => 'john') ;
$this->session->set_userdata($session_array);


问:
Assigning a number to a name without enumerating and printing a name based on that number
What I am trying to do is using n as the number of characters in list "Roles", print out the number n and the role next to it. Is there a way I can later, depending on the number I ask for, get a character that is "assigned"  to that number. I tried using enumerate, but I wasn't able to call the enumerated roles later with if/while/for or if I wanted to print them. I also tried using dictionary but you can't use append for dictionary. If it's possible to call the enumerated Roles, I would like to know how I can do that, if not I go back to my original question. Here's the code I'm using:

```<code>import random
Roles = ["One", "Two", "Three", "Four"]
SheriffList = []
Alive = []
for n in range(0, len(Roles)):
    random.shuffle(Roles)
    Role = random.choice(Roles)
    Alive.append(Roles.pop(Roles.index(Role)))
    Role2 = n,Role
    print(Role2)
    SheriffList.append(Role2)
    n += 1
    if n == len(Roles):
        random.shuffle(Alive)
        random.choice(Alive)

print(SheriffList)
   [(0, 'One'), (1, 'Four'), (2, 'Three'), (3, 'Two')]
k = int(input("Choose a number:"))
</code>```

Now I want k (The number I choose), to be able to print me back the role that was assigned to it For example if I assign 1 to "k", it will send me 'Four'. I'm sorry if the question was already asked before, I just wasn't able to find what I needed.

答:
A common way to solve this is to use an indirection table:

```<code>ind = [0, 3, 2, 1]
</code>```

then to get the role corresponding at number k, you just use:

```<code>cur_role = Role[ind[k]]
</code>```

Simple, clean and no need for loops...

Body:
What I am trying to do is using n as the number of characters in list "Roles", print out the number n and the role next to it. Is there a way I can later, depending on the number I ask for, get a character that is "assigned"  to that number. I tried using enumerate, but I wasn't able to call the enumerated roles later with if/while/for or if I wanted to print them. I also tried using dictionary but you can't use append for dictionary. If it's possible to call the enumerated Roles, I would like to know how I can do that, if not I go back to my original question. Here's the code I'm using:

import random
Roles = ["One", "Two", "Three", "Four"]
SheriffList = []
Alive = []
for n in range(0, len(Roles)):
    random.shuffle(Roles)
    Role = random.choice(Roles)
    Alive.append(Roles.pop(Roles.index(Role)))
    Role2 = n,Role
    print(Role2)
    SheriffList.append(Role2)
    n += 1
    if n == len(Roles):
        random.shuffle(Alive)
        random.choice(Alive)

print(SheriffList)
   [(0, 'One'), (1, 'Four'), (2, 'Three'), (3, 'Two')]
k = int(input("Choose a number:"))

Now I want k (The number I choose), to be able to print me back the role that was assigned to it For example if I assign 1 to "k", it will send me 'Four'. I'm sorry if the question was already asked before, I just wasn't able to find what I needed.

Body:
A common way to solve this is to use an indirection table:

ind = [0, 3, 2, 1]

then to get the role corresponding at number k, you just use:

cur_role = Role[ind[k]]

Simple, clean and no need for loops...


问:
AWS create tags for instances launched in ECS Auto Scaling Group
I am trying to create tags for EC2 instances from userdata script after the instance is launched using a cloudformation. The ec2 instances are part of an ECS AutoScaling group. The ECS ASG cloudformation is creating the the instances in the given VPCZoneIdentifiers. The tags I need on these instances depend on the AZ they are launched into, so they are kind of dynamic. I haven't been able to find any way to make this, i.e. look at the AZ the ECS ASG will launch the current instance in and add appropriate tag, happen in the cloudformation. So my second idea is to add tags from inside the userdata script. I am basically using the instance metadata and create-tags tool inside cloudinit script to add tags. I am able to get the instance-id during cloudinit but when trying to create tags on the instance id, I get instance id does not exist error. Am not sure what's happening here.

Does AWS block operations on instances which running the userdata script? Any suggestions how I can add the tags? I have some custom code in the end of userdata script which depends on these tags. Any help/suggestions are much appreciated.

答:
As per my knowledge, you can add the tags by getting it from created instance in cloud formation itself.

Please try statement(YAML)

Ex. AvailabilityZone: !GetAtt '<Your_instance>.AvailabilityZone'


答:
This will shuffle the Roles list and give you one of them based on a number from 0 to 3 given by the user.</p>

```<code>import random

Roles = ['One','Two','Three','Four']

random.shuffle(Roles)

k = int(input('choose a number:'))

print(Roles[k])
</code>```

Title: Assigning a number to a name without enumerating and printing a name based on that number

Body:
This will shuffle the Roles list and give you one of them based on a number from 0 to 3 given by the user.

import random

Roles = ['One','Two','Three','Four']

random.shuffle(Roles)

k = int(input('choose a number:'))

print(Roles[k])


问:
How to mock babel plugin in Jest test?
I am using a babel plugin which provides a function called myHelper which is used (but not imported since it is provided as a babel plugin) inside a component I want to test.

How do I "globally" mock myHelper with Jest?

答:
I would let those components accept a myHelper property to optionally mock myHelper method provided by babel. By default the property would point to the original myHelper method:

```<code>class MyComponent extends Component {
  constructor() {
      // Use myHelper function like:
      this.props.myHelper();
  }

  return (
    <div>...</div>
  );
}

MyComponent.propTypes = {
  myHelper: PropTypes.func.isRequired,
};

MyComponent.defaultProps = {
  // set by default to babel-provided method
  myHelper: myHelper,
};
</code>```

..and that in your tests using, for example, enzyme:

```<code>const myHelperMock = jest.fn();
const wrapper = shallow(
    <MyComponent
      myHelper={myHelperMock}
    />
);
</code>```

Title: How to mock babel plugin in Jest test?

Body:
I would let those components accept a myHelper property to optionally mock myHelper method provided by babel. By default the property would point to the original myHelper method:

class MyComponent extends Component {
  constructor() {
      // Use myHelper function like:
      this.props.myHelper();
  }

  return (
    <div>...</div>
  );
}

MyComponent.propTypes = {
  myHelper: PropTypes.func.isRequired,
};

MyComponent.defaultProps = {
  // set by default to babel-provided method
  myHelper: myHelper,
};

..and that in your tests using, for example, enzyme:

const myHelperMock = jest.fn();
const wrapper = shallow(
    <MyComponent
      myHelper={myHelperMock}
    />
);


问:
Cytoscape layout - No such layout cola found
I am using Cytoscape on Angular 2 project with Typescript and wanted to use Cola layout. Hence I added the dependency to my project using npm. Since I am using Angular 2 with Typescript I have added the js module first to the angular-cli.json file then to the index.html file. After that in my NetworkComponent , which is the angular component I am using to display the graph, I am importing the library as follows:

declare var cola:any;

Then I am trying to use the layout as follows:

```<code>   this.cyto = cytoscape({
            container: document.getElementById("graph"),
            elements: this.graph.elements,
            style: res.json()
            });
    this.cyto.layout({name: "cola"});
</code>```

The graph doesn't display and I get the following error in the console:

Can not apply layout: No such layout 'cola' found; did you include its
  JS file?

I can use the concentric layout and the graph displays but I get the same error for other layout extensions such as cose-bilkent and springy.

How can I import cola library and use it as my graph layout? What might be wrong here?

答: It was a simple fix. It turns out I forgot to add a reference to cola.js file in index.html which is required by cytoscape-cola.js. I thought only using cytoscape-cola.js was enough, but after adding the cola js file it is working properly.

Body:
I am using Cytoscape on Angular 2 project with Typescript and wanted to use Cola layout. Hence I added the dependency to my project using npm. Since I am using Angular 2 with Typescript I have added the js module first to the angular-cli.json file then to the index.html file. After that in my NetworkComponent , which is the angular component I am using to display the graph, I am importing the library as follows:

declare var cola:any;

Then I am trying to use the layout as follows:

   this.cyto = cytoscape({
            container: document.getElementById("graph"),
            elements: this.graph.elements,
            style: res.json()
            });
    this.cyto.layout({name: "cola"});

The graph doesn't display and I get the following error in the console:

Can not apply layout: No such layout 'cola' found; did you include its
  JS file?

I can use the concentric layout and the graph displays but I get the same error for other layout extensions such as cose-bilkent and springy.

How can I import cola library and use it as my graph layout? What might be wrong here?


问:
PHP session settings ignored on Apache production?
I'm having trouble with setting up PHP sessions for a project of ours and would like to ask for help. The goal was to prolong shopping cart data validity (stored in sessions) by increasing session lifetime.

The issue is, no matter what I do, no matter the settings, the session file gets deleted after a few hours.

I set it up in the virtual host definition like so:

```<code><VirtualHost *:80>
    ...
    php_value    memory_limit            128M
    php_value    upload_max_filesize     20M
    php_value    post_max_size           20M
    php_value    session.cookie_lifetime 2592000
    php_value    session.gc_maxlifetime  2592000
    php_value    session.save_path       "/data/hosting/myproject/sessions"
    ...
</VirtualHost>
</code>```

Even moved the session storage to a dedicated directory to avoid any possible system upkeep clearing the sessions, without success.

On a development enviroment (Wamp 3.0.6 64b) this works just fine and as intended, not so much on the production server. Also, when I attempt to double-check the set up values using the PHP ini_get() function (http://php.net/manual/en/function.ini-get.php), both development and production enviroments return the correct, required values.

The project is stored on a VPS on which we use these:

PHP 5.5.38

Apache/2.2.15 (Unix)

CentOS Linux release 6.0 (Final)

A noteworthy observation – it's not just this project, the same setup fails when applied to another project as well.

Thanks in advance for any tip or idea that would help me solve this one, it would be much appreciated.

Disclaimer: Please do not comment on the solution itself, I am well aware of it not being optimal. It's an old project and it's simply not viable to rewrite the shopping cart data storing method.

答:
Well..
1) Verify that in code there isn't a ini_set that fiddles with the gc. Since that would override any setting you put in apache.
2) Verify that there is no .htaccess doing the same thing as 1, since it would obviously also trash the settings.
3) Set the divisor/probability (might help)
4) Enforce set_cookie parameters as well, it might not be the server messing up but the clients that are getting default session cookie lifetimes and thus after 30 minutes would kill the cookie. </p>

Body:
I'm having trouble with setting up PHP sessions for a project of ours and would like to ask for help. The goal was to prolong shopping cart data validity (stored in sessions) by increasing session lifetime.

The issue is, no matter what I do, no matter the settings, the session file gets deleted after a few hours.

I set it up in the virtual host definition like so:

<VirtualHost *:80>
    ...
    php_value    memory_limit            128M
    php_value    upload_max_filesize     20M
    php_value    post_max_size           20M
    php_value    session.cookie_lifetime 2592000
    php_value    session.gc_maxlifetime  2592000
    php_value    session.save_path       "/data/hosting/myproject/sessions"
    ...
</VirtualHost>

Even moved the session storage to a dedicated directory to avoid any possible system upkeep clearing the sessions, without success.

On a development enviroment (Wamp 3.0.6 64b) this works just fine and as intended, not so much on the production server. Also, when I attempt to double-check the set up values using the PHP ini_get() function (http://php.net/manual/en/function.ini-get.php), both development and production enviroments return the correct, required values.

The project is stored on a VPS on which we use these:

PHP 5.5.38

Apache/2.2.15 (Unix)

CentOS Linux release 6.0 (Final)

A noteworthy observation – it's not just this project, the same setup fails when applied to another project as well.

Thanks in advance for any tip or idea that would help me solve this one, it would be much appreciated.

Disclaimer: Please do not comment on the solution itself, I am well aware of it not being optimal. It's an old project and it's simply not viable to rewrite the shopping cart data storing method.


问:
read line by line with awk and parse variables
I have a script that read log files and parse the data to insert them to mysql table..

My script looks like

```<code>while read x;do
var=$(echo ${x}|cut -d+ -f1)
var2=$(echo ${x}|cut -d_ -f3)
...
echo "$var,$var2,.." >> mysql.infile
done<logfile
</code>```

The Problem is that log files are thousands of lines and taking hours....

I read that awk is better, I tried, but don't know the syntax to parse the variables...

EDIT:
inputs are structure firewall logs so they are pretty large files like

@timestamp $HOST reason="idle Timeout" source-address="x.x.x.x"
  source-port="19219" destination-address="x.x.x.x"
  destination-port="53" service-name="dns-udp" application="DNS"....

So I'm using a lot of grep for ~60 variables e.g

```<code>sourceaddress=$(echo ${x}|grep -P -o '.{0,0}
source-address=\".{0,50}'|cut -d\" -f2)
</code>```

if you think perl will be better I'm open to suggestions and maybe a hint how to script it...

答:
The perl script below might help:

```<code>perl -ane '/^[^+]*/;printf "%s,",$&;/^([^_]*_){2}([^_]*){1ntf "%s\n",$+' logfile
</code>```

Since, $& can result in performance penalty, you could also use the /p modifier like below :

```<code>perl -ane  '/^[^+]*/p;printf "%s,",${^MATCH};/^([^_]*_){2}([^_]*){1}_.*/;printf "%s\n",$+' logfile
</code>```

For more on perl regex matching  refer to [ PerlDoc ]

ContentLicense: CC BY-SA 4.0

Body:
I have a script that read log files and parse the data to insert them to mysql table..

My script looks like

while read x;do
var=$(echo ${x}|cut -d+ -f1)
var2=$(echo ${x}|cut -d_ -f3)
...
echo "$var,$var2,.." >> mysql.infile
done<logfile

The Problem is that log files are thousands of lines and taking hours....

I read that awk is better, I tried, but don't know the syntax to parse the variables...

EDIT:
inputs are structure firewall logs so they are pretty large files like

@timestamp $HOST reason="idle Timeout" source-address="x.x.x.x"
  source-port="19219" destination-address="x.x.x.x"
  destination-port="53" service-name="dns-udp" application="DNS"....

So I'm using a lot of grep for ~60 variables e.g

sourceaddress=$(echo ${x}|grep -P -o '.{0,0}
source-address=\".{0,50}'|cut -d\" -f2)

if you think perl will be better I'm open to suggestions and maybe a hint how to script it...

Body:
The perl script below might help:

perl -ane '/^[^+]*/;printf "%s,",$&;/^([^_]*_){2}([^_]*){1ntf "%s\n",$+' logfile

Since, $& can result in performance penalty, you could also use the /p modifier like below :

perl -ane  '/^[^+]*/p;printf "%s,",${^MATCH};/^([^_]*_){2}([^_]*){1}_.*/;printf "%s\n",$+' logfile

For more on perl regex matching  refer to [ PerlDoc ]


问:
Yii2 rest API return page html instead of json response
I have created a modules say Api using gii in my yii2-advanced application and API working with access token in header Authorization, but in case of wrong access token or no access token the API return 401 page html.

How to handle error/exception in yii2 API so that I can format response data in json?

答:
In your config/main.php response component:

```<code>'response' => [
  'format' => yii\web\Response::FORMAT_JSON
]
</code>```

Body:
In your config/main.php response component:

'response' => [
  'format' => yii\web\Response::FORMAT_JSON
]


问:
How to run docker-compose on remote host?
I have compose file locally. How to run bundle of containers on remote host like docker-compose up -d with DOCKER_HOST=<some ip>?

答:
Given that you are able to log in on the remote machine, another approach to running docker-compose commands on that machine is to use SSH.

Copy your docker-compose.yml file over to the remote host via scp, run the docker-compose commands over SSH, finally clean up by removing the file again.
This could look as follows:

```<code>scp ./docker-compose.yml SomeUser@RemoteHost:/tmp/docker-compose.yml
ssh SomeUser@RemoteHost "docker-compose -f /tmp/docker-compose.yml up"
ssh SomeUser@RemoteHost "rm -f /tmp/docker-compose.yml"
</code>```

You could even make it shorter and omit the sending and removing of the docker-compose.yml file by using the -f - option to docker-compose which will expect the docker-compose.yml file to be piped from stdin. Just pipe its content to the SSH command:

```<code>cat docker-compose.yml | ssh SomeUser@RemoteHost "docker-compose -f - up"
</code>```

If you use environment variable substitution in your docker-compose.yml file, the above-mentioned command will not replace them with your local values on the remote host and your commands might fail due to the variables being unset. To overcome this, the envsubst utility can be used to replace the variables with your local values in memory before piping the content to the SSH command:

```<code>envsubst < docker-compose.yml | ssh SomeUser@RemoteHost "docker-compose up"
</code>```

Body:
Given that you are able to log in on the remote machine, another approach to running docker-compose commands on that machine is to use SSH.

Copy your docker-compose.yml file over to the remote host via scp, run the docker-compose commands over SSH, finally clean up by removing the file again.
This could look as follows:

scp ./docker-compose.yml SomeUser@RemoteHost:/tmp/docker-compose.yml
ssh SomeUser@RemoteHost "docker-compose -f /tmp/docker-compose.yml up"
ssh SomeUser@RemoteHost "rm -f /tmp/docker-compose.yml"

You could even make it shorter and omit the sending and removing of the docker-compose.yml file by using the -f - option to docker-compose which will expect the docker-compose.yml file to be piped from stdin. Just pipe its content to the SSH command:

cat docker-compose.yml | ssh SomeUser@RemoteHost "docker-compose -f - up"

If you use environment variable substitution in your docker-compose.yml file, the above-mentioned command will not replace them with your local values on the remote host and your commands might fail due to the variables being unset. To overcome this, the envsubst utility can be used to replace the variables with your local values in memory before piping the content to the SSH command:

envsubst < docker-compose.yml | ssh SomeUser@RemoteHost "docker-compose up"


答:
Is somelink defined safely in both Firefox and Chrome?

When I try your code it works successfully in both FF and Chrome if someLink is defined, and fails to work as you describe in both if it is not defined.

Title: javascript confirm dialog issues

Body:
I have some troubles with confirm dialog not working with Firefox, but working with Chrome.

html code looks like this:

<input type="submit" name="Odjava" value="Remove selected link" onclick="return odjava(somelink,'Do you really want to remove ')"/>

javascript code looks like this:

function odjava(link,text)
{
    if(link=="" || text=="")
        return false;
    return confirm(text + link + " ?");
}

With Chrome, everything is ok - onClick generates "confirm" dialog, and if user answer with "yes", form is submitted, otherwise it's not. Firefox doesen't show "confirm" dialog, it just submits the form.

Why's that? What am i doing wrong?

****EDIT:
I got it! I just changed my javascript to look like this:

function odjava(text)
{
    var linkovi = document.getElementById('linkovi');
    link = linkovi.options[linkovi.selectedIndex].text
    if(link=="" || text=="")
        return false;
    return confirm(text + link + " ?");
}

and it's working. It turn out that Chrome can find element in document even without document.getElementById, FF can't (won't)!


问:
How can I increase the scrollspeed of the div?
I am trying to make a sort of parallax webdesign. My question is, if someone knows how I can make the red div move faster. I think its in the formule but dont know sure. Maybe someone knows?

Here is my code: http://jsfiddle.net/PvVdq/

```<code>$(document).ready(function () {
var $horizontal = $('#horizontal');

$(window).scroll(function () {
    var s = $(this).scrollTop(),
        d = $(document).height(),
        c = $(this).height();

    scrollPercent = (s / (d - c));

    var position = (scrollPercent * ($(document).width() - $horizontal.width()));

    $horizontal.css({
        'left': position
    });
});
</code>```

});

答:
Yuo need to play with your scrollPercent , if you want it go faster :

```<code>    scrollPercent = (s / (d - c) * 2);//twice fatser
</code>```

or even faster :

```<code>    scrollPercent = (s / (d - c) * 3);//3 times fatser
</code>```

http://jsfiddle.net/PvVdq/1448/

Body:
I am trying to make a sort of parallax webdesign. My question is, if someone knows how I can make the red div move faster. I think its in the formule but dont know sure. Maybe someone knows?

Here is my code: http://jsfiddle.net/PvVdq/

$(document).ready(function () {
var $horizontal = $('#horizontal');

$(window).scroll(function () {
    var s = $(this).scrollTop(),
        d = $(document).height(),
        c = $(this).height();

    scrollPercent = (s / (d - c));

    var position = (scrollPercent * ($(document).width() - $horizontal.width()));

    $horizontal.css({
        'left': position
    });
});

});

Body:
Yuo need to play with your scrollPercent , if you want it go faster :

    scrollPercent = (s / (d - c) * 2);//twice fatser

or even faster :

    scrollPercent = (s / (d - c) * 3);//3 times fatser

http://jsfiddle.net/PvVdq/1448/


问:
Showing part of the ImageView which is cover by another ImageView
I have a Framelayout, where the first element is an ImageView which height and width is match parent and let the id is A. Second element is also an ImageView which height and width also match parent and let the id is B. Third element is a View which height and width is 100 dp and can be move to the whole screen and let the id is C. I am using transparent color in background C, so inside C we should see B, because B is above A. But I want to show A in inside C , how can I do that?</p>

答:
If I understand your question correctly, you basically want to have the intersection of View C and View B transparent to see View A which is behind both of them.

In that case it might be enough to get visible rectangle of view C:

```<code>Rect rect = new Rect();
viewC.getGlobalVisibleRect(rect);
</code>```

And then you can draw this rectangle as transparent mask on view B, which will therefore allow you to see View A that is behind view B. You can achieve it by overriding onDraw method of view B.

```<code>Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas)
    canvas.drawRect(rect, paint);
}
</code>```

This will achieve something similar to this:

You should also not forget to disable HW acceleration for view on which you are drawing (View B in this case) and also tell the view that you are going to draw to it manually:

```<code>setWillNotDraw(false);
setLayerType(LAYER_TYPE_HARDWARE, null)
</code>```

Further explanation and example can be found here:
Android canvas: draw transparent circle on image

Body:
If I understand your question correctly, you basically want to have the intersection of View C and View B transparent to see View A which is behind both of them.

In that case it might be enough to get visible rectangle of view C:

Rect rect = new Rect();
viewC.getGlobalVisibleRect(rect);

And then you can draw this rectangle as transparent mask on view B, which will therefore allow you to see View A that is behind view B. You can achieve it by overriding onDraw method of view B.

Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas)
    canvas.drawRect(rect, paint);
}

This will achieve something similar to this:

You should also not forget to disable HW acceleration for view on which you are drawing (View B in this case) and also tell the view that you are going to draw to it manually:

setWillNotDraw(false);
setLayerType(LAYER_TYPE_HARDWARE, null)

Further explanation and example can be found here:
Android canvas: draw transparent circle on image


问:
How to Disable Double Click on the Header of a DataGridView
I want to do some stuff while double click on a Gridview (Row) not single cell. Means on a double click event handler not on MouseDoubleClick event. But i am not able to disable the header column and row double click event..and also want to load data to combobox(ComboBox is on the same form) when i double click on the GridView Row. Help me Please..!!!</p>

```<code>private void gvLoadAllData_DoubleClick(object sender, EventArgs e)
{
    if()
    {
        //Do Something
    }
}
</code>```

答:
Just do this:

```<code>private void itemsList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    if(e.RowIndex>-1)
        HereIsNotHeader();
}
</code>```

and bind it to the CellDoubleClick event

Body:
I want to do some stuff while double click on a Gridview (Row) not single cell. Means on a double click event handler not on MouseDoubleClick event. But i am not able to disable the header column and row double click event..and also want to load data to combobox(ComboBox is on the same form) when i double click on the GridView Row. Help me Please..!!!

private void gvLoadAllData_DoubleClick(object sender, EventArgs e)
{
    if()
    {
        //Do Something
    }
}

Body:
Just do this:

private void itemsList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    if(e.RowIndex>-1)
        HereIsNotHeader();
}

and bind it to the CellDoubleClick event


问:
Img path issues reactjs
I am developing a react app. I am loading datas from a module like that

```<code>const results = [
{
    'home': 'fbc',
    'home_score': '74',
    'visitor': 'jda',
    'visitor_score': '69',
    'home_logo': 'jda_logo.png'
}]
</code>```

What I am trying to do is loading images from the data (home_logo). But I don't know how to use relative path with React.
I wanted to see what is the path when I load a picture with

```<code>import jda from './img/jda_logo.png';
</code>```

And I am surprised the path is static/media/jda_logo.e596d19c.png Someone can explain to me what is the e596d19c that's been added ?
And is it possible from me to load images with relative path that I am loading from my data ?

答:
In my opinion react is returning you the reference to the cached/copied media. Usually this is a result of the behaviour of builders/compilers/bundlers such as webpack. Essentially the image is the same but it is copied to a different location, used at runtime.

I believe you would like to take a look at this and this as they're handling questions quite close to yours.

Title: Img path issues reactjs

Body:
I am developing a react app. I am loading datas from a module like that

const results = [
{
    'home': 'fbc',
    'home_score': '74',
    'visitor': 'jda',
    'visitor_score': '69',
    'home_logo': 'jda_logo.png'
}]

What I am trying to do is loading images from the data (home_logo). But I don't know how to use relative path with React.
I wanted to see what is the path when I load a picture with

import jda from './img/jda_logo.png';

And I am surprised the path is static/media/jda_logo.e596d19c.png Someone can explain to me what is the e596d19c that's been added ?
And is it possible from me to load images with relative path that I am loading from my data ?


问:
Android Google maps - custom tile overlay
Been working on a custom tile overlay implementation for an android app.
I'm having trouble with threading the image downloads in the background.

Quick overview:
I have a class (MapOverlay) that extends Overlay. The draw method basically calculates the images (bitmaps) needed and the x,y position to draw them on the screen. I then have an AsyncTask that loops through each tiles and download the images if it doesn't exist on the storage card (local caching) then once the AsyncTask has completed I then loop through the images and draw them to the canvas object that is passed into the draw method of the MapOverlay. But the bitmaps are never getting drawn.

I have done some rudimentary debugging by logging the width and the height of the canvas element at the time the AsyncTask completes but it is returning 0 for them so I'm guessing that the canvas object is no longer available to the code running in AsyncTask's onPostExecute() after the draw method has completed

Without the threading I had this working pretty well, except for the "freezing" while panning while the image downloading blocks the UI thread. Now I'm totally suck trying to get threading to work

答: Have you tried calling postInvalidate() when the AsyncTask  done downloading? That way the call in MapView.draw() will get and draw the downloaded overlay (that is if your caching system works).</p>


问:
Laravel redirecting when accessing post route directly
I do a post request to a route calculate-cars and display an other view with some data I query based on the data I entered in the form I do the post request from, but I want to redirect to the homepage when someone access this route directly.

Unfortunately I keep getting this error:

Symfony \ Component \ HttpKernel \ Exception \
  MethodNotAllowedHttpException No message

my route:

Route::post('calculate-cars', 'CarsController@calculateCars');

I know I get this error because I access a post route directly but I try this in my controller method but I still get the same error:

```<code>if (!$request->isMethod('post')) {
    return redirect()->to('/');
}
</code>```

答:
Add another route

```<code>Route::get('calculate-cars', function () {
    return redirect()->to('/');
});
</code>```

If you'r using Laravel 5.5, you can do it like this:

```<code>Route::redirect('/calculate-cars', '/', 301);
</code>```

UPDATE:
The method Route::redirect will redirect the post route as well, it's not useful in your case.

Just put this in your routes/web.php file:

```<code>Route::get('calculate-cars', function () {
    return redirect()->to('/');
});
</code>```

Body:
I do a post request to a route calculate-cars and display an other view with some data I query based on the data I entered in the form I do the post request from, but I want to redirect to the homepage when someone access this route directly.

Unfortunately I keep getting this error:

Symfony \ Component \ HttpKernel \ Exception \
  MethodNotAllowedHttpException No message

my route:

Route::post('calculate-cars', 'CarsController@calculateCars');

I know I get this error because I access a post route directly but I try this in my controller method but I still get the same error:

if (!$request->isMethod('post')) {
    return redirect()->to('/');
}

Body:
Add another route

Route::get('calculate-cars', function () {
    return redirect()->to('/');
});

If you'r using Laravel 5.5, you can do it like this:

Route::redirect('/calculate-cars', '/', 301);

UPDATE:
The method Route::redirect will redirect the post route as well, it's not useful in your case.

Just put this in your routes/web.php file:

Route::get('calculate-cars', function () {
    return redirect()->to('/');
});


问:
C++ comparing Char to Strings
I'm trying to loop through a word but only vowels are working for some reason. The other type prints out the amount of words in total. Please excuse my poor choise of words mixed with Swedish and English.</p>

```<code>#include <iostream>

using namespace std;

int main()
{
    int vo = 0;
    int ko = 0;

    char vocals[7]
    {
        'A','O','U','E','I','Y'
    };

    char konsonanter[19]
    {
        'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','X','Z'
    };

    string word = "Toysoldier";

    for(int i = 0; i < word.length(); i++)
    {
        for(int v = 0; v < vocals[v]; v++)
        {
            if(vocals[v] == word[i])
                vo++;
        }

        for(int k = 0; k < konsonanter[k]; k++)
        {
            if(konsonanter[k] == word[i])
                ko++;
        }
    }

    cout << "Konsonanter = " << ko << " Vokaler = " << vo << endl;
}
</code>```

答:
You got your loop condition wrong.
Instead of v < vocals[v] you probably meant to write v < 7 as there are 7 vocals in your array.

Writing v < vocals[v] is not an error as v is initialized to zero while the expression vocals[v] is a char which can also be used in array subscripts ('A' is translated to 65, 'E' to 69 and so on).

The same problem exists in the loop for consonants.

Title: C++ comparing Char to Strings

Body:
I'm trying to loop through a word but only vowels are working for some reason. The other type prints out the amount of words in total. Please excuse my poor choise of words mixed with Swedish and English.

#include <iostream>

using namespace std;

int main()
{
    int vo = 0;
    int ko = 0;

    char vocals[7]
    {
        'A','O','U','E','I','Y'
    };

    char konsonanter[19]
    {
        'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','X','Z'
    };

    string word = "Toysoldier";

    for(int i = 0; i < word.length(); i++)
    {
        for(int v = 0; v < vocals[v]; v++)
        {
            if(vocals[v] == word[i])
                vo++;
        }

        for(int k = 0; k < konsonanter[k]; k++)
        {
            if(konsonanter[k] == word[i])
                ko++;
        }
    }

    cout << "Konsonanter = " << ko << " Vokaler = " << vo << endl;
}


问:
Provide border if div has overflow text
What would be the best way to implement a design that want div-containers be provides with a border, if the content of the div causes vertical scroll of the div?

CSS

```<code>div {
  max-height: 100px;
  overflow-y: auto;
  // if content exceeds 100 px show border
  border: solid 1px;
}
</code>```

HTML

```<code><div>
   // Text ..
</div>
</code>```

答:
I am assuming there is some kind of event that changes or determines the content of that div.
In my humble opinion, you can not achieve that using html/css alone. You would have to use JavaScript.
https://jsfiddle.net/4u2Lurt3/

Here is a simple example of how to do that. You may need to "re-wire" a bit differently to get the exact behavior you wanted

```<code><div id="myDiv">
    Hello
</div>

<button onclick="addText()">
Click to change div
</button>
</code>```

And

```<code>function checkWidth() {
    var div = document.getElementById('myDiv');
          if(div.offsetWidth > 100) {
            div.style.border = "1px solid black"
          }
        }

function addText() {
    var div = document.getElementById('myDiv');
  div.style.width="250px";
  div.innerText = "AAAAAAAAAAAAA VVVVVVEERRRRY LOOOONNNNGGG TEEEEEXXXXXTT";
  checkWidth();
}
</code>```

Title: Provide border if div has overflow text

Body:
What would be the best way to implement a design that want div-containers be provides with a border, if the content of the div causes vertical scroll of the div?

CSS

div {
  max-height: 100px;
  overflow-y: auto;
  // if content exceeds 100 px show border
  border: solid 1px;
}

HTML

   // Text ..

Body:
I am assuming there is some kind of event that changes or determines the content of that div.
In my humble opinion, you can not achieve that using html/css alone. You would have to use JavaScript.
https://jsfiddle.net/4u2Lurt3/

Here is a simple example of how to do that. You may need to "re-wire" a bit differently to get the exact behavior you wanted

<div id="myDiv">
    Hello
</div>

<button onclick="addText()">
Click to change div
</button>

And

function checkWidth() {
    var div = document.getElementById('myDiv');
          if(div.offsetWidth > 100) {
            div.style.border = "1px solid black"
          }
        }

function addText() {
    var div = document.getElementById('myDiv');
  div.style.width="250px";
  div.innerText = "AAAAAAAAAAAAA VVVVVVEERRRRY LOOOONNNNGGG TEEEEEXXXXXTT";
  checkWidth();
}


答:
but I want to redirect to the homepage when someone access this route
  directly.

That means when a user does a GET

Your route Route::post('calculate-cars', 'CarsController@calculateCars');

only allows POST

So change it to

Route::any('calculate-cars', 'CarsController@calculateCars');

Title: Laravel redirecting when accessing post route directly


问:
percentage on y lab in a faceted ggplot barchart?
doing facets in ggplot I would often like the percentage to be used instead of counts.

e.g.

```<code>test1 <- sample(letters[1:2], 100, replace=T)
test2 <- sample(letters[3:8], 100, replace=T)
test <- data.frame(cbind(test1,test2))
ggplot(test, aes(test2))+geom_bar()+facet_grid(~test1)
</code>```

This is very easy but if N is different in facet A compared to facet B, it would be better I think, to compare percentages, in such a way that the each facet sums to 100%.

how would you achieve this?

Hope my question makes sense.

Sincerely.

答:
A very simple way:

```<code>ggplot(test, aes(test2)) +
    geom_bar(aes(y = (..count..)/sum(..count..))) +
    facet_grid(~test1)
</code>```

So I only changed the parameter of geom_bar to aes(y = (..count..)/sum(..count..)).
 After setting ylab to NULL and specifying the formatter, you could get:

```<code>ggplot(test, aes(test2)) +
    geom_bar(aes(y = (..count..)/sum(..count..))) +
    facet_grid(~test1) +
    scale_y_continuous('', formatter="percent")
</code>```

Update
Note that while formatter = "percent") works for ggplot2 version 0.8.9, in 0.9.0 you'd want something like scale_y_continuous(labels = percent_format()).

Body:
doing facets in ggplot I would often like the percentage to be used instead of counts.

e.g.

test1 <- sample(letters[1:2], 100, replace=T)
test2 <- sample(letters[3:8], 100, replace=T)
test <- data.frame(cbind(test1,test2))
ggplot(test, aes(test2))+geom_bar()+facet_grid(~test1)

This is very easy but if N is different in facet A compared to facet B, it would be better I think, to compare percentages, in such a way that the each facet sums to 100%.

how would you achieve this?

Hope my question makes sense.

Sincerely.

Body:
A very simple way:

ggplot(test, aes(test2)) +
    geom_bar(aes(y = (..count..)/sum(..count..))) +
    facet_grid(~test1)

So I only changed the parameter of geom_bar to aes(y = (..count..)/sum(..count..)).
 After setting ylab to NULL and specifying the formatter, you could get:

ggplot(test, aes(test2)) +
    geom_bar(aes(y = (..count..)/sum(..count..))) +
    facet_grid(~test1) +
    scale_y_continuous('', formatter="percent")

Update
Note that while formatter = "percent") works for ggplot2 version 0.8.9, in 0.9.0 you'd want something like scale_y_continuous(labels = percent_format()).


问:
Azure WebJob Queues are not triggering WebJobs
Azure WebJob Queues are not triggering WebJobs If I pass message in binary format to Queues?

I have Pushed GOOGLE PROTOBUF Bytes as CloudMessage into the Azure Queue Storage. But, Azure Queue storage is not pinging and Passing that CloudMessage to my Azure Continuous running WebJob instead of that, those Messages are moving to the Poison Queues?

Following Code is my WebJob for pooling the Queue Message.

Program file:

```<code>public class Program
{
    // Please set the following connection strings in app.config for this WebJob to run:
    // AzureWebJobsDashboard and AzureWebJobsStorage
    public static void Main()
    {
        try
        {

            JobHost host = new JobHost();
            //Following code ensures that the WebJob will be running continuously
            host.RunAndBlock();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}
</code>```

Function.cs

```<code>public class Function
{
    //This function will get triggered/Executed when new message is written on an Azure Queue called messagequeue
    public static void ProcessMessageQueue([QueueTrigger("messagequeue")] string message)
    {
        #region WebAPI Call

        #endregion
    }
}
</code>```

Code for Adding Message Bytes into Azure Queue:

```<code>  private void PushPayloadBytesToAzureQueueStorage(byte[] payload)
    {
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureWebJobsStorage"]);
        CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
        CloudQueue queue = queueClient.GetQueueReference("messagequeue");
        queue.CreateIfNotExists();
        CloudQueueMessage msg = new CloudQueueMessage(payload);
        queue.AddMessage(msg);
    }
</code>```

My case is, I will add the message as Bytes in the Queue then That Queue Storage have to send a message and trigger my Web job which is published/running in the Azure Cloud.

I have a doubt about the below Method Signature.

```<code> public static void ProcessMessageQueue([QueueTrigger("messagequeue")] string message)
</code>```

What datatype should I use for the message parameter in the above method signature since Messages are added into the Queue Storage Successfully but Queue does not trigger Azure function and all the Queue Messages are moved to Poison Queue.

What am I missing here?

Appreciate your thoughts on this.

Thanks in Advance!

答:
Based on your code, I checked this issue. I passed the payload as System.Text.UTF8Encoding.UTF8.GetBytes("hello world " + DateTime.Now), then I could retrieve the string parameter message under my ProcessMessageQueue function.

As How to trigger a function when a queue message is received states as follows:

Besides string, the parameter may be a byte array, a CloudQueueMessage object, or a POCO that you define.

For the byte array or CloudQueueMessage parameter, you could refer to the following code snippet:

```<code>System.Text.UTF8Encoding.UTF8.GetString(message); //for byte array

System.Text.UTF8Encoding.UTF8.GetString(message.AsBytes); //for CloudQueueMessage object
</code>```

Azure Queue storage is not pinging and Passing that CloudMessage to my Azure Continuous running WebJob instead of that, those Messages are moving to the Poison Queues?

The WebJobs SDK would handle a function up to 5 times to process your queue message. The message would be moved to a poison queue, more details your could refer to the description under How to handle poison messages.

I assumed that you need to check the encoding format of your input. And you could check the logs under your azure storage, more details you could follow here. Moreover, you could also use try-catch-throw within your ProcessMessageQueue function to narrow this issue.

Body:
Azure WebJob Queues are not triggering WebJobs If I pass message in binary format to Queues?

I have Pushed GOOGLE PROTOBUF Bytes as CloudMessage into the Azure Queue Storage. But, Azure Queue storage is not pinging and Passing that CloudMessage to my Azure Continuous running WebJob instead of that, those Messages are moving to the Poison Queues?

Following Code is my WebJob for pooling the Queue Message.

Program file:

public class Program
{
    // Please set the following connection strings in app.config for this WebJob to run:
    // AzureWebJobsDashboard and AzureWebJobsStorage
    public static void Main()
    {
        try
        {

            JobHost host = new JobHost();
            //Following code ensures that the WebJob will be running continuously
            host.RunAndBlock();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

Function.cs

public class Function
{
    //This function will get triggered/Executed when new message is written on an Azure Queue called messagequeue
    public static void ProcessMessageQueue([QueueTrigger("messagequeue")] string message)
    {
        #region WebAPI Call

        #endregion
    }
}

Code for Adding Message Bytes into Azure Queue:

  private void PushPayloadBytesToAzureQueueStorage(byte[] payload)
    {
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureWebJobsStorage"]);
        CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
        CloudQueue queue = queueClient.GetQueueReference("messagequeue");
        queue.CreateIfNotExists();
        CloudQueueMessage msg = new CloudQueueMessage(payload);
        queue.AddMessage(msg);
    }

My case is, I will add the message as Bytes in the Queue then That Queue Storage have to send a message and trigger my Web job which is published/running in the Azure Cloud.

I have a doubt about the below Method Signature.

 public static void ProcessMessageQueue([QueueTrigger("messagequeue")] string message)

What datatype should I use for the message parameter in the above method signature since Messages are added into the Queue Storage Successfully but Queue does not trigger Azure function and all the Queue Messages are moved to Poison Queue.

What am I missing here?

Appreciate your thoughts on this.

Thanks in Advance!

Body:
Based on your code, I checked this issue. I passed the payload as System.Text.UTF8Encoding.UTF8.GetBytes("hello world " + DateTime.Now), then I could retrieve the string parameter message under my ProcessMessageQueue function.

As How to trigger a function when a queue message is received states as follows:

Besides string, the parameter may be a byte array, a CloudQueueMessage object, or a POCO that you define.

For the byte array or CloudQueueMessage parameter, you could refer to the following code snippet:

System.Text.UTF8Encoding.UTF8.GetString(message); //for byte array

System.Text.UTF8Encoding.UTF8.GetString(message.AsBytes); //for CloudQueueMessage object

Azure Queue storage is not pinging and Passing that CloudMessage to my Azure Continuous running WebJob instead of that, those Messages are moving to the Poison Queues?

The WebJobs SDK would handle a function up to 5 times to process your queue message. The message would be moved to a poison queue, more details your could refer to the description under How to handle poison messages.

I assumed that you need to check the encoding format of your input. And you could check the logs under your azure storage, more details you could follow here. Moreover, you could also use try-catch-throw within your ProcessMessageQueue function to narrow this issue.


问:
I'm trying to compile the following code, but keep on getting the same error message
```<code>using System;
using System.Collections.Generic;
using PX.Data;
using System.Collections;
using PX.Objects.AR;
using PX.Objects.CR;
using PX.Objects.CS;
using PX.Objects.GL;
using PX.Objects.IN;
using PX.Objects.CT;
using PX.Objects;
using PX.Objects.PM;

namespace PX.Objects.PM{}

public class
ProjectBalanceEntry_Extension:PXGraphExtension<ProjectBalanceEntry>{}

  #region Event Handler

  public PXFilter<ProjectBalanceEntry.ProjectBalanceFilter>(Filter);
  [PXVirtualDAC]

  ProjectBalanceEntry row = e.Row as ProjectBalanceFilter;

  if (row != null)
    {
      Items.Cache.AllowInsert = row.ProjectID != null && row.AccountGroupID
!= null;
    }

  if (Filter.Current == null)
        {
            Items.Cache = row.ProjectID != null && row.AccountGroupID !=
null;
        }

            PXSelectJoin<PMProjectStatus,
                InnerJoin<PMTask, On<PMTask.projectID,
Equal<PMProjectStatus.projectID>>>,
                Where<PMProjectStatus.projectID,
Equal<Current<ProjectBalanceFilter.projectID>>,
And<PMProjectStatus.accountGroupID,
Equal<Current<ProjectBalanceFilter.accountGroupID>>>>,

              {
  if (project == null) project = Base.Project.Select();

  if (project != null && row != null)
 }

             INItemSite itemsite = PXSelectJoin<INItemSite,
                InnerJoin<Location, On<Location.cSiteID,
Equal<INItemSite.siteID>>>,
                Where<INItemSite.inventoryID,
Equal<Required<INItemSite.inventoryID>>, And<Location.bAccountID,
Equal<Required<Location.bAccountID>>>>>.Select(Base, row.InventoryID,
project.CustomerID);

           if (itemsite != null)
    {
      e.NewValue = itemsite.LastCost;
    }

  e.Cancel = true;

 #endregion
</code>```

I get the following error when validating this code:

Validating Binary Files Validating the website C:\Program Files
  (x86)\Acumatica
  ERP\Customization\AcumaticaPUPKT11Validation\AcumaticaPUPKT11Website
  IIS APPPOOL.NET v4.5 Building directory
  '\WebSiteValidationDomain\App_RuntimeCode\'.
  \App_RuntimeCode\ProjectBalanceEntry.cs(23): error CS1518: Expected
  class, delegate, enum, interface, or struct
  \App_RuntimeCode\ProjectBalanceEntry.cs(29): error CS1518: Expected
  class, delegate, enum, interface, or struct
  \App_RuntimeCode\ProjectBalanceEntry.cs(23): error CS1518: Expected
  class, delegate, enum, interface, or struct Compiler time, in seconds:
  5.0554991 Validation failed.

答:
You have {} in several places when I feel sure you meant {

```<code>namespace PX.Objects.PM{}

public class
ProjectBalanceEntry_Extension:PXGraphExtension<ProjectBalanceEntry>{}
</code>```

Basically something very wrong has happened to your curly braces (eg. a Find/Replace mistake). You may need to revert to an earlier version of the source code.

Also the function definitions have thr wrong syntax:

```<code>  public PXFilter<ProjectBalanceEntry.ProjectBalanceFilter>(Filter);
  [PXVirtualDAC]
</code>```

probably should be

```<code>  [PXVirtualDAC]
  public PXFilter<ProjectBalanceEntry.ProjectBalanceFilter>(Filter)
  {
</code>```

Body:
using System;
using System.Collections.Generic;
using PX.Data;
using System.Collections;
using PX.Objects.AR;
using PX.Objects.CR;
using PX.Objects.CS;
using PX.Objects.GL;
using PX.Objects.IN;
using PX.Objects.CT;
using PX.Objects;
using PX.Objects.PM;

namespace PX.Objects.PM{}

public class
ProjectBalanceEntry_Extension:PXGraphExtension<ProjectBalanceEntry>{}

  #region Event Handler

  public PXFilter<ProjectBalanceEntry.ProjectBalanceFilter>(Filter);
  [PXVirtualDAC]

  ProjectBalanceEntry row = e.Row as ProjectBalanceFilter;

  if (row != null)
    {
      Items.Cache.AllowInsert = row.ProjectID != null && row.AccountGroupID
!= null;
    }

  if (Filter.Current == null)
        {
            Items.Cache = row.ProjectID != null && row.AccountGroupID !=
null;
        }

            PXSelectJoin<PMProjectStatus,
                InnerJoin<PMTask, On<PMTask.projectID,
Equal<PMProjectStatus.projectID>>>,
                Where<PMProjectStatus.projectID,
Equal<Current<ProjectBalanceFilter.projectID>>,
And<PMProjectStatus.accountGroupID,
Equal<Current<ProjectBalanceFilter.accountGroupID>>>>,

              {
  if (project == null) project = Base.Project.Select();

  if (project != null && row != null)
 }

             INItemSite itemsite = PXSelectJoin<INItemSite,
                InnerJoin<Location, On<Location.cSiteID,
Equal<INItemSite.siteID>>>,
                Where<INItemSite.inventoryID,
Equal<Required<INItemSite.inventoryID>>, And<Location.bAccountID,
Equal<Required<Location.bAccountID>>>>>.Select(Base, row.InventoryID,
project.CustomerID);

           if (itemsite != null)
    {
      e.NewValue = itemsite.LastCost;
    }

  e.Cancel = true;

 #endregion

I get the following error when validating this code:

Validating Binary Files Validating the website C:\Program Files
  (x86)\Acumatica
  ERP\Customization\AcumaticaPUPKT11Validation\AcumaticaPUPKT11Website
  IIS APPPOOL.NET v4.5 Building directory
  '\WebSiteValidationDomain\App_RuntimeCode\'.
  \App_RuntimeCode\ProjectBalanceEntry.cs(23): error CS1518: Expected
  class, delegate, enum, interface, or struct
  \App_RuntimeCode\ProjectBalanceEntry.cs(29): error CS1518: Expected
  class, delegate, enum, interface, or struct
  \App_RuntimeCode\ProjectBalanceEntry.cs(23): error CS1518: Expected
  class, delegate, enum, interface, or struct Compiler time, in seconds:
  5.0554991 Validation failed.

Body:
You have {} in several places when I feel sure you meant {

namespace PX.Objects.PM{}

public class
ProjectBalanceEntry_Extension:PXGraphExtension<ProjectBalanceEntry>{}

Basically something very wrong has happened to your curly braces (eg. a Find/Replace mistake). You may need to revert to an earlier version of the source code.

Also the function definitions have thr wrong syntax:

  public PXFilter<ProjectBalanceEntry.ProjectBalanceFilter>(Filter);
  [PXVirtualDAC]

probably should be

  [PXVirtualDAC]
  public PXFilter<ProjectBalanceEntry.ProjectBalanceFilter>(Filter)
  {