问:
lookup module fail to compute value of a template using regex_replace filter
This seems to be a bug. But before posting an issue to ansible's github project, I ask here.

Playbook :

```<code>- hosts: localhost
  tasks:
    - template: >
        dest=/tmp/test.xml
        src=test.xml.j2
    - debug: msg="{{ lookup( 'template', 'test.xml.j2' ) }}"
  vars:
    - command: 'echo "word1 word2"'
</code>```

test.xml.j2

```<code><command>ssh {{ command| regex_replace('"(.*)"', '"\\"\1\\""') }} #1</command>
<command>ssh {{ command| regex_replace('"(.*)"', '"\\"\\1\\""') }} #2</command>
</code>```

Test command

```<code>ansible-playbook test.yml -D -C
</code>```

Expected result : same result on the two tasks

Actual results (ansible 2.3.1.0) :

when escaping once, template module fail to display first reference

when escaping twice, lookup module fail to dereference second reference

答:
template action and template lookup are known to give different results in several cases.

You may feel free to file an issue.

As a workaround, you can use set in your template:

```<code>{% set repl = '"\\"\\1\\""' %}
<command>ssh {{ command| regex_replace('"(.*)"', '"\\"\1\\""') }} #1</command>
<command>ssh {{ command| regex_replace('"(.*)"', '"\\"\\1\\""') }} #2</command>
<command>ssh {{ command| regex_replace('"(.*)"', repl) }} #3</command>
</code>```

Here #3 gives the same result both with action and with lookup:

```<code>- template:
    dest: /tmp/test.xml
    src: test.xml.j2
- copy:
    content: "{{ lookup( 'template', 'test.xml.j2' ) }}"
    dest: /tmp/test2.xml
</code>```

result:

```<code><command>ssh echo "\"\"" #1</command>
<command>ssh echo "\"word1 word2\"" #2</command>
<command>ssh echo "\"word1 word2\"" #3</command>

<command>ssh echo "\"word1 word2\"" #1</command>
<command>ssh echo "\"\1\"" #2</command>
<command>ssh echo "\"word1 word2\"" #3</command>
</code>```

Body:
This seems to be a bug. But before posting an issue to ansible's github project, I ask here.

Playbook :

- hosts: localhost
  tasks:
    - template: >
        dest=/tmp/test.xml
        src=test.xml.j2
    - debug: msg="{{ lookup( 'template', 'test.xml.j2' ) }}"
  vars:
    - command: 'echo "word1 word2"'

test.xml.j2

<command>ssh {{ command| regex_replace('"(.*)"', '"\\"\1\\""') }} #1</command>
<command>ssh {{ command| regex_replace('"(.*)"', '"\\"\\1\\""') }} #2</command>

Test command

ansible-playbook test.yml -D -C

Expected result : same result on the two tasks

Actual results (ansible 2.3.1.0) :

when escaping once, template module fail to display first reference

when escaping twice, lookup module fail to dereference second reference

Body:
template action and template lookup are known to give different results in several cases.

You may feel free to file an issue.

As a workaround, you can use set in your template:

{% set repl = '"\\"\\1\\""' %}
<command>ssh {{ command| regex_replace('"(.*)"', '"\\"\1\\""') }} #1</command>
<command>ssh {{ command| regex_replace('"(.*)"', '"\\"\\1\\""') }} #2</command>
<command>ssh {{ command| regex_replace('"(.*)"', repl) }} #3</command>

Here #3 gives the same result both with action and with lookup:

- template:
    dest: /tmp/test.xml
    src: test.xml.j2
- copy:
    content: "{{ lookup( 'template', 'test.xml.j2' ) }}"
    dest: /tmp/test2.xml

result:

<command>ssh echo "\"\"" #1</command>
<command>ssh echo "\"word1 word2\"" #2</command>
<command>ssh echo "\"word1 word2\"" #3</command>

<command>ssh echo "\"word1 word2\"" #1</command>
<command>ssh echo "\"\1\"" #2</command>
<command>ssh echo "\"word1 word2\"" #3</command>


来源: stackexchange

问:
How to debug code executed at application's startup if application is hosted in IIS and starts when IIS does?
I have a .NET application which is server framework and it is hosted in IIS and it starts when IIS does.

To debug the framework I attach to the client process by Visual Studio. It works for normal debugging, but now I want to debug section when framework loads its configuration from xml files (it is handled by C# code). It does it only once when application starts so exactly the same time the IIS starts. I am not faster than IIS with attaching my solution.

If I attach framework to the client process then reset the IIS the debugger will be detached.

How to handle such problem?

Bad solution: The only way may work is to put a very long Thread.Sleep at the beginning of the app and then attach quickly.

答:
Add

```<code>System.Diagnostics.Debugger.Launch();
</code>```

to Application_Start. You'll get a popup asking you if you want to debug the website, and if you click OK, you'll be taken to Visual Studio in debug mode, paused at that line.

ContentLicense: CC BY-SA 3.0

Body:
Add

System.Diagnostics.Debugger.Launch();

to Application_Start. You'll get a popup asking you if you want to debug the website, and if you click OK, you'll be taken to Visual Studio in debug mode, paused at that line.


问:
C# Packing multiple signed integers into a single 64-bit value
I need to pack and unpack several values to/from a single 64-bit value. I have 3 signed integers (x,y,z). I would like to pack them into a single 64-bit value (signed or unsigned doesn't matter to me) using 24, 16, and 24 bits for the values respectively. Here are my requirements:

1) I can ensure ahead of times that the values being stored do not exceed the limits of the number of bits I am using to store them into the 64-bit value, so no additional checks need to be made.

2) The initial values are signed, so I'm thinking some kind of bit magic may need to be done in order to ensure that nothing is lost.

3) This conversion is going to take place a LOT, so it needs to be fast. I know in C++ this can pretty easily be done by storing the values in a struct that specifies the integer length, and then establishing a pointer that just points to the first value that can be used for the 64-bit value. With this method, there really isn't any math that needs done, everything is just memory read or right. As far as I can tell, this can't be done quite so simply in C#, but C# is what I have to work with for this project.

4) I don't really care if the 64-bit value is signed or unsigned, so long as I can go both ways with the operation and recover the initial values, and whatever type is used can be used for a Dictionary key.

答:
These values are byte-aligned inside the long, you'll want to take advantage of Intel/AMD processors being able to directly access them to make the code as fast as possible.  The killer requirement is the 24 bit size, the processor can only directly read/write 8, 16, 32 or 64 bits.

That is a problem in C++ as well, you'd have to use bit-fields.  C# does not support them, you'll have to write the code that the C++ compiler emits automatically.  Like this:

```<code>[StructLayout(LayoutKind.Explicit)]
struct MyPackedLong {
    [FieldOffset(0)] uint item1;    // 24-bit field
    [FieldOffset(3)] uint item2;    // 24-bit field
    [FieldOffset(6)] ushort item3;  // 16-bit field

    public uint Item1 {
        get { return item1 & 0xffffff; }
        set { item1 = (item1 & 0xff000000) | value; }
    }
    public uint Item2 {
        get { return item2 & 0xffffff; }
        set { item2 = (item2 & 0xff000000) | value; }
    }
    public ushort Item3 {
        get { return item3; }
        set { item3 = value; }
    }
}
</code>```

Some trickorama here, note how item2 has an intentional offset of 3 so that no shift is necessary.  I ordered the fields so their access is optimal, putting the 16-bit value either first or last is best.  Not thoroughly tested, ought to be in the ballpark.  Be careful in threaded code, the writes are not atomic.

Body:
These values are byte-aligned inside the long, you'll want to take advantage of Intel/AMD processors being able to directly access them to make the code as fast as possible.  The killer requirement is the 24 bit size, the processor can only directly read/write 8, 16, 32 or 64 bits.

That is a problem in C++ as well, you'd have to use bit-fields.  C# does not support them, you'll have to write the code that the C++ compiler emits automatically.  Like this:

[StructLayout(LayoutKind.Explicit)]
struct MyPackedLong {
    [FieldOffset(0)] uint item1;    // 24-bit field
    [FieldOffset(3)] uint item2;    // 24-bit field
    [FieldOffset(6)] ushort item3;  // 16-bit field

    public uint Item1 {
        get { return item1 & 0xffffff; }
        set { item1 = (item1 & 0xff000000) | value; }
    }
    public uint Item2 {
        get { return item2 & 0xffffff; }
        set { item2 = (item2 & 0xff000000) | value; }
    }
    public ushort Item3 {
        get { return item3; }
        set { item3 = value; }
    }
}

Some trickorama here, note how item2 has an intentional offset of 3 so that no shift is necessary.  I ordered the fields so their access is optimal, putting the 16-bit value either first or last is best.  Not thoroughly tested, ought to be in the ballpark.  Be careful in threaded code, the writes are not atomic.


问:
Loading csv to table in Oracle
I cannot get csv data into an Oracle table.

ERROR:

```<code>    Traceback (most recent call last):
    File "H:/Standard_Procedures/Dataset_Management/Table_to_Oracle.py", line 139, in <module>
      sde_cursor.execute(insert_string,row)
    DatabaseError: ORA-01747: invalid user.table.column, table.column, or column specification
</code>```

CODE:

```<code>with open(dataset) as f:
    reader = csv.reader(f, delimiter=',')
    column_string = ','.join(next(reader)).translate(None,'"')
    insert_string='INSERT INTO {} ({}) VALUES ('.format(dataset_name, column_string)
    val_list=[]
    for i in range(1,len(first_row)+1):
        val_list.append(':'+ str(i))
    value_string=','.join(val_list)
    insert_string += value_string + ')'
    for row in reader:
        print 'Insert String = {}'.format(insert_string)
        print 'Row = {}'.format(row)
        sde_cursor.execute(insert_string,row)
</code>```

PRINT RESULT:

Insert String = INSERT INTO area_harvest_summary_20170629a (PERIOD,YEAR,PERIODWIDTH,ObjectID,TSA_UKEY,POLY_NUM,CLUSTER,FMU,LANDBASE,WATERSHED,COMPARTMENT,OWNERSHIP,AREA,YC,Cover,AgeAtHarvest,HarvestYear,Treatment,NewYc,PriConifer,PriDecid,IncConifer,IncDecid,ConiferPieceSize,DecidPieceSize) VALUES (:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13,:14,:15,:16,:17,:18,:19,:20,:21,:22,:23,:24,:25)

Row = ['1', '10', '10', 'A14029867', '7025115', '851840750', 'A14010716', 'A14', 'CON', '480', 'A14-A', 'Northlan', '9.022459984', '5', 'C_Mx_Sw', '118', '5', 'Inten', '5', '1718.527663', '0', '0', '598.0849757', '0.371338338', '0.287112087']

I have tried zip(row) and zip(row,val_list) but neither does it.Is it an issue with the string format of numbers in Row? If so, how do I get around this? I have also tried some of the methods I found on google, but again, no luck.

Ideally, I'd like this in an executemany statement, but all efforts on that side are as well not working.

答:
You have reversed VALUES with enumeration of rows, change to the following:

```<code>with open(dataset) as f:
    ...
    # Don't change insert_string
    # insert_string += value_string + ')'
    for row in reader:
        # Append this row Data
        print 'Insert String = {}'.format(insert_string + row)
        sde_cursor.execute(insert_string + row)
</code>```

Title: Loading csv to table in Oracle

Body:
I cannot get csv data into an Oracle table.

ERROR:

    Traceback (most recent call last):
    File "H:/Standard_Procedures/Dataset_Management/Table_to_Oracle.py", line 139, in <module>
      sde_cursor.execute(insert_string,row)
    DatabaseError: ORA-01747: invalid user.table.column, table.column, or column specification

CODE:

with open(dataset) as f:
    reader = csv.reader(f, delimiter=',')
    column_string = ','.join(next(reader)).translate(None,'"')
    insert_string='INSERT INTO {} ({}) VALUES ('.format(dataset_name, column_string)
    val_list=[]
    for i in range(1,len(first_row)+1):
        val_list.append(':'+ str(i))
    value_string=','.join(val_list)
    insert_string += value_string + ')'
    for row in reader:
        print 'Insert String = {}'.format(insert_string)
        print 'Row = {}'.format(row)
        sde_cursor.execute(insert_string,row)

PRINT RESULT:

Insert String = INSERT INTO area_harvest_summary_20170629a (PERIOD,YEAR,PERIODWIDTH,ObjectID,TSA_UKEY,POLY_NUM,CLUSTER,FMU,LANDBASE,WATERSHED,COMPARTMENT,OWNERSHIP,AREA,YC,Cover,AgeAtHarvest,HarvestYear,Treatment,NewYc,PriConifer,PriDecid,IncConifer,IncDecid,ConiferPieceSize,DecidPieceSize) VALUES (:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13,:14,:15,:16,:17,:18,:19,:20,:21,:22,:23,:24,:25)

Row = ['1', '10', '10', 'A14029867', '7025115', '851840750', 'A14010716', 'A14', 'CON', '480', 'A14-A', 'Northlan', '9.022459984', '5', 'C_Mx_Sw', '118', '5', 'Inten', '5', '1718.527663', '0', '0', '598.0849757', '0.371338338', '0.287112087']

I have tried zip(row) and zip(row,val_list) but neither does it.Is it an issue with the string format of numbers in Row? If so, how do I get around this? I have also tried some of the methods I found on google, but again, no luck.

Ideally, I'd like this in an executemany statement, but all efforts on that side are as well not working.

Body:
You have reversed VALUES with enumeration of rows, change to the following:

with open(dataset) as f:
    ...
    # Don't change insert_string
    # insert_string += value_string + ')'
    for row in reader:
        # Append this row Data
        print 'Insert String = {}'.format(insert_string + row)
        sde_cursor.execute(insert_string + row)


问:
What does " -r " do in pip install -r requirements.txt
I looked up how to install multiple packages from a requirements document using pip. The answers were mostly:

```<code> pip install -r requirements.txt
</code>```

What does the -r do though? I can't find an answer for this and it isn't listed when I run pip help.

答: In your case pip install -r requirements.txt will install the libraries listed in your requirements.txt file.

Body:
I looked up how to install multiple packages from a requirements document using pip. The answers were mostly:

 pip install -r requirements.txt

What does the -r do though? I can't find an answer for this and it isn't listed when I run pip help.


问:
Pass HTML Table string through Json from controller to view
I want to achieve this:

```<code>public System.Web.Mvc.ActionResult ExposureGrid(Guid? id, decimal stdDev)
        {
            //return null;
            try
            {
                var str = "<table border=1>";
                str += "<tr><th>Date</th><th>Expected Credit Exposure</th><th>Max Credit Exposure</th></tr>";

                str += "<tr><td>12/1/2010</td><td>100,000</td><td>50</td></tr>";
                str += "<tr><td>12/2/2010</td><td>101,000</td><td>100</td></tr>";
                str += "<tr><td>12/3/2010</td><td>102,000</td><td>150</td></tr>";
                str += "<tr><td>12/4/2010</td><td>103,000</td><td>200</td></tr>";
                str += "<tr><td>12/5/2010</td><td>104,000</td><td>250</td></tr>";
                str += "<tr><td>12/6/2010</td><td>105,000</td><td>300</td></tr>";
                str += "<tr><td>12/7/2010</td><td>106,000</td><td>350</td></tr>";

            str += "</table>";
            return Json(str);
            }
            catch (Exception e)
            {
                return Json(e.ToString());
            }
        }
</code>```

Then I take that Json and put it on my view like this:

```<code>$.ajax({
                type: "POST",
                url: "<%= Url.Action("ExposureGrid", "Indications") %> ",
                dataType: "jsonData",
                data: tableJSON,
                success: function(data) {
                      existingDiv = document.getElementById('table');
                      existingDiv.innerHTML = data;
                }
            });
</code>```

But what shows on the view in HTML is this:

"\u003ctable border=1\u003e\u003ctr\u003e\u003cth\u003eDate\u003c/th\u003e\u003cth\u003eExpected Credit Exposure\u003c/th\u003e\u003cth\u003eMax Credit Exposure\u003c/th\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/1/2010\u003c/td\u003e\u003ctd\u003e100,000\u003c/td\u003e\u003ctd\u003e50\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/2/2010\u003c/td\u003e\u003ctd\u003e101,000\u003c/td\u003e\u003ctd\u003e100\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/3/2010\u003c/td\u003e\u003ctd\u003e102,000\u003c/td\u003e\u003ctd\u003e150\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/4/2010\u003c/td\u003e\u003ctd\u003e103,000\u003c/td\u003e\u003ctd\u003e200\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/5/2010\u003c/td\u003e\u003ctd\u003e104,000\u003c/td\u003e\u003ctd\u003e250\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/6/2010\u003c/td\u003e\u003ctd\u003e105,000\u003c/td\u003e\u003ctd\u003e300\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/7/2010\u003c/td\u003e\u003ctd\u003e106,000\u003c/td\u003e\u003ctd\u003e350\u003c/td\u003e\u003c/tr\u003e\u003c/table\u003e"

How do I fix this?

答:
Why you don't load it directly from html ?
Instead of rendering a Json (content-type: application/json), you return it as a partial html element (content-type: text/html) and from JQuery you load it with dataType: "html".

Doing so, you even wouldn't have to change your success method !

ContentLicense: CC BY-SA 2.5

Body:
I want to achieve this:

public System.Web.Mvc.ActionResult ExposureGrid(Guid? id, decimal stdDev)
        {
            //return null;
            try
            {
                var str = "
";
                str += "
Date	Expected Credit Exposure	Max Credit Exposure
";

                str += "
12/1/2010	100,000	50
";
                str += "
12/2/2010	101,000	100
";
                str += "
12/3/2010	102,000	150
";
                str += "
12/4/2010	103,000	200
";
                str += "
12/5/2010	104,000	250
";
                str += "
12/6/2010	105,000	300
";
                str += "
12/7/2010	106,000	350
";

            str += "
";
            return Json(str);
            }
            catch (Exception e)
            {
                return Json(e.ToString());
            }
        }

Then I take that Json and put it on my view like this:

$.ajax({
                type: "POST",
                url: "<%= Url.Action("ExposureGrid", "Indications") %> ",
                dataType: "jsonData",
                data: tableJSON,
                success: function(data) {
                      existingDiv = document.getElementById('table');
                      existingDiv.innerHTML = data;
                }
            });

But what shows on the view in HTML is this:

"\u003ctable border=1\u003e\u003ctr\u003e\u003cth\u003eDate\u003c/th\u003e\u003cth\u003eExpected Credit Exposure\u003c/th\u003e\u003cth\u003eMax Credit Exposure\u003c/th\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/1/2010\u003c/td\u003e\u003ctd\u003e100,000\u003c/td\u003e\u003ctd\u003e50\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/2/2010\u003c/td\u003e\u003ctd\u003e101,000\u003c/td\u003e\u003ctd\u003e100\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/3/2010\u003c/td\u003e\u003ctd\u003e102,000\u003c/td\u003e\u003ctd\u003e150\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/4/2010\u003c/td\u003e\u003ctd\u003e103,000\u003c/td\u003e\u003ctd\u003e200\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/5/2010\u003c/td\u003e\u003ctd\u003e104,000\u003c/td\u003e\u003ctd\u003e250\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/6/2010\u003c/td\u003e\u003ctd\u003e105,000\u003c/td\u003e\u003ctd\u003e300\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/7/2010\u003c/td\u003e\u003ctd\u003e106,000\u003c/td\u003e\u003ctd\u003e350\u003c/td\u003e\u003c/tr\u003e\u003c/table\u003e"

How do I fix this?


问:
Adding columns to a structured Numpy array
I have the following data in geo.dat

```<code>id  lon  lat inhab  name
 1   9.  45.   100  Ciriè
 2  10.  45.    60  Acquanegra
</code>```

and I get it in a ndarray

```<code>import numpy as np
data = np.genfromtxt('geo.dat', dtype=None, names=True)
</code>```

so far, so good, I have a data structure that I can address by column name

```<code>print(data['name'][1]) #>>> Acquanegra
</code>```

Next step, and question — I have a function that takes in input two vectors of
geographical coordinates (data['LON'] and data['LAT'] of course) and returns two arrays x and y of projected positions on a map (this works ok).

I can live with separate vectors x and y but I'd like to augment data with two new columns, data['x'] and data['y']. My naive attempt

```<code>data['x'], data['y'] = convert(data['LON'], data['LAT'])
</code>```

raised a ValueError: no field of name x, teaching me that data has some traits of a dictionary but a dictionary is not.

Is it possible to do as I want? tia

Please consider that .hstack() doesn't work with structured arrays aka record arrays, most previous answers work only for homogeneous arrays (the exception is mentioned in below comment by Warren).

PS I'd prefer not to pandas.

答:
You can use np.lib.recfunctions:

```<code>import numpy.lib.recfunctions as rfn

data = rfn.append_fields(data, ['x', 'y'], [x, y])
</code>```

Body:
I have the following data in geo.dat

id  lon  lat inhab  name
 1   9.  45.   100  Ciriè
 2  10.  45.    60  Acquanegra

and I get it in a ndarray

import numpy as np
data = np.genfromtxt('geo.dat', dtype=None, names=True)

so far, so good, I have a data structure that I can address by column name

print(data['name'][1]) #>>> Acquanegra

Next step, and question — I have a function that takes in input two vectors of
geographical coordinates (data['LON'] and data['LAT'] of course) and returns two arrays x and y of projected positions on a map (this works ok).

I can live with separate vectors x and y but I'd like to augment data with two new columns, data['x'] and data['y']. My naive attempt

data['x'], data['y'] = convert(data['LON'], data['LAT'])

raised a ValueError: no field of name x, teaching me that data has some traits of a dictionary but a dictionary is not.

Is it possible to do as I want? tia

Please consider that .hstack() doesn't work with structured arrays aka record arrays, most previous answers work only for homogeneous arrays (the exception is mentioned in below comment by Warren).

PS I'd prefer not to pandas.

Body:
You can use np.lib.recfunctions:

import numpy.lib.recfunctions as rfn

data = rfn.append_fields(data, ['x', 'y'], [x, y])


问:
What jQuery version to mention in code
I'm using jQuery, and I'm little confused about what version is included at start of my page. From my experience with other software I understand that each new version contains most old features, and offers some new ones. If latests jQuery version is 1.9 for example, why would I mention this:

```<code><meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../jqm145/jquery.mobile-1.4.5.min.css">
<script src="../jq1-11-3/jquery-1.11.3.js"></script>
<script src="../jqm145/jquery.mobile-1.4.5.min.js"></script>
</code>```

How do I check if a function will work in a specific version of Jquery?

Furthermore, the mobile JQuery version 1.4.5 and "plain" JQuery is 1.11.3. Why is this the case?

答:
jQuery mobile (perhaps confusingly) is not a mobile version of jQuery, it's a library based on jQuery that contains controls, logic, etc. for Mobile devices.

jQuery has remained backwards compatible until version 3.0.0, in which support for older browsers has been dropped.

As a rule of thumb, it's good to update both libraries at the same time if one depends upon the other.

Title: What jQuery version to mention in code

Body:
I'm using jQuery, and I'm little confused about what version is included at start of my page. From my experience with other software I understand that each new version contains most old features, and offers some new ones. If latests jQuery version is 1.9 for example, why would I mention this:

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../jqm145/jquery.mobile-1.4.5.min.css">

How do I check if a function will work in a specific version of Jquery?

Furthermore, the mobile JQuery version 1.4.5 and "plain" JQuery is 1.11.3. Why is this the case?


问:
Extracting grid cells of a netcdf file based values from another nc file with R
I want to extract the grid cells from a MERRA2 netcdf file which are flagged as sea only with R:

However parts of the land areas are within my selection due to the curved nature of the lower boundary of the land area. I want to select the area of the sea area which are closest to the land but there are areas of the land in  my selection which I want to filter out.

I have another nc file which has the fractions of the land and sea areas from which I understand it is possible to extract the grid cells I need from:

So I have to define a mask that I can use to only select ocean points from my first file with a certain threshold since there are fractional coverage of land and ocean.
Please is there a way to do this with R or maybe in ArcGIS

答:
you can do something using CDO perhaps.  If you decide on a land fraction threshold "c" you want to use for your mask from your landsea mask file landsea.nc (it sounds from your description that c needs to be a very small positive real number) then you can either define a mask which is zero for sea and one for land

```<code>cdo lec,c landsea.nc mask.nc
</code>```

This sets all points with values < c to 1, otherwise 0 (for land)

Or if you want to then set all land points to "missing" then you can

```<code>cdo setrtomiss,0.5,2 mask.nc mask_miss.nc
</code>```

Now land points are set to "missing"

you can then scale the data file with the mask to either set the land points to zero

```<code>cdo mul merra2.nc mask.nc out1.nc
</code>```

or you can set them to missing :

```<code>cdo mul merra2.nc mask_miss.nc out2.nc
</code>```

Which you can then process.

Of course, here I am assuming that the landsea.nc mask file is on the same grid as your merra file.  If they are not you will need to regrid the mask file first, which you can also do with CDO.

Body:
you can do something using CDO perhaps.  If you decide on a land fraction threshold "c" you want to use for your mask from your landsea mask file landsea.nc (it sounds from your description that c needs to be a very small positive real number) then you can either define a mask which is zero for sea and one for land

cdo lec,c landsea.nc mask.nc

This sets all points with values < c to 1, otherwise 0 (for land)

Or if you want to then set all land points to "missing" then you can

cdo setrtomiss,0.5,2 mask.nc mask_miss.nc

Now land points are set to "missing"

you can then scale the data file with the mask to either set the land points to zero

cdo mul merra2.nc mask.nc out1.nc

or you can set them to missing :

cdo mul merra2.nc mask_miss.nc out2.nc

Which you can then process.

Of course, here I am assuming that the landsea.nc mask file is on the same grid as your merra file.  If they are not you will need to regrid the mask file first, which you can also do with CDO.


问:
How to show javascript alertbox on button click event in asp.net webpage if textbox1.text=""?
How to show javascript alertbox on button click event in asp.net webpage if textbox1.text="" ?</p>

答:
What you must do is attach a script to the button's client click event. In that script, check the value of textbox1. If it's empty, you show the alert and return false to prevent the form from submitting (prevent postback).

To do so, in Page_Load, insert the following:

```<code>if (!Page.IsPostBack)
{
    string script = string.Format("if (document.getElementById('{0}').value == '') {{ alert('Textbox is empty'); return false; }}", textbox1.ClientID);
    btnMyButton.Attributes.Add("onclick", script);
}
</code>```

Of course, you could encapsulate the script in a reusable method, use jquery to check the value, but this is the big idea.

Body:
What you must do is attach a script to the button's client click event. In that script, check the value of textbox1. If it's empty, you show the alert and return false to prevent the form from submitting (prevent postback).

To do so, in Page_Load, insert the following:

if (!Page.IsPostBack)
{
    string script = string.Format("if (document.getElementById('{0}').value == '') {{ alert('Textbox is empty'); return false; }}", textbox1.ClientID);
    btnMyButton.Attributes.Add("onclick", script);
}

Of course, you could encapsulate the script in a reusable method, use jquery to check the value, but this is the big idea.


问:
How to retrieve the Content-Type and the Content-Disposition from an outlook msg file using Apache POI-HSMF?
I need to write a Java program to extract all attachments from messages saved by Outlook 2016 in the native msg format. The program should skip inline images. Also some of the mails have multipart/alternative parts where the program should retrieve the "best" content-type, e.g. text/html over text/plain.

In order to do that, I need to find out the content-type and content-disposition of all parts and attachments of the message.

I tried the following:

```<code>public static void main(String[] args) throws IOException {
    String mfile = "test/test2.msg";
    MAPIMessage msg = new MAPIMessage(mfile);

    AttachmentChunks[] attachments = msg.getAttachmentFiles();
    if (attachments.length > 0) {
        for (AttachmentChunks attachment : attachments) {
            System.out.println("long file name = " + attachment.getAttachLongFileName());
            System.out.println("content id = " + attachment.getAttachContentId());
            System.out.println("mime tag = " + attachment.getAttachMimeTag());
            System.out.println("embedded = " + attachment.isEmbeddedMessage());
        }
    }
    msg.close();
}
</code>```

The problem is, that the "mime tag" (i.e. the content-type) is returned only for some attachments and returns null for all others. The content-disposition seems to be totally missing.

For example, I get the following output on a mail saved by OL2016 (the mail contains a PDF attachment and an inline logo image):

```<code>long file name = Vertretungsvollmacht Übersiedlung.pdf
content id = null
mime tag = null
embedded = false
long file name = image001.jpg
content id = image001.jpg@01D2E697.12EC9370
mime tag = image/jpeg
embedded = false
</code>```

Is there a way to get these attributes out of the msg files or is there a more complete & convenient way to achieve what I want in Java with some other library than Apache POI-HSMF?

答:
In order to get the content-disposition (inline or attachment), I did the following:

```<code>    String disposition = "attachment";
    if (contentId != "")
        if (body.contains(contentId.toString()))
            disposition = "inline";
</code>```

To obtain the content-type, I have derived it from the file extension of the attachment, e.g.:

```<code>        String ext = fileNameOri.substring(fileNameOri.lastIndexOf(".") + 1);
        switch (ext.toLowerCase()) {
        case "xlsx":
            ct = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            break;
        }
</code>```

A list of mime types can be obtained from e.g. https://wiki.selfhtml.org/wiki/MIME-Type/%C3%9Cbersicht

Of course, this should only be done in case AttachmentChunks.getAttachMimeTag() returns an empty string.

Body:
I need to write a Java program to extract all attachments from messages saved by Outlook 2016 in the native msg format. The program should skip inline images. Also some of the mails have multipart/alternative parts where the program should retrieve the "best" content-type, e.g. text/html over text/plain.

In order to do that, I need to find out the content-type and content-disposition of all parts and attachments of the message.

I tried the following:

public static void main(String[] args) throws IOException {
    String mfile = "test/test2.msg";
    MAPIMessage msg = new MAPIMessage(mfile);

    AttachmentChunks[] attachments = msg.getAttachmentFiles();
    if (attachments.length > 0) {
        for (AttachmentChunks attachment : attachments) {
            System.out.println("long file name = " + attachment.getAttachLongFileName());
            System.out.println("content id = " + attachment.getAttachContentId());
            System.out.println("mime tag = " + attachment.getAttachMimeTag());
            System.out.println("embedded = " + attachment.isEmbeddedMessage());
        }
    }
    msg.close();
}

The problem is, that the "mime tag" (i.e. the content-type) is returned only for some attachments and returns null for all others. The content-disposition seems to be totally missing.

For example, I get the following output on a mail saved by OL2016 (the mail contains a PDF attachment and an inline logo image):

long file name = Vertretungsvollmacht Übersiedlung.pdf
content id = null
mime tag = null
embedded = false
long file name = image001.jpg
content id = image001.jpg@01D2E697.12EC9370
mime tag = image/jpeg
embedded = false

Is there a way to get these attributes out of the msg files or is there a more complete & convenient way to achieve what I want in Java with some other library than Apache POI-HSMF?

Body:
In order to get the content-disposition (inline or attachment), I did the following:

    String disposition = "attachment";
    if (contentId != "")
        if (body.contains(contentId.toString()))
            disposition = "inline";

To obtain the content-type, I have derived it from the file extension of the attachment, e.g.:

        String ext = fileNameOri.substring(fileNameOri.lastIndexOf(".") + 1);
        switch (ext.toLowerCase()) {
        case "xlsx":
            ct = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            break;
        }

A list of mime types can be obtained from e.g. https://wiki.selfhtml.org/wiki/MIME-Type/%C3%9Cbersicht

Of course, this should only be done in case AttachmentChunks.getAttachMimeTag() returns an empty string.


问:
Breaking a line inside a span using Javascript or CSS
I'm well aware that span is an inline element and by making a separate span and simply using display:block on it would be the solution in most other cases. Mine is a bit more complicated since my code is tangled up in Javascript & semi-PHP code. So here's what I'm facing:

This part of the code is used in the template file (.tpl):

```<code><p id="reduction_amount" {if !$product->specificPrice || $product->specificPrice.reduction_type != 'amount' || $product->specificPrice.reduction|floatval ==0} style="display:none"{/if}>
   {strip}
    <span id="reduction_amount_display">
     {if $product->specificPrice && $product->specificPrice.reduction_type == 'amount' && $product->specificPrice.reduction|floatval !=0}
     SAVE {convertPrice price=$productPriceWithoutReduction|floatval-$productPrice|floatval}
     {/if}
    </span>
   {/strip}
</p>
</code>```

..And this part inside a .js file:

```<code>if (combination.specific_price.reduction_type == 'amount') {
  $('#reduction_amount_display').html('SAVE ' + formatCurrency(discountValue, currencyFormat, currencySign, currencyBlank));
  $('#reduction_amount').show();
}
</code>```

This works perfectly and this is how it looks like currently:

(note: the
 element has a fixed width and height)

The thing is, I'd like to give a line break after the "SAVE" part and be able to style the amount shown with a bigger font size. Demonstration:

This could be, as I mentioned above, achieved by separating the two with two other spans and stylizing them to how I want it to look. However, as my knowledge in Javascript is quite limited I do not know the correct way to insert a span. I tried several ways, for example adding html += '' right before formatCurrency and a closing tag after the paranthesis but this kinda messed up everything in the design for some reason. I also tried without using html += and plainly with quotes and the same thing happened. What solution is there for this? It does not necessarily have to be Javascript code. It could be a CSS or an HTML solution as well.

EDIT:

Using
 is unfortunately not plausible since I wouldn't be able to stylize the amount shown separately. Also, using that tag makes a huge gap that the amount goes way out of (overflows) the
 element.

答:
You can wrap the dollar value in an element created by jQuery using append(), and style it accordingly with a given class.

var amount = $('#reduction_amount_display');

amount.html('SAVE ');

amount.append('
$10
');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.style-amount {
  font-size:32px;
}</code>```

```

Body:
I'm well aware that span is an inline element and by making a separate span and simply using display:block on it would be the solution in most other cases. Mine is a bit more complicated since my code is tangled up in Javascript & semi-PHP code. So here's what I'm facing:

This part of the code is used in the template file (.tpl):

specificPrice || $product->specificPrice.reduction_type != 'amount' || $product->specificPrice.reduction|floatval ==0} style="display:none"{/if}>
   {strip}

     {if $product->specificPrice && $product->specificPrice.reduction_type == 'amount' && $product->specificPrice.reduction|floatval !=0}
     SAVE {convertPrice price=$productPriceWithoutReduction|floatval-$productPrice|floatval}
     {/if}

   {/strip}

..And this part inside a .js file:

if (combination.specific_price.reduction_type == 'amount') {
  $('#reduction_amount_display').html('SAVE ' + formatCurrency(discountValue, currencyFormat, currencySign, currencyBlank));
  $('#reduction_amount').show();
}

This works perfectly and this is how it looks like currently:

(note: the
 element has a fixed width and height)

The thing is, I'd like to give a line break after the "SAVE" part and be able to style the amount shown with a bigger font size. Demonstration:

This could be, as I mentioned above, achieved by separating the two with two other spans and stylizing them to how I want it to look. However, as my knowledge in Javascript is quite limited I do not know the correct way to insert a span. I tried several ways, for example adding html += '' right before formatCurrency and a closing tag after the paranthesis but this kinda messed up everything in the design for some reason. I also tried without using html += and plainly with quotes and the same thing happened. What solution is there for this? It does not necessarily have to be Javascript code. It could be a CSS or an HTML solution as well.

EDIT:

Using
 is unfortunately not plausible since I wouldn't be able to stylize the amount shown separately. Also, using that tag makes a huge gap that the amount goes way out of (overflows) the
 element.

Body:
You can wrap the dollar value in an element created by jQuery using append(), and style it accordingly with a given class.

var amount = $('#reduction_amount_display');

amount.html('SAVE ');

amount.append('<div class="style-amount">$10</div>');

.style-amount {
  font-size:32px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="reduction_amount_display">

</p>


问:
Is there an appropriate header for sending client library information in a REST Api?
I would like to send an identifier of my client libraries when calling my RESTful API. We have client libraries for Java, C#, Ruby, Python and others. For example, my Java client library could send:

```<code>User-Agent: java/1.10.2
</code>```

Is it better to use the User-Agent header or a custom header just for my application? The User-Agent header seems to be used more for browsers, and I am yet to find an API that uses the header for client libraries.

EDIT

The client library is used by our customers to consume our API and it handles all the request and response logic. It's just an easy way of calling our API.

The information will be used just for statistics and to help us identify which version of the client library our customers are using in the event of a bug.

答:
I think User-Agent is the appropriate header in this scenario.

According to Wikipedia, User-Agent is:

a user agent is software (a software agent) that is acting on behalf of a user... In many cases, a user agent acts as a client in a network protocol used in communications within a client–server distributed computing system. In particular, the Hypertext Transfer Protocol (HTTP) identifies the client software originating the request, using a user-agent header, even when the client is not operated by a user.

Thus, to become a User-Agent, it should be:

a software

client in a network protocol

on behalf of a user

According to the description in question, the client library (software) is used to consume API (on behalf of a user) and handles ALL the request & response logic (client in a network protocol), which makes it perfectly follow the above definition.

Also, the usage of client library information is typically what plain browser's User-Agent is used for.

Body:
I would like to send an identifier of my client libraries when calling my RESTful API. We have client libraries for Java, C#, Ruby, Python and others. For example, my Java client library could send:

User-Agent: java/1.10.2

Is it better to use the User-Agent header or a custom header just for my application? The User-Agent header seems to be used more for browsers, and I am yet to find an API that uses the header for client libraries.

EDIT

The client library is used by our customers to consume our API and it handles all the request and response logic. It's just an easy way of calling our API.

The information will be used just for statistics and to help us identify which version of the client library our customers are using in the event of a bug.


问:
How to get string objects instead of Unicode from JSON
I'm using Python 2 to parse JSON from ASCII encoded text files.

When loading these files with either json or simplejson, all my string values are cast to Unicode objects instead of string objects. The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.

Is it possible to get string objects instead of Unicode ones?

Example

```<code>>>> import json
>>> original_list = ['a', 'b']
>>> json_list = json.dumps(original_list)
>>> json_list
'["a", "b"]'
>>> new_list = json.loads(json_list)
>>> new_list
[u'a', u'b']  # I want these to be of type `str`, not `unicode`</code>```

(One easy and clean solution for 2017 is to use a recent version of Python — i.e. Python 3 and forward.)

答:
Check out this answer to a similar question like this which states that

The u- prefix just means that you have a Unicode string.  When you really use the string, it won't appear in your data.  Don't be thrown by the printed output.

For example, try this:

```<code>print mail_accounts[0]["i"]
</code>```

You won't see a u.

ContentLicense: CC BY-SA 4.0

Body:
I'm using Python 2 to parse JSON from ASCII encoded text files.

When loading these files with either json or simplejson, all my string values are cast to Unicode objects instead of string objects. The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them.

Is it possible to get string objects instead of Unicode ones?

Example

>>> import json
>>> original_list = ['a', 'b']
>>> json_list = json.dumps(original_list)
>>> json_list
'["a", "b"]'
>>> new_list = json.loads(json_list)
>>> new_list
[u'a', u'b']  # I want these to be of type `str`, not `unicode`

(One easy and clean solution for 2017 is to use a recent version of Python — i.e. Python 3 and forward.)

Body:
Check out this answer to a similar question like this which states that

The u- prefix just means that you have a Unicode string.  When you really use the string, it won't appear in your data.  Don't be thrown by the printed output.

For example, try this:

print mail_accounts[0]["i"]

You won't see a u.


问:
SyntaxError .../project/assets/images/logo.png: Unexpected character '�' (1:0)
this looks like a loader error, but shouldn't Expo/CRNA support png by default?

Here's my code:

```<code><View style={ styles.logo }>
  <Image source={require('../assets/images/logo.png')} style={{ flex:1, width: 150, height: 150 }} />
</View>

logo: {
  flex: 1,
  flexDirection: 'column',
  justifyContent: 'center',
  alignItems: 'center',

  height: 200,
},
</code>```

My images are cached using the example code on expo.io. This is the first asset I try. How do I fix this? I can't even find any loader configuration.

答: Alright, found it. It wasn't in my code, but I deleted the Expo app, restarted Expo XDE, and the error disappeared.</p>

Body:
this looks like a loader error, but shouldn't Expo/CRNA support png by default?

Here's my code:

<View style={ styles.logo }>
  <Image source={require('../assets/images/logo.png')} style={{ flex:1, width: 150, height: 150 }} />
</View>

logo: {
  flex: 1,
  flexDirection: 'column',
  justifyContent: 'center',
  alignItems: 'center',

  height: 200,
},

My images are cached using the example code on expo.io. This is the first asset I try. How do I fix this? I can't even find any loader configuration.


问:
/usr/lib64/libstdc++.so.6: version `CXXABI_1.3.8' not found when loading R packages
I know this question has been asked many times, but my case is very special: I am using a Linux cluster where I do not have root but could only use commands like "module load gcc" "module load mkl" "module load R3.3/mkl" and so on to load libraries.

Recently I tried installing mxnet on my account on that cluster, after that everything seems to work, but then I switched from R3.2 to R3.2 by using "module load R3.3/mkl" instead of "module load R3.2/mkl", but now when I try to load R packages like stringi, it said

library(stringi),
  Error in dyn.load(file, DLLpath = DLLpath, ...) :
    unable to load shared object '/home/hpc/pr74ze/ru37wof2/R/x86_64-pc-linux-gnu-library/3.3/stringi/libs/x
  86_64/stringi.so':
    /usr/lib64/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by /home/hpc/pr74ze/ru37wof2/R/x86
  _64-pc-linux-gnu-library/3.3/stringi/libs/x86_64/stringi.so)
  Error: package or namespace load failed for ‘stringi’

I remember that I have tried to load gsl before

```<code>module list
Currently Loaded Modulefiles:
 1) admin/1.0     3) intel/16.0   5) mpi.intel/5.1   7) R/3.3mkl   9) git/latest  11) gsl/1.16
 2) tempdir/1.0   4) mkl/11.3     6) lrz/default     8) nano/2.2  10) gcc/4.9
</code>```

if I run the following

```<code>echo $LD_LIBRARY_PATH
    /usr/lib64:/lrz/mnt/sys.x86_64/compilers/java/jdk1.7.0_51/jre/lib/amd64/server:/usr/lib64:/lrz/mnt/sys.x86
    _64/compilers/java/jdk1.7.0_51/jre/lib/amd64/server:/lrz/sys/libraries/gsl/1.16/lib:/lrz/sys/compilers/gcc
    /4.9.3/lib64:/lrz/sys/compilers/gcc/4.9.3/lib:/lrz/sys/applications/R/3.3.1_MKL/lib64/R/lib/x86_64:/lrz/sy
    s/intel/impi/5.1.3.181/lib64:/lrz/sys/intel/studio2016_u4/compilers_and_libraries_2016.4.258/linux/mkl/lib
    /intel64:/lrz/sys/intel/studio2016_u4/debugger_2016/libipt/intel64/lib:/lrz/sys/intel/studio2016_u4/compil
    ers_and_libraries_2016.4.258/linux/compiler/lib/intel64
</code>```

If I try to install the RcppZiggurat

```<code>* installing *source* package ‘RcppZiggurat’ ...
** package ‘RcppZiggurat’ successfully unpacked and MD5 sums checked
** libs
*** arch - x86_64
icpc -I/lrz/sys/applications/R/3.3.1_MKL/lib64/R/include -I/lrz/sys/applications/R/3.3.1_MKL/lib64/R/include/x86_64 -DNDEBUG -I. -I../inst/include -I/usr/local/include -I"/home/hpc/pr74ze/ru37wof2/R/x86_64-pc-lin
ux-gnu-library/3.3/Rcpp/include" -I"/home/hpc/pr74ze/ru37wof2/R/x86_64-pc-linux-gnu-library/3.3/RcppGSL/include"   -fpic  -O3  -c RcppExports.cpp -o RcppExports.o
In file included from /home/hpc/pr74ze/ru37wof2/R/x86_64-pc-linux-gnu-library/3.3/RcppGSL/include/RcppGSL.h(25),
                 from RcppExports.cpp(4):
/home/hpc/pr74ze/ru37wof2/R/x86_64-pc-linux-gnu-library/3.3/RcppGSL/include/RcppGSLForward.h(26): catastrophic error: cannot open source file "gsl/gsl_vector.h"
  #include <gsl/gsl_vector.h>
                              ^

compilation aborted for RcppExports.cpp (code 4)
</code>```

But how should I proceed to find out where the problem is?

答:
Note the 3.3 hiding inside of /home/hpc/pr74ze/ru37wof2/R/x86_64-pc-linux-gnu-library/3.3/stringi/libs/x 86_64/stringi.so -- you probably built that under 3.2 so it sits below /home/hpc/pr74ze/ru37wof2/R/x86_64-pc-linux-gnu-library/3.2.

You can overcome this by setting your own .libPaths(), either directly or via environment variables -- you may want something like ~/R/library.  See help(Startup) for details.

Body:
I know this question has been asked many times, but my case is very special: I am using a Linux cluster where I do not have root but could only use commands like "module load gcc" "module load mkl" "module load R3.3/mkl" and so on to load libraries.

Recently I tried installing mxnet on my account on that cluster, after that everything seems to work, but then I switched from R3.2 to R3.2 by using "module load R3.3/mkl" instead of "module load R3.2/mkl", but now when I try to load R packages like stringi, it said

library(stringi),
  Error in dyn.load(file, DLLpath = DLLpath, ...) :
    unable to load shared object '/home/hpc/pr74ze/ru37wof2/R/x86_64-pc-linux-gnu-library/3.3/stringi/libs/x
  86_64/stringi.so':
    /usr/lib64/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by /home/hpc/pr74ze/ru37wof2/R/x86
  _64-pc-linux-gnu-library/3.3/stringi/libs/x86_64/stringi.so)
  Error: package or namespace load failed for ‘stringi’

I remember that I have tried to load gsl before

module list
Currently Loaded Modulefiles:
 1) admin/1.0     3) intel/16.0   5) mpi.intel/5.1   7) R/3.3mkl   9) git/latest  11) gsl/1.16
 2) tempdir/1.0   4) mkl/11.3     6) lrz/default     8) nano/2.2  10) gcc/4.9

if I run the following

echo $LD_LIBRARY_PATH
    /usr/lib64:/lrz/mnt/sys.x86_64/compilers/java/jdk1.7.0_51/jre/lib/amd64/server:/usr/lib64:/lrz/mnt/sys.x86
    _64/compilers/java/jdk1.7.0_51/jre/lib/amd64/server:/lrz/sys/libraries/gsl/1.16/lib:/lrz/sys/compilers/gcc
    /4.9.3/lib64:/lrz/sys/compilers/gcc/4.9.3/lib:/lrz/sys/applications/R/3.3.1_MKL/lib64/R/lib/x86_64:/lrz/sy
    s/intel/impi/5.1.3.181/lib64:/lrz/sys/intel/studio2016_u4/compilers_and_libraries_2016.4.258/linux/mkl/lib
    /intel64:/lrz/sys/intel/studio2016_u4/debugger_2016/libipt/intel64/lib:/lrz/sys/intel/studio2016_u4/compil
    ers_and_libraries_2016.4.258/linux/compiler/lib/intel64

If I try to install the RcppZiggurat

* installing *source* package ‘RcppZiggurat’ ...
** package ‘RcppZiggurat’ successfully unpacked and MD5 sums checked
** libs
*** arch - x86_64
icpc -I/lrz/sys/applications/R/3.3.1_MKL/lib64/R/include -I/lrz/sys/applications/R/3.3.1_MKL/lib64/R/include/x86_64 -DNDEBUG -I. -I../inst/include -I/usr/local/include -I"/home/hpc/pr74ze/ru37wof2/R/x86_64-pc-lin
ux-gnu-library/3.3/Rcpp/include" -I"/home/hpc/pr74ze/ru37wof2/R/x86_64-pc-linux-gnu-library/3.3/RcppGSL/include"   -fpic  -O3  -c RcppExports.cpp -o RcppExports.o
In file included from /home/hpc/pr74ze/ru37wof2/R/x86_64-pc-linux-gnu-library/3.3/RcppGSL/include/RcppGSL.h(25),
                 from RcppExports.cpp(4):
/home/hpc/pr74ze/ru37wof2/R/x86_64-pc-linux-gnu-library/3.3/RcppGSL/include/RcppGSLForward.h(26): catastrophic error: cannot open source file "gsl/gsl_vector.h"
  #include <gsl/gsl_vector.h>
                              ^

compilation aborted for RcppExports.cpp (code 4)

But how should I proceed to find out where the problem is?


问:
Using openssh public key (ecdsa-sha2-nistp256) with Java Security
Is there a Java library/example to read an openssh format ecdsa public key to a JCE PublicKey in Java? I want to use EC for JWT .

The format I'm trying to read is as per authorized_keys, or Github API (e.g. https://api.github.com/users/davidcarboni/keys):  ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBK8hPtB72/sfYgNw1WTska2DNOJFx+QhUxuV6OLINSD2ty+6gxcM8yZrvMqWdMePGRb2cGh8L/0bGOk+64IQ/pM=

I've found this answer, which is fine for RSA and DSS:
Using public key from authorized_keys with Java security, and this discussion of the openssh format for ECDSA: https://security.stackexchange.com/questions/129910/ecdsa-why-do-ssh-keygen-and-java-generated-public-keys-have-different-sizes

However I'm getting lost trying to adapt the RSS/DSA code for ECDSA - I'm not sure how to set up an ECPublicKeySpec. It needs ECPoint, EllipticCurve, ECParameterSpec, ECField. The openssh format only contains two integers, which makes sense for ECPoint, but I don't know how to set up the rest.

I've been poking around a bunch of libraries, including jsch, sshj, ssh-tools and good old Bouncycastle. The closest I have is:

com.jcraft.jsch.KeyPair load = com.jcraft.jsch.KeyPair.load(jsch, null, bytes[openSshKey]);

Which loads the key fine, but doesn't get me to a JCE PublicKey - just a byte[] getPublicKeyBlob() method.

Am I missing something obvious?

答:
For completeness, here's the code I've gone with. It's nearly-pure JCE, with a sprinkling of Bouncycastle inside helper methods (this updates the example code in Using public key from authorized_keys with Java security):</p>

```<code>...
        } else if (type.startsWith("ecdsa-sha2-") &&
                (type.endsWith("nistp256") || type.endsWith("nistp384") || type.endsWith("nistp521"))) {
            // Based on RFC 5656, section 3.1 (https://tools.ietf.org/html/rfc5656#section-3.1)
            String identifier = decodeType();
            BigInteger q = decodeBigInt();
            ECPoint ecPoint = getECPoint(q, identifier);
            ECParameterSpec ecParameterSpec = getECParameterSpec(identifier);
            ECPublicKeySpec spec = new ECPublicKeySpec(ecPoint, ecParameterSpec);
            return KeyFactory.getInstance("EC").generatePublic(spec);
        } ...

/**
 * Provides a means to get from a parsed Q value to the X and Y point values.
 * that can be used to create and ECPoint compatible with ECPublicKeySpec.
 *
 * @param q          According to RFC 5656:
 *                   "Q is the public key encoded from an elliptic curve point into an octet string"
 * @param identifier According to RFC 5656:
 *                   "The string [identifier] is the identifier of the elliptic curve domain parameters."
 * @return An ECPoint suitable for creating a JCE ECPublicKeySpec.
 */
ECPoint getECPoint(BigInteger q, String identifier) {
    String name = identifier.replace("nist", "sec") + "r1";
    ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(name);
    org.bouncycastle.math.ec.ECPoint point = ecSpec.getCurve().decodePoint(q.toByteArray());
    BigInteger x = point.getAffineXCoord().toBigInteger();
    BigInteger y = point.getAffineYCoord().toBigInteger();
    System.out.println("BC x = " + x);
    System.out.println("BC y = " + y);
    return new ECPoint(x, y);
}

/**
 * Gets the curve parameters for the given key type identifier.
 *
 * @param identifier According to RFC 5656:
 *                   "The string [identifier] is the identifier of the elliptic curve domain parameters."
 * @return An ECParameterSpec suitable for creating a JCE ECPublicKeySpec.
 */
ECParameterSpec getECParameterSpec(String identifier) {
    try {
        // http://www.bouncycastle.org/wiki/pages/viewpage.action?pageId=362269#SupportedCurves(ECDSAandECGOST)-NIST(aliasesforSECcurves)
        String name = identifier.replace("nist", "sec") + "r1";
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
        parameters.init(new ECGenParameterSpec(name));
        return parameters.getParameterSpec(ECParameterSpec.class);
    } catch (InvalidParameterSpecException | NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Unable to get parameter spec for identifier " + identifier, e);
    }
}
</code>```

Body:
For completeness, here's the code I've gone with. It's nearly-pure JCE, with a sprinkling of Bouncycastle inside helper methods (this updates the example code in Using public key from authorized_keys with Java security):

...
        } else if (type.startsWith("ecdsa-sha2-") &&
                (type.endsWith("nistp256") || type.endsWith("nistp384") || type.endsWith("nistp521"))) {
            // Based on RFC 5656, section 3.1 (https://tools.ietf.org/html/rfc5656#section-3.1)
            String identifier = decodeType();
            BigInteger q = decodeBigInt();
            ECPoint ecPoint = getECPoint(q, identifier);
            ECParameterSpec ecParameterSpec = getECParameterSpec(identifier);
            ECPublicKeySpec spec = new ECPublicKeySpec(ecPoint, ecParameterSpec);
            return KeyFactory.getInstance("EC").generatePublic(spec);
        } ...

/**
 * Provides a means to get from a parsed Q value to the X and Y point values.
 * that can be used to create and ECPoint compatible with ECPublicKeySpec.
 *
 * @param q          According to RFC 5656:
 *                   "Q is the public key encoded from an elliptic curve point into an octet string"
 * @param identifier According to RFC 5656:
 *                   "The string [identifier] is the identifier of the elliptic curve domain parameters."
 * @return An ECPoint suitable for creating a JCE ECPublicKeySpec.
 */
ECPoint getECPoint(BigInteger q, String identifier) {
    String name = identifier.replace("nist", "sec") + "r1";
    ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(name);
    org.bouncycastle.math.ec.ECPoint point = ecSpec.getCurve().decodePoint(q.toByteArray());
    BigInteger x = point.getAffineXCoord().toBigInteger();
    BigInteger y = point.getAffineYCoord().toBigInteger();
    System.out.println("BC x = " + x);
    System.out.println("BC y = " + y);
    return new ECPoint(x, y);
}

/**
 * Gets the curve parameters for the given key type identifier.
 *
 * @param identifier According to RFC 5656:
 *                   "The string [identifier] is the identifier of the elliptic curve domain parameters."
 * @return An ECParameterSpec suitable for creating a JCE ECPublicKeySpec.
 */
ECParameterSpec getECParameterSpec(String identifier) {
    try {
        // http://www.bouncycastle.org/wiki/pages/viewpage.action?pageId=362269#SupportedCurves(ECDSAandECGOST)-NIST(aliasesforSECcurves)
        String name = identifier.replace("nist", "sec") + "r1";
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
        parameters.init(new ECGenParameterSpec(name));
        return parameters.getParameterSpec(ECParameterSpec.class);
    } catch (InvalidParameterSpecException | NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Unable to get parameter spec for identifier " + identifier, e);
    }
}


问:
filtering xpath with same functionality on different pages
Because I have the same functionality on several different pages and dont want to repeat myself. I want to make a xpath that retrieves the element with a wildcard. On each page I have a input ID, they look like this:

```<code>tbAAFound_fileUpload
tbBBFound_fileUpload
tbCCFound_fileUpload
tbDDFound_fileUpload
tbEEFound_fileUpload
</code>```

I want to make the xpath filter so that it searches if it can find the element on more than one page.

When I try the following xpath:

```<code>[FindsBy(How = How.XPath, Using = "//input[starts-with(@id, 'tb:') and contains(@id, '_fileUpload')]")]
private IWebElement UrlFileElement { get; set; }
</code>```

Selenium cannot find the element. Hope that you guys can help me out.

答: starts-with(@id, 'tb:') remove : , as it's not in id actually

Body:
Because I have the same functionality on several different pages and dont want to repeat myself. I want to make a xpath that retrieves the element with a wildcard. On each page I have a input ID, they look like this:

tbAAFound_fileUpload
tbBBFound_fileUpload
tbCCFound_fileUpload
tbDDFound_fileUpload
tbEEFound_fileUpload

I want to make the xpath filter so that it searches if it can find the element on more than one page.

When I try the following xpath:

[FindsBy(How = How.XPath, Using = "//input[starts-with(@id, 'tb:') and contains(@id, '_fileUpload')]")]
private IWebElement UrlFileElement { get; set; }

Selenium cannot find the element. Hope that you guys can help me out.


问:
Changing constraint multiplier using traits
I have several objects with a width of at least 75% of the screen width.
The issue is that they do not look as good on iPads or landscape mode.
I want to change the "75%" for different traits but couldn't figure out how.

I've looked at the details of the constraint and clicked on the PLUS icon:

After adding a variation, I see that I can change the constant but not the multiplier:

Anyone has any idea how this can be done elegantly?

Thanks

答:
Have two different constraint one for regular width (iPad) and one for compact width (iPhone).
Then add a variation to install the constraint only for the trait you are interested in by checking / unchecking the Installed option.</p>


问:
MSSQL Sum with Case Query Error
I have been trying to complete the below query however I cant seem to get it to work.

I wonder if anyone can see sometihng obvious that I am doing wrong?

MSSQL Server 2012.

I have tested the joins and some of the sub queries as you can see from the query it self and they work fine.

Any ideas?

```<code>SELECT b.CLIENT_NAME
  ,e.VARIABLE_NAME
  --,[TOTAL]
  --,AVG(a.TOTAL) AS [Total KPI]
   --, (SUM(d.WEEK1_NET)+SUM(d.WEEK2_NET)+SUM(d.WEEK3_NET)+SUM(d.WEEK4_NET))AS [Net Sales]
  ,SUM(
case
  when a.GRAPH_ID =  1 then 100/(SUM(d.WEEK1_NET)+SUM(d.WEEK2_NET)+SUM(d.WEEK3_NET)+SUM(d.WEEK4_NET))*SUM(a.TOTAL)
  when a.GRAPH_ID =  2 then 100/ (SUM(d.WEEK1_GROSS)+SUM(d.WEEK2_GROSS)+SUM(d.WEEK3_GROSS)+SUM(d.WEEK4_GROSS))*SUM(a.TOTAL)

  else AVG(a.TOTAL)
end) AS Project_KPI
FROM [MMAUDIT].[dbo].[MMA_KPIVAR_DAT] AS a

LEFT JOIN MMA_CLIENT_MST AS b
ON a.CLIENT_ID= b.CLIENT_ID

LEFT JOIN MMA_SITE_MST AS c
ON a.CLIENT_ID= c.CLIENT_ID
AND a.SITE_ID= c.SITE_ID

LEFT JOIN MMA_SALESPERF_DAT AS d
ON a.CLIENT_ID= d.CLIENT_ID
AND a.SITE_ID= d.SITE_ID
AND a.AUDIT_DATE= d.AUDIT_DATE

LEFT JOIN MMA_KPIVAR_MST As e
ON a.CLIENT_ID= e.CLIENT_ID
AND a.CHART_ID=e.CHART_ID
AND a.GRAPH_ID= e.GRAPH_ID
AND a.VARIABLE_ID= e.VARIABLE_ID

WHERE a.CLIENT_ID= 18
AND a.AUDIT_DATE BETWEEN '2017-01-01' AND '2017-07-01'
--AND a.GRAPH_ID IN (3,4,5,6)
GROUP BY b.CLIENT_NAME
  ,e.VARIABLE_NAME
  --,[TOTAL]'
</code>```

Thank you John

答:
You can't have nested SUMs or other aggregates. A simple example is here.

```<code>SUM(
case
  when a.GRAPH_ID =  1 then 100/(SUM(d.WEEK1_NET)+SUM(d.WEEK2_NET)+SUM(d.WEEK3_NET)+SUM(d.WEEK4_NET))*SUM(a.TOTAL)
  when a.GRAPH_ID =  2 then 100/ (SUM(d.WEEK1_GROSS)+SUM(d.WEEK2_GROSS)+SUM(d.WEEK3_GROSS)+SUM(d.WEEK4_GROSS))*SUM(a.TOTAL)

  else AVG(a.TOTAL)
end)
</code>```

is a problem as it nests SUM with both SUM and AVG and the calculation is ambiguous. The easiest fix it to do you inner SUMs: SUM(d.WEEK1_NET) etc in a subquery and then use the values in the case statement in the main query.

Title: MSSQL Sum with Case Query Error

Body:
I have been trying to complete the below query however I cant seem to get it to work.

I wonder if anyone can see sometihng obvious that I am doing wrong?

MSSQL Server 2012.

I have tested the joins and some of the sub queries as you can see from the query it self and they work fine.

Any ideas?

SELECT b.CLIENT_NAME
  ,e.VARIABLE_NAME
  --,[TOTAL]
  --,AVG(a.TOTAL) AS [Total KPI]
   --, (SUM(d.WEEK1_NET)+SUM(d.WEEK2_NET)+SUM(d.WEEK3_NET)+SUM(d.WEEK4_NET))AS [Net Sales]
  ,SUM(
case
  when a.GRAPH_ID =  1 then 100/(SUM(d.WEEK1_NET)+SUM(d.WEEK2_NET)+SUM(d.WEEK3_NET)+SUM(d.WEEK4_NET))*SUM(a.TOTAL)
  when a.GRAPH_ID =  2 then 100/ (SUM(d.WEEK1_GROSS)+SUM(d.WEEK2_GROSS)+SUM(d.WEEK3_GROSS)+SUM(d.WEEK4_GROSS))*SUM(a.TOTAL)

  else AVG(a.TOTAL)
end) AS Project_KPI
FROM [MMAUDIT].[dbo].[MMA_KPIVAR_DAT] AS a

LEFT JOIN MMA_CLIENT_MST AS b
ON a.CLIENT_ID= b.CLIENT_ID

LEFT JOIN MMA_SITE_MST AS c
ON a.CLIENT_ID= c.CLIENT_ID
AND a.SITE_ID= c.SITE_ID

LEFT JOIN MMA_SALESPERF_DAT AS d
ON a.CLIENT_ID= d.CLIENT_ID
AND a.SITE_ID= d.SITE_ID
AND a.AUDIT_DATE= d.AUDIT_DATE

LEFT JOIN MMA_KPIVAR_MST As e
ON a.CLIENT_ID= e.CLIENT_ID
AND a.CHART_ID=e.CHART_ID
AND a.GRAPH_ID= e.GRAPH_ID
AND a.VARIABLE_ID= e.VARIABLE_ID

WHERE a.CLIENT_ID= 18
AND a.AUDIT_DATE BETWEEN '2017-01-01' AND '2017-07-01'
--AND a.GRAPH_ID IN (3,4,5,6)
GROUP BY b.CLIENT_NAME
  ,e.VARIABLE_NAME
  --,[TOTAL]'

Thank you John

Body:
You can't have nested SUMs or other aggregates. A simple example is here.

SUM(
case
  when a.GRAPH_ID =  1 then 100/(SUM(d.WEEK1_NET)+SUM(d.WEEK2_NET)+SUM(d.WEEK3_NET)+SUM(d.WEEK4_NET))*SUM(a.TOTAL)
  when a.GRAPH_ID =  2 then 100/ (SUM(d.WEEK1_GROSS)+SUM(d.WEEK2_GROSS)+SUM(d.WEEK3_GROSS)+SUM(d.WEEK4_GROSS))*SUM(a.TOTAL)

  else AVG(a.TOTAL)
end)

is a problem as it nests SUM with both SUM and AVG and the calculation is ambiguous. The easiest fix it to do you inner SUMs: SUM(d.WEEK1_NET) etc in a subquery and then use the values in the case statement in the main query.


问:
How to embed small icon in UILabel
I need to embed small icons ( sort of custom bullets ) to my UILabel in iOS7.
How can I do this in interface designer? Or at least in code?

In Android there are leftDrawable and rightDrawable for labels, but how it is done in iOS?
Sample in android :

答:
Swift 3 UILabel extention

Tip: If you need some space between the image and the text just use a space or two before the labelText.

```<code>extension UILabel {
    func addIconToLabel(imageName: String, labelText: String, bounds_x: Double, bounds_y: Double, boundsWidth: Double, boundsHeight: Double) {
        let attachment = NSTextAttachment()
        attachment.image = UIImage(named: imageName)
        attachment.bounds = CGRect(x: bounds_x, y: bounds_y, width: boundsWidth, height: boundsHeight)
        let attachmentStr = NSAttributedString(attachment: attachment)
        let string = NSMutableAttributedString(string: "")
        string.append(attachmentStr)
        let string2 = NSMutableAttributedString(string: labelText)
        string.append(string2)
        self.attributedText = string
    }
}
</code>```

Title: How to embed small icon in UILabel

Body:
Swift 3 UILabel extention

Tip: If you need some space between the image and the text just use a space or two before the labelText.

extension UILabel {
    func addIconToLabel(imageName: String, labelText: String, bounds_x: Double, bounds_y: Double, boundsWidth: Double, boundsHeight: Double) {
        let attachment = NSTextAttachment()
        attachment.image = UIImage(named: imageName)
        attachment.bounds = CGRect(x: bounds_x, y: bounds_y, width: boundsWidth, height: boundsHeight)
        let attachmentStr = NSAttributedString(attachment: attachment)
        let string = NSMutableAttributedString(string: "")
        string.append(attachmentStr)
        let string2 = NSMutableAttributedString(string: labelText)
        string.append(string2)
        self.attributedText = string
    }
}


问:
Reverse proxy with openid connect redirection
In my application I have integrated Identity server 3 with openid-connect.
On our production server our website is behind a reverse proxy which is causing problems;

When the user logs in and is redirected back by identity server, our application wants to redirect the user to his original location (the page with the AuthorizeAttribute).
The problem here is that the user is redirected to the hidden url instead of the public url used by the reverse proxy.

How can I redirect the user to the public url?

答:
After a long search this is the fix:

The OWIN middleware UseOpenIdConnectAuthentication has a property Notifications in the Options property.
This Notifications property has a func SecurityTokenValidated. In this function you can modify the Redirect Uri.

```<code>app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
    Authority = "https://idp.io",
    ClientId = "clientid",
    RedirectUri = "https://mywebsite.io",
    ResponseType = "code id_token token",
    Scope = "openid profile",
    SignInAsAuthenticationType = "Cookies",
    UseTokenLifetime = false,
    Notifications = new OpenIdConnectAuthenticationNotifications
    {
        SecurityTokenValidated = notification =>
        {
            notification.AuthenticationTicket.Properties.RedirectUri = RewriteToPublicOrigin(notification.AuthenticationTicket.Properties.RedirectUri);
            return Task.CompletedTask;
        }
    }
});
</code>```

This is the function which rewrites the url to the public origin:

```<code>private static string RewriteToPublicOrigin(string originalUrl)
{
    var publicOrigin = ConfigurationManager.AppSettings["app:identityServer.PublicOrigin"];
    if (!string.IsNullOrEmpty(publicOrigin))
    {
        var uriBuilder = new UriBuilder(originalUrl);
        var publicOriginUri = new Uri(publicOrigin);
        uriBuilder.Host = publicOriginUri.Host;
        uriBuilder.Scheme = publicOriginUri.Scheme;
        uriBuilder.Port = publicOriginUri.Port;
        var newUrl = uriBuilder.Uri.AbsoluteUri;

        return newUrl;
    }

    return originalUrl;
}
</code>```

Now the OpenIdConnect redirects the user to the public url instead of the non-public webserver url.

Body:
After a long search this is the fix:

The OWIN middleware UseOpenIdConnectAuthentication has a property Notifications in the Options property.
This Notifications property has a func SecurityTokenValidated. In this function you can modify the Redirect Uri.

app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
    Authority = "https://idp.io",
    ClientId = "clientid",
    RedirectUri = "https://mywebsite.io",
    ResponseType = "code id_token token",
    Scope = "openid profile",
    SignInAsAuthenticationType = "Cookies",
    UseTokenLifetime = false,
    Notifications = new OpenIdConnectAuthenticationNotifications
    {
        SecurityTokenValidated = notification =>
        {
            notification.AuthenticationTicket.Properties.RedirectUri = RewriteToPublicOrigin(notification.AuthenticationTicket.Properties.RedirectUri);
            return Task.CompletedTask;
        }
    }
});

This is the function which rewrites the url to the public origin:

private static string RewriteToPublicOrigin(string originalUrl)
{
    var publicOrigin = ConfigurationManager.AppSettings["app:identityServer.PublicOrigin"];
    if (!string.IsNullOrEmpty(publicOrigin))
    {
        var uriBuilder = new UriBuilder(originalUrl);
        var publicOriginUri = new Uri(publicOrigin);
        uriBuilder.Host = publicOriginUri.Host;
        uriBuilder.Scheme = publicOriginUri.Scheme;
        uriBuilder.Port = publicOriginUri.Port;
        var newUrl = uriBuilder.Uri.AbsoluteUri;

        return newUrl;
    }

    return originalUrl;
}

Now the OpenIdConnect redirects the user to the public url instead of the non-public webserver url.


问:
Combination of rules with Regex
In an android project, im trying to validate a password that the user inputs, and it must follow some rules

The rules are:
it must have 7 characters and 3 of the following conditions

**

-One lowercase character

-One uppercase character

-One number

-One special character

**

for example:

asd123!!!

PPPppp000

TTT999###

i was trying with this regex

```<code>^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{7,}+$
</code>```

but this enforces all rules at same time.

答:
The approach is wrong here. The regex you created looks like a monster from under the bed, and is highly illegible even for someone regex-literate.

Why not split it into 4 (or as much as there are rules) regexes and check against whether 3 of them return a match? Not only will you make your regexes cleaner, but you will be able to add more rules if need be without changing whole regex.

You can also use inbuilt methods for checking (if applicable under Android development kit).

Some pseudocode would look like this:

```<code>result1 = Regex.IsMatch(password, rule1regex)
result2 = Regex.IsMatch(password, rule2regex)
...
resultN = Regex.IsMatch(password, rule3regex)

if(three_out_of_four_rules_apply)
    password_valid = true
</code>```

You can also apply method suggested in comments by @pskink and iterate over each character of a password and set the output accordingly.

Title: Combination of rules with Regex

Body:
In an android project, im trying to validate a password that the user inputs, and it must follow some rules

The rules are:
it must have 7 characters and 3 of the following conditions

**

-One lowercase character

-One uppercase character

-One number

-One special character

**

for example:

asd123!!!

PPPppp000

TTT999###

i was trying with this regex

^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{7,}+$

but this enforces all rules at same time.

Body:
The approach is wrong here. The regex you created looks like a monster from under the bed, and is highly illegible even for someone regex-literate.

Why not split it into 4 (or as much as there are rules) regexes and check against whether 3 of them return a match? Not only will you make your regexes cleaner, but you will be able to add more rules if need be without changing whole regex.

You can also use inbuilt methods for checking (if applicable under Android development kit).

Some pseudocode would look like this:

result1 = Regex.IsMatch(password, rule1regex)
result2 = Regex.IsMatch(password, rule2regex)
...
resultN = Regex.IsMatch(password, rule3regex)

if(three_out_of_four_rules_apply)
    password_valid = true

You can also apply method suggested in comments by @pskink and iterate over each character of a password and set the output accordingly.


问:
Download a PDF automatically once its generated (Node, Express)
I am using following node module html-pdf
to convert html to pdf. I have successfully converted html to pdf but I am having trouble downloading the file once it has been created.

Code to generate PDF:

```<code>var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('./test/businesscard.html', 'utf8');
var options = { format: 'Letter' };

pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/app/businesscard.pdf' }
});
</code>```

How can I either open the PDF within the browser for the user to see or automatically download the pdf within the browser without the user having to go through another step.

答:
I just made some changes to your code.In this code I create a route. Whenever you made a request with this route it converts HTML file to PDF and creating a pdf file into your directory from where you are executing. And at the sametime it displays the html file in browser with downloading option also. Hope this helps for you. And here is my code.

```<code>var express=require('express');
var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('C:/Users/nodejs/tasks/file.html', 'utf8');
var options = { format: 'Letter' };
var app=express();
app.get('/file',function(request,response)
{
    pdf.create(html, options).toFile('./businesscaw.pdf', function(err, res) {
        if (err) return console.log(err);
        console.log(res);
        var file= 'C:/Users/nodejs/tasks/businesscaw.pdf';
        fs.readFile(file,function(err,data){
            response.contentType("application/pdf");
            response.send(data);
        });
    });
});
app.listen(3000,function(){
    console.log("Server listening on port http://loalhost:3000");
});
</code>```

Output:
See the output in browser like : localhost:3000/file

Body:
I am using following node module html-pdf
to convert html to pdf. I have successfully converted html to pdf but I am having trouble downloading the file once it has been created.

Code to generate PDF:

var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('./test/businesscard.html', 'utf8');
var options = { format: 'Letter' };

pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/app/businesscard.pdf' }
});

How can I either open the PDF within the browser for the user to see or automatically download the pdf within the browser without the user having to go through another step.

Body:
I just made some changes to your code.In this code I create a route. Whenever you made a request with this route it converts HTML file to PDF and creating a pdf file into your directory from where you are executing. And at the sametime it displays the html file in browser with downloading option also. Hope this helps for you. And here is my code.

var express=require('express');
var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('C:/Users/nodejs/tasks/file.html', 'utf8');
var options = { format: 'Letter' };
var app=express();
app.get('/file',function(request,response)
{
    pdf.create(html, options).toFile('./businesscaw.pdf', function(err, res) {
        if (err) return console.log(err);
        console.log(res);
        var file= 'C:/Users/nodejs/tasks/businesscaw.pdf';
        fs.readFile(file,function(err,data){
            response.contentType("application/pdf");
            response.send(data);
        });
    });
});
app.listen(3000,function(){
    console.log("Server listening on port http://loalhost:3000");
});

Output:
See the output in browser like : localhost:3000/file


问:
How to resolve tomcat memory leak warning - The web application have started a thread but has failed to stop it
I am using com.ning.async-http-client(1.9.40) library to post asynchronous request. While shutting down tomcat, I am getting below messages in catalina.out log :-

```<code>SEVERE: The web application [/xyz] appears to have started a thread named [Hashed wheel timer #1] but has failed to stop it. This is very likely to create a memory leak.
Jul 03, 2017 1:27:15 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
SEVERE: The web application [/xyz] appears to have started a thread named [New I/O worker #1] but has failed to stop it. This is very likely to create a memory leak.
Jul 03, 2017 1:27:15 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
SEVERE: The web application [/xyz] appears to have started a thread named [New I/O worker #2] but has failed to stop it. This is very likely to create a memory leak.
Jul 03, 2017 1:27:15 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
SEVERE: The web application [/xyz] appears to have started a thread named [New I/O boss #3] but has failed to stop it. This is very likely to create a memory leak.
Jul 03, 2017 1:27:15 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
SEVERE: The web application [/xyz] appears to have started a thread named [Hashed wheel timer #2] but has failed to stop it. This is very likely to create a memory leak.**
</code>```

The state of these threads are:

```<code>"New I/O boss #3" prio=10 tid=0x00007ff3a00f9000 nid=0x17a9 runnable [0x00007ff3878f7000]
"New I/O worker #2" daemon prio=10 tid=0x00007ff3a00aa800 nid=0x17a8 runnable [0x00007ff3879f8000]
"New I/O worker #1" daemon prio=10 tid=0x00007ff3a00b8800 nid=0x17a7 runnable [0x00007ff387af9000]
"Hashed wheel timer #2" prio=10 tid=0x00007ff3a020e800 nid=0x17aa waiting on condition [0x00007ff3875f0000]
"Hashed wheel timer #1" prio=10 tid=0x00007ff3a0083000 nid=0x17a6 sleeping[0x00007ff387bfa000]
</code>```

Please suggest a way to stop these threads from application.

答:
The AsyncHttpClient implements Closeable. It suffices to call close() on it when your application shuts down.

This will clean up the resources used by AsyncHttpClient.

To illustrate :

```<code>public static void main(String[] args) throws Exception {
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    Future<Response> f = asyncHttpClient.prepareGet("http://www.google.com/").execute();
    Response r = f.get();

    asyncHttpClient.close(); // when this is commented out, the application won't exit, as the non daemon threads prevent it.
}
</code>```

Body:
I am using com.ning.async-http-client(1.9.40) library to post asynchronous request. While shutting down tomcat, I am getting below messages in catalina.out log :-

SEVERE: The web application [/xyz] appears to have started a thread named [Hashed wheel timer #1] but has failed to stop it. This is very likely to create a memory leak.
Jul 03, 2017 1:27:15 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
SEVERE: The web application [/xyz] appears to have started a thread named [New I/O worker #1] but has failed to stop it. This is very likely to create a memory leak.
Jul 03, 2017 1:27:15 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
SEVERE: The web application [/xyz] appears to have started a thread named [New I/O worker #2] but has failed to stop it. This is very likely to create a memory leak.
Jul 03, 2017 1:27:15 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
SEVERE: The web application [/xyz] appears to have started a thread named [New I/O boss #3] but has failed to stop it. This is very likely to create a memory leak.
Jul 03, 2017 1:27:15 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
SEVERE: The web application [/xyz] appears to have started a thread named [Hashed wheel timer #2] but has failed to stop it. This is very likely to create a memory leak.**

The state of these threads are:

"New I/O boss #3" prio=10 tid=0x00007ff3a00f9000 nid=0x17a9 runnable [0x00007ff3878f7000]
"New I/O worker #2" daemon prio=10 tid=0x00007ff3a00aa800 nid=0x17a8 runnable [0x00007ff3879f8000]
"New I/O worker #1" daemon prio=10 tid=0x00007ff3a00b8800 nid=0x17a7 runnable [0x00007ff387af9000]
"Hashed wheel timer #2" prio=10 tid=0x00007ff3a020e800 nid=0x17aa waiting on condition [0x00007ff3875f0000]
"Hashed wheel timer #1" prio=10 tid=0x00007ff3a0083000 nid=0x17a6 sleeping[0x00007ff387bfa000]

Please suggest a way to stop these threads from application.

Body:
The AsyncHttpClient implements Closeable. It suffices to call close() on it when your application shuts down.

This will clean up the resources used by AsyncHttpClient.

To illustrate :

public static void main(String[] args) throws Exception {
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    Future<Response> f = asyncHttpClient.prepareGet("http://www.google.com/").execute();
    Response r = f.get();

    asyncHttpClient.close(); // when this is commented out, the application won't exit, as the non daemon threads prevent it.
}


问:
Jira release version as an input step parameter
I try to load a jira release version into a variable using an input step.

```<code>node {
    def version = input message: 'Approve', parameters: [[$class: 'JiraVersionParameterDefinition', description: 'Select the version', jiraProjectKey: 'APP', jiraReleasePattern: '^1\\.([0-9]+)\\.([0-9]+)$', jiraShowArchived: 'false', jiraShowReleased: 'false', name: 'version']]
    echo version
}
</code>```

The input shows me a version and I can select it but the result (the variable version) is always null. Is this currently not supported or how is it done?

答:
This seems to be a bug in the JIRA Plugin for Jenkins.

I've created an Issue for that: JENKINS-45293

As a workaround you can use the JIRA Steps Plugin (step jiraGetProjectVersions) to query the versions and then put them into a choice parameter. Be aware of Bug JENKINS-40358 when filling in the choices using the Snippet Generator.

Body:
I try to load a jira release version into a variable using an input step.

node {
    def version = input message: 'Approve', parameters: [[$class: 'JiraVersionParameterDefinition', description: 'Select the version', jiraProjectKey: 'APP', jiraReleasePattern: '^1\\.([0-9]+)\\.([0-9]+)$', jiraShowArchived: 'false', jiraShowReleased: 'false', name: 'version']]
    echo version
}

The input shows me a version and I can select it but the result (the variable version) is always null. Is this currently not supported or how is it done?


问:
Angular checked property with radio button
May be this was a simple problem i am trying to set checked attribute to radio buttons based on variable value

$scope.art.is_copyright_protected = ($scope.art.is_copyright_protected==1)?true:false;

```<code> <div class="form-inline checkbox-wrap">
      <fieldset class="form-group">
        <input name="is_copyright_protected"  ng-model="art.is_copyright_protected"     type="radio" id="radio11" >
        <label for="radio11">Yes</label>
     </fieldset>
  <fieldset class="form-group">
      <input name="is_copyright_protected"  ng-model="art.is_copyright_protected"   type="radio" id="radio21"><label for="radio21">No</label>
</fieldset>
</div>
</code>```

But the problem is radio button is never checked

答:
You should use ng-value directive

Binds the given expression to the value of the element.

```<code><input ng-value="1" ng-model="art.is_copyright_protected" type="radio">
</code>```

(function(angular) {
  'use strict';
  angular.module('myApp', [])
    .controller('Controller', ['$scope', function($scope) {
      $scope.art = {
        is_copyright_protected: 0
      };
    }]);
})(window.angular);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="Controller">
    <div class="form-inline checkbox-wrap">
      <fieldset class="form-group">
        <input name="is_copyright_protected" ng-value="1" ng-model="art.is_copyright_protected" type="radio" id="radio11">
        <label for="radio11">Yes</label>
      </fieldset>
      <fieldset class="form-group">
        <input name="is_copyright_protected" ng-value="0" ng-model="art.is_copyright_protected" type="radio" id="radio21"><label for="radio21">No</label>
      </fieldset>

      {{art.is_copyright_protected}}
    </div>
  </div>
</div></code>```

Body:
May be this was a simple problem i am trying to set checked attribute to radio buttons based on variable value

$scope.art.is_copyright_protected = ($scope.art.is_copyright_protected==1)?true:false;

      <fieldset class="form-group">
        <input name="is_copyright_protected"  ng-model="art.is_copyright_protected"     type="radio" id="radio11" >
        Yes
     </fieldset>
  <fieldset class="form-group">
      <input name="is_copyright_protected"  ng-model="art.is_copyright_protected"   type="radio" id="radio21">No
</fieldset>

But the problem is radio button is never checked

Body:
You should use ng-value directive

Binds the given expression to the value of the element.

<input ng-value="1" ng-model="art.is_copyright_protected" type="radio">

(function(angular) {
  'use strict';
  angular.module('myApp', [])
    .controller('Controller', ['$scope', function($scope) {
      $scope.art = {
        is_copyright_protected: 0
      };
    }]);
})(window.angular);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="Controller">
    <div class="form-inline checkbox-wrap">
      <fieldset class="form-group">
        <input name="is_copyright_protected" ng-value="1" ng-model="art.is_copyright_protected" type="radio" id="radio11">
        <label for="radio11">Yes</label>
      </fieldset>
      <fieldset class="form-group">
        <input name="is_copyright_protected" ng-value="0" ng-model="art.is_copyright_protected" type="radio" id="radio21"><label for="radio21">No</label>
      </fieldset>

      {{art.is_copyright_protected}}
    </div>
  </div>
</div>


问:
Hibernate sequence not generated
Im working on a Spring (not Boot!) project, with Hibernate and PostgreSQL database. I also use Flyway for migration.
I use Flyway to generate the schema of the database, and insert initial data to it with given SQL scripts in my resources folder. For this reason, I excluded the hibernate.hbm2ddl.auto property from my hibernate.properties file.
On the startup, the schema is created and the data is inserted to the database, but my problem is, that this way Hibernate doesn't generate its sequence, and I cant save data from the application:

```<code>org.postgresql.util.PSQLException: ERROR: relation "hibernate_sequence" does not exist
</code>```

What can I do with this?

答:
As you didn't provide any code not sure what is wrong there, assume missing @SequenceGenerator annotation, I'll provide the one is working for me.

```<code>@Entity
@Table(name = "your_table")
@SequenceGenerator(name = "your_table_id_seq", sequenceName = "your_table_id_seq", allocationSize = 1)
public class YourTable implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "your_table_id_seq")
private Long id;
</code>```

.
.
.

Title: Hibernate sequence not generated

Body:
Im working on a Spring (not Boot!) project, with Hibernate and PostgreSQL database. I also use Flyway for migration.
I use Flyway to generate the schema of the database, and insert initial data to it with given SQL scripts in my resources folder. For this reason, I excluded the hibernate.hbm2ddl.auto property from my hibernate.properties file.
On the startup, the schema is created and the data is inserted to the database, but my problem is, that this way Hibernate doesn't generate its sequence, and I cant save data from the application:

org.postgresql.util.PSQLException: ERROR: relation "hibernate_sequence" does not exist

What can I do with this?

Body:
As you didn't provide any code not sure what is wrong there, assume missing @SequenceGenerator annotation, I'll provide the one is working for me.

@Entity
@Table(name = "your_table")
@SequenceGenerator(name = "your_table_id_seq", sequenceName = "your_table_id_seq", allocationSize = 1)
public class YourTable implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "your_table_id_seq")
private Long id;

.
.
.


问:
Garbage collector performance on different machines
I have a large memory consumption .NET 2.0 application. Ussually the GC handles the cleaning of the memory well.
However, I have a case where the application is installed in 2 different machines, one with 2gb of memory and one with 3gb of memory. In the 3gb of memory it crashes with Out Of Memory exception, while in the 2gb it nevers fails.
The .net runtime is the same in both machines and also the application installation is the same.
It is possible that when there is more memory the trigger to start the Grabage Collector is not raised on time?</p>

答:
The amount of RAM has nothing to do with the amount of memory available to a .NET program.  All modern operating systems provide virtual memory.  On Windows, the typical amount of virtual memory available to a program is a bit less than 2 gigabytes.  There's a special boot option (/3GB) that increases that to 3 gigabytes, at a cost of taking addressable memory away from the operating system.  It doesn't work anymore on most modern machines, the video card tends to eat up too much addressable physical memory.  It isn't impossible to actually get less than 2GB because of this.

If the machine runs a 64-bit operating system then you'll get close to 4 gigabytes if the code runs in x86 mode.  And oodles of virtual memory in x64 mode, limited only by the maximum size of the paging file.

These virtual memory sizes are completely independent of the actual amount of RAM installed on the machine.  If you have less RAM than addressable virtual memory space, very common 15 years ago, then it is possible to invoke so-called 'paging file thrashing'.  You see the operating system trying to provide enough available RAM to honor the program's need to use too much virtual memory at the same time.  It swaps data between RAM and the paging file.  That can severely slow down the machine, you run out of patience before you run out of memory.

An OutOfMemoryException tells you that the program ran out of addressable virtual memory.  The most typical cause is not actually completely depleting all address space, it is running out of holes big enough to fit the object you're trying to allocate.  Virtual memory can become fragmented.  The SysInterals' VMMap utility can give you insight in how the virtual memory of your program is divvied-up.

Running out of virtual memory is quite difficult to deal with, it is essentially an asynchronous exception that you cannot recover from.  With the exception of doing something like loading a bitmap, the kind of object that requires lots of (unmanaged) memory and therefore almost always has trouble with finding a large enough hole.  In general, your program should never get any closer than using up half of the available space.  That's not usually difficult, a gigabyte is a lot of memory.  When your program's needs are fundamentally beyond that limit then you must specify a 64-bit operating system requirement for your program.  A two hundred dollar solution.