问:
Zend framework facebook redirect URL to canvas application URL
I am currently developing a facebook canvas (iframe) based application. Is there any way to get Zend framework to output URLs like this:

```<code>http://app.facebook.com/appName/controller/action
</code>```

intead of getting

```<code>http://www.domain.com/controller/action ?
</code>```

It is not so important because due to iframe based app everything is working fine, but I'd like to provide better user experince and getting the url

```<code>http://app.facebook.com/appName/
</code>```

is not user friendly at all. Probably the solution is very easy but I am completely "stack". The application is devided to modules so I can change sth in Boostrap.php which is probably to hold the solution underneath my nose but I can not see it..:-/

EDIT:
Maybe i did not expressed it as I should have. The problem is not within facebook. The problem is in zend itself. It outputs the original application (e.g. myapp.example.com) URL and I want it to output http://app.facebook.com/myapp

Thanks in advance.

Lukas

答:
Finally, I managed to solve this issue. So for fellow developers I am posting here my solution.

The soulition is to be honest a bit complicated but:

```<code>Use Zend_Controller_Router_Route_Hostname
</code>```

The example of usage can be found in http://framework.zend.com/manual/en/zend.controller.router.html the and then Chain it with classic route like:

```<code>$hostnameRoute = new
    Zend_Controller_Router_Route_Hostname(
                     ':username.users.example.com',
                     array(
                  'controller' => 'profile',
                  'action'     => 'userinfo'
              )
      );
$plainPathRoute = new Zend_Controller_Router_Route_Static('');
$router->addRoute('user', $hostnameRoute->chain($plainPathRoute);
</code>```

Body:
I am currently developing a facebook canvas (iframe) based application. Is there any way to get Zend framework to output URLs like this:

http://app.facebook.com/appName/controller/action

intead of getting

http://www.domain.com/controller/action ?

It is not so important because due to iframe based app everything is working fine, but I'd like to provide better user experince and getting the url

http://app.facebook.com/appName/

is not user friendly at all. Probably the solution is very easy but I am completely "stack". The application is devided to modules so I can change sth in Boostrap.php which is probably to hold the solution underneath my nose but I can not see it..:-/

EDIT:
Maybe i did not expressed it as I should have. The problem is not within facebook. The problem is in zend itself. It outputs the original application (e.g. myapp.example.com) URL and I want it to output http://app.facebook.com/myapp

Thanks in advance.

Lukas

Body:
Finally, I managed to solve this issue. So for fellow developers I am posting here my solution.

The soulition is to be honest a bit complicated but:

Use Zend_Controller_Router_Route_Hostname

The example of usage can be found in http://framework.zend.com/manual/en/zend.controller.router.html the and then Chain it with classic route like:

$hostnameRoute = new
    Zend_Controller_Router_Route_Hostname(
                     ':username.users.example.com',
                     array(
                  'controller' => 'profile',
                  'action'     => 'userinfo'
              )
      );
$plainPathRoute = new Zend_Controller_Router_Route_Static('');
$router->addRoute('user', $hostnameRoute->chain($plainPathRoute);


来源: stackexchange

问:
Make distinction between inner and outer NA's in a raster in R
In R, how could I make the distinction between inner and outer NA's in a raster with some shape having NA's both around but also inside?

In the example below, how could I for exemple select only the NA's outside the R logo (i.e., how can I make everything which is included in the circle of the logo appear as white)?

```<code>library(raster)
r <- raster(system.file("external/rlogo.grd", package="raster"))
r[r>240] = NA
par(mfrow=c(1,2))
plot(r, main='r')
plot(is.na(r), main="is.na(r)")
</code>```

答:
You don't really have many options. This type of analysis usually requires some more elaborate methods. Here however is a simple workaround using the clumpfunction:

```<code>#your inital code
library(raster)
r <- raster(system.file("external/rlogo.grd", package="raster"))
rna <- rc <- r
rna[r>240] = NA
par(mfrow=c(2,2))

#reclass values <=240 to NA (needed for clump function.
#Here, NAs are used to seperate clumps)
rc[r<=240] <- NA
rc <- clump(rc)

#what you get after applying the clump function
#are homogenous areas that are separated by NAs.
#Let's reclassify all areas with an ID > 8.
#In this case, these are the areas inside the ring.
rc_reclass <- rc
rc_reclass[rc_reclass>8]  <- 100

#let's do some plotting
plot(r, main='r')
plot(is.na(rna), main="is.na(r)")
plot(rc, main="clumps")
plot(rc_reclass, main="clumps reclass")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In R, how could I make the distinction between inner and outer NA's in a raster with some shape having NA's both around but also inside?

In the example below, how could I for exemple select only the NA's outside the R logo (i.e., how can I make everything which is included in the circle of the logo appear as white)?

library(raster)
r <- raster(system.file("external/rlogo.grd", package="raster"))
r[r>240] = NA
par(mfrow=c(1,2))
plot(r, main='r')
plot(is.na(r), main="is.na(r)")

Body:
You don't really have many options. This type of analysis usually requires some more elaborate methods. Here however is a simple workaround using the clumpfunction:

#your inital code
library(raster)
r <- raster(system.file("external/rlogo.grd", package="raster"))
rna <- rc <- r
rna[r>240] = NA
par(mfrow=c(2,2))

#reclass values <=240 to NA (needed for clump function.
#Here, NAs are used to seperate clumps)
rc[r<=240] <- NA
rc <- clump(rc)

#what you get after applying the clump function
#are homogenous areas that are separated by NAs.
#Let's reclassify all areas with an ID > 8.
#In this case, these are the areas inside the ring.
rc_reclass <- rc
rc_reclass[rc_reclass>8]  <- 100

#let's do some plotting
plot(r, main='r')
plot(is.na(rna), main="is.na(r)")
plot(rc, main="clumps")
plot(rc_reclass, main="clumps reclass")


问:
Why does my code raise an error?
I am doing a coding exercise: Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

So I wrote this code:

```<code>def almostIncreasingSequence(sequence):
    first_list, second_list = sequence, sequence
    for i in range(len(sequence)-1):
        if sequence[i] >= sequence[i+1]:
            first_list.remove(sequence[i])
            second_list.remove(sequence[i+1])
            break

    if first_list == sorted(set(first_list)) or second_list == sorted(set(second_list)):
        return True
    else:
        return False
</code>```

Now this code seems to work on most sequences but this one in particular raises an error:

```<code>print almostIncreasingSequence([1,3,2])
</code>```

The error is as following:

Traceback (most recent call last):
  file.py3 on line ?, in getUserOutputs
    userOutput = _runsppge(testInputs[i])
  file.py3 on line ?, in _runsppge
    return almostIncreasingSequence(*_fArgs_lujxeukjlbwc)
  file.py3 on line 7, in almostIncreasingSequence
    second_list.remove(sequence[i+1])
IndexError: list index out of range
```

I just dont understand how the list index could possibly be out of range.. Anyone got a clue?

答:
```<code>> c:\users\jeffrey\documents\github\wadi\example.py(4)almostIncreasingSequence()
      3     for i in range(len(sequence)-1):
----> 4         if sequence[i] >= sequence[i+1]:
      5             first_list.remove(sequence[i])

ipdb> next
> c:\users\jeffrey\documents\github\wadi\example.py(5)almostIncreasingSequence()
      4         if sequence[i] >= sequence[i+1]:
----> 5             first_list.remove(sequence[i])
      6             second_list.remove(sequence[i+1])

ipdb> first_list
[1, 3, 2]
ipdb> second_list
[1, 3, 2]
ipdb> next
> c:\users\jeffrey\documents\github\wadi\example.py(6)almostIncreasingSequence()
      5             first_list.remove(sequence[i])
----> 6             second_list.remove(sequence[i+1])
      7             break

ipdb> first_list
[1, 2]
ipdb> second_list
[1, 2]
ipdb>
</code>```

Even if I didn't execute this line second_list.remove(sequence[i+1]), because first_list and second_list point to the same location. In other words we can say that one is an alias of the other. So that if one can change then second_list get change also.

Title: Why does my code raise an error?

Body:
I am doing a coding exercise: Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

So I wrote this code:

def almostIncreasingSequence(sequence):
    first_list, second_list = sequence, sequence
    for i in range(len(sequence)-1):
        if sequence[i] >= sequence[i+1]:
            first_list.remove(sequence[i])
            second_list.remove(sequence[i+1])
            break

    if first_list == sorted(set(first_list)) or second_list == sorted(set(second_list)):
        return True
    else:
        return False

Now this code seems to work on most sequences but this one in particular raises an error:

print almostIncreasingSequence([1,3,2])

The error is as following:

Traceback (most recent call last):
  file.py3 on line ?, in getUserOutputs
    userOutput = _runsppge(testInputs[i])
  file.py3 on line ?, in _runsppge
    return almostIncreasingSequence(*_fArgs_lujxeukjlbwc)
  file.py3 on line 7, in almostIncreasingSequence
    second_list.remove(sequence[i+1])
IndexError: list index out of range

I just dont understand how the list index could possibly be out of range.. Anyone got a clue?

Body:
> c:\users\jeffrey\documents\github\wadi\example.py(4)almostIncreasingSequence()
      3     for i in range(len(sequence)-1):
----> 4         if sequence[i] >= sequence[i+1]:
      5             first_list.remove(sequence[i])

ipdb> next
> c:\users\jeffrey\documents\github\wadi\example.py(5)almostIncreasingSequence()
      4         if sequence[i] >= sequence[i+1]:
----> 5             first_list.remove(sequence[i])
      6             second_list.remove(sequence[i+1])

ipdb> first_list
[1, 3, 2]
ipdb> second_list
[1, 3, 2]
ipdb> next
> c:\users\jeffrey\documents\github\wadi\example.py(6)almostIncreasingSequence()
      5             first_list.remove(sequence[i])
----> 6             second_list.remove(sequence[i+1])
      7             break

ipdb> first_list
[1, 2]
ipdb> second_list
[1, 2]
ipdb>

Even if I didn't execute this line second_list.remove(sequence[i+1]), because first_list and second_list point to the same location. In other words we can say that one is an alias of the other. So that if one can change then second_list get change also.


问:
Service fabric stateful service partitioned - well distributed
Imagine we want to have a stateful service partitioned by range of points,
with the goal of sorting each partition by points (in general, we want to divide the sort task among partitions). We would like to have users well distributed among partitions.
The ideal would be to change the range of each partition while users' points change. But it is not possible, because we cannot change the range of a partition dynamically.

One idea would be to have a single stateful service which would manage the ranges of points and would use a map to tell other services which partition should be requested for specific points. But this may mean lots of accesses to this new service, which may overload the service.

Are there any better ideas?

Edit 1:

Goal 1: To have rankings sorted by sorted-blocks (partitions), which would be aggregated by another service.

Goal 2: To provide a provisional position for a given amount of points.

答:
I recommend you partition the service by userid. For example, take modulo partitioncount of userid to determine the partition index.
This way a user can always be found in a predictable partition, and your users will be distributed well (provided you have many more users than partitions).

You can use a pub/sub mechanism to publish changing scores to a different (stateless) service, to hold a view of current highscores.


问:
Using common methods for Jenkins builds
I have multiple Jenkins jobs using pipeline scripts and i use the same method for at least 4 of them

```<code>def createJiraLinks(def ticketNumbers) {
  ArrayList<String> jiraLinks = new ArrayList<String>();
  for(int i =0; i < ticketNumbers.size(); i++) {
    def jira_json = sh script: """/usr/local/bin/curl -X GET -H "Content-Type: application/json" --cert-type PEM --key-type PEM -E /Users/Jenkins/.jenkins/workspace/certificates/cert.pem --key /Users/Jenkins/.jenkins/workspace/certificates/cert.pem https://jira.dev.org.co.uk:443/rest/api/2/issue/${ticketNumbers[i]}""", returnStdout: true
    def json = jsonParse(jira_json);
    def summary = json['fields']['summary'].toString();
    jiraLinks.add("[" + ticketNumbers[i] + "](https://jira.dev.org.co.uk/browse/" + ticketNumbers[i] + ")" + " - " + summary);

  }
  return jiraLinks;
}
</code>```

How can i have each pipeline job import this method so that if i ever need to update it i can just do it once, the key part here is having the ability to use sh script: as if i run the the curl command using "String.execute()" the command fails as i cannot correctly format it

Any advice/tips appreaciated

Thanks

答: See the detailed description at Extending with Shared Libraries.</p>

Title: Using common methods for Jenkins builds

Body:
I have multiple Jenkins jobs using pipeline scripts and i use the same method for at least 4 of them

def createJiraLinks(def ticketNumbers) {
  ArrayList<String> jiraLinks = new ArrayList<String>();
  for(int i =0; i < ticketNumbers.size(); i++) {
    def jira_json = sh script: """/usr/local/bin/curl -X GET -H "Content-Type: application/json" --cert-type PEM --key-type PEM -E /Users/Jenkins/.jenkins/workspace/certificates/cert.pem --key /Users/Jenkins/.jenkins/workspace/certificates/cert.pem https://jira.dev.org.co.uk:443/rest/api/2/issue/${ticketNumbers[i]}""", returnStdout: true
    def json = jsonParse(jira_json);
    def summary = json['fields']['summary'].toString();
    jiraLinks.add("[" + ticketNumbers[i] + "](https://jira.dev.org.co.uk/browse/" + ticketNumbers[i] + ")" + " - " + summary);

  }
  return jiraLinks;
}

How can i have each pipeline job import this method so that if i ever need to update it i can just do it once, the key part here is having the ability to use sh script: as if i run the the curl command using "String.execute()" the command fails as i cannot correctly format it

Any advice/tips appreaciated

Thanks


问:
how to pass data sing postLink in cakphp 2.0
I want to know how to fetch request data by postlink in cakephp 2.0.

```<code>echo $this->Html->div('col-md-12', $this->Form->postLink(__($a['b']['name'].'abc'), array('controller' => 'abc', 'action' => 'xyz', $a['b']['slug'], $a['b']['id']), array($a['b']['id'])));
</code>```

In output I want value for '$a['b']['slug']'.
i.e. pr($a['b']['slug']);
o/p : xyz

Thanks in advance.

答:
There is no way(as per my knowledge) but you can still do it another way using javascript,

```<code><FORM METHOD="POST" NAME="postForm" action="/action_page/55?data=Your_data" hidden>
</FORM>
<?php echo $this->Html->link(
'Enter',
['onClick' => 'document.postForm.submit();return false']); ?>
</code>```

As per my knowledge, this is an alternative solution to your question. I think there are no direct ans to your ques.

Body:
I want to know how to fetch request data by postlink in cakephp 2.0.

echo $this->Html->div('col-md-12', $this->Form->postLink(__($a['b']['name'].'abc'), array('controller' => 'abc', 'action' => 'xyz', $a['b']['slug'], $a['b']['id']), array($a['b']['id'])));

In output I want value for '$a['b']['slug']'.
i.e. pr($a['b']['slug']);
o/p : xyz

Thanks in advance.

Body:
There is no way(as per my knowledge) but you can still do it another way using javascript,

<FORM METHOD="POST" NAME="postForm" action="/action_page/55?data=Your_data" hidden>
</FORM>
<?php echo $this->Html->link(
'Enter',
['onClick' => 'document.postForm.submit();return false']); ?>

As per my knowledge, this is an alternative solution to your question. I think there are no direct ans to your ques.


问:
Mathematica: branch points for real roots of polynomial
I am doing a brute force search for "gradient extremals" on the following example function

```<code>fv[{x_, y_}] = ((y - (x/4)^2)^2 + 1/(4 (1 + (x - 1)^2)))/2;
</code>```

This involves finding the following zeros

```<code>gecond = With[{g = D[fv[{x, y}], {{x, y}}], h = D[fv[{x, y}], {{x, y}, 2}]},
 g.RotationMatrix[Pi/2].h.g == 0]
</code>```

Which Reduce happily does for me:

```<code>geyvals = y /. Cases[List@ToRules@Reduce[gecond, {x, y}], {y -> _}];
</code>```

geyvals is the three roots of a cubic polynomial, but the expression is a bit large to put here.

Now to my question: For different values of x, different numbers of these roots are real, and I would like to pick out the values of x where the solutions branch in order to piece together the gradient extremals along the valley floor (of fv). In the present case, since the polynomial is only cubic, I could probably do it by hand -- but I am looking for a simple way of having Mathematica do it for me?

Edit: To clarify: The gradient extremals stuff is just background -- and a simple way to set up a hard problem. I am not so interested in the specific solution to this problem as in a general hand-off way of spotting the branch points for polynomial roots. Have added an answer below with a working approach.

Edit 2: Since it seems that the actual problem is much more fun than root branching: rcollyer suggests using ContourPlot directly on gecond to get the gradient extremals. To make this complete we need to separate valleys and ridges, which is done by looking at the eigenvalue of the Hessian perpendicular to the gradient. Putting a check for "valleynes" in as a RegionFunction we are left with only the valley line:

```<code>valleycond = With[{
    g = D[fv[{x, y}], {{x, y}}],
    h = D[fv[{x, y}], {{x, y}, 2}]},
  g.RotationMatrix[Pi/2].h.RotationMatrix[-Pi/2].g >= 0];
gbuf["gevalley"]=ContourPlot[gecond // Evaluate, {x, -2, 4}, {y, -.5, 1.2},
   RegionFunction -> Function[{x, y}, Evaluate@valleycond],
   PlotPoints -> 41];
</code>```

Which gives just the valley floor line. Including some contours and the saddle point:

```<code>fvSaddlept = {x, y} /. First@Solve[Thread[D[fv[{x, y}], {{x, y}}] == {0, 0}]]
gbuf["contours"] = ContourPlot[fv[{x, y}],
   {x, -2, 4}, {y, -.7, 1.5}, PlotRange -> {0, 1/2},
   Contours -> fv@fvSaddlept (Range[6]/3 - .01),
   PlotPoints -> 41, AspectRatio -> Automatic, ContourShading -> None];
gbuf["saddle"] = Graphics[{Red, Point[fvSaddlept]}];
Show[gbuf /@ {"contours", "saddle", "gevalley"}]
</code>```

We end up with a plot like this:

答:
If you only want to plot the result then use StreamPlot[] on the gradients:

```<code>grad = D[fv[{x, y}], {{x, y}}];
StreamPlot[grad, {x, -5, 5}, {y, -5, 5},
           RegionFunction -> Function[{x, y}, fv[{x, y}] < 1],
           StreamScale -> 1]
</code>```

You may have to fiddle around with the plot's precision, StreamStyle, and the RegionFunction to get it perfect. Especially useful would be using the solution for the valley floor to seed StreamPoints programmatically.

ContentLicense: CC BY-SA 2.5

Body:
I am doing a brute force search for "gradient extremals" on the following example function

fv[{x_, y_}] = ((y - (x/4)^2)^2 + 1/(4 (1 + (x - 1)^2)))/2;

This involves finding the following zeros

gecond = With[{g = D[fv[{x, y}], {{x, y}}], h = D[fv[{x, y}], {{x, y}, 2}]},
 g.RotationMatrix[Pi/2].h.g == 0]

Which Reduce happily does for me:

geyvals = y /. Cases[List@ToRules@Reduce[gecond, {x, y}], {y -> _}];

geyvals is the three roots of a cubic polynomial, but the expression is a bit large to put here.

Now to my question: For different values of x, different numbers of these roots are real, and I would like to pick out the values of x where the solutions branch in order to piece together the gradient extremals along the valley floor (of fv). In the present case, since the polynomial is only cubic, I could probably do it by hand -- but I am looking for a simple way of having Mathematica do it for me?

Edit: To clarify: The gradient extremals stuff is just background -- and a simple way to set up a hard problem. I am not so interested in the specific solution to this problem as in a general hand-off way of spotting the branch points for polynomial roots. Have added an answer below with a working approach.

Edit 2: Since it seems that the actual problem is much more fun than root branching: rcollyer suggests using ContourPlot directly on gecond to get the gradient extremals. To make this complete we need to separate valleys and ridges, which is done by looking at the eigenvalue of the Hessian perpendicular to the gradient. Putting a check for "valleynes" in as a RegionFunction we are left with only the valley line:

valleycond = With[{
    g = D[fv[{x, y}], {{x, y}}],
    h = D[fv[{x, y}], {{x, y}, 2}]},
  g.RotationMatrix[Pi/2].h.RotationMatrix[-Pi/2].g >= 0];
gbuf["gevalley"]=ContourPlot[gecond // Evaluate, {x, -2, 4}, {y, -.5, 1.2},
   RegionFunction -> Function[{x, y}, Evaluate@valleycond],
   PlotPoints -> 41];

Which gives just the valley floor line. Including some contours and the saddle point:

fvSaddlept = {x, y} /. First@Solve[Thread[D[fv[{x, y}], {{x, y}}] == {0, 0}]]
gbuf["contours"] = ContourPlot[fv[{x, y}],
   {x, -2, 4}, {y, -.7, 1.5}, PlotRange -> {0, 1/2},
   Contours -> fv@fvSaddlept (Range[6]/3 - .01),
   PlotPoints -> 41, AspectRatio -> Automatic, ContourShading -> None];
gbuf["saddle"] = Graphics[{Red, Point[fvSaddlept]}];
Show[gbuf /@ {"contours", "saddle", "gevalley"}]

We end up with a plot like this:

Body:
If you only want to plot the result then use StreamPlot[] on the gradients:

grad = D[fv[{x, y}], {{x, y}}];
StreamPlot[grad, {x, -5, 5}, {y, -5, 5},
           RegionFunction -> Function[{x, y}, fv[{x, y}] < 1],
           StreamScale -> 1]

You may have to fiddle around with the plot's precision, StreamStyle, and the RegionFunction to get it perfect. Especially useful would be using the solution for the valley floor to seed StreamPoints programmatically.


问:
NetSuite - importing Bills and Bill Payment
I've created a template to import bills and that seems to work. Having issues with the bill payment. Error: You must enter at least one line item for this transaction.

I've taken the bill internal ID and mapped it to the Vendor Payment Bills > Bill field. Is that the correct mapping? I tried setting the Vendor Payments Bill > 'Line' field to 0 and then 1 but no luck. Also, it asks for an external Id or an 'order / invoice no, which I don't have.

Also - I can't map my csv status field. I tried using integer values like 1,2,3, string like pending approval as well as VendBill:A - no luck. What's the correct way to map to status field?

答:
Bill imports require two CSV files!

One contains the "header" information and each row represents a unique bill.  This is the part of the bill that hits accounts payable.  The other CSV file contains the "line" information or how the bill is coded.  Each line in the header file must have at least one row of data in the line file, but you can have more than one.

The "Ref No" Field

NetSuite uses a field called "Ref No" to match data from the two files together.  You need a "Ref No" column in both the "Header" and "Line" files.

The Header File

Your header file should have sequential numbers in your "Ref No" column (e.g.1, 2, 3, 4...) on each row and each should be unique.  They are only used to assist with the import process and don't actually show up in your NetSuite transaction data.

The Line File

Your line file should reference the ref numbers from the header file.  For example, assuming you gave your first bill a "Ref No" of "1", and that bill has two rows of coding data, your line file should have two rows of data using "1" as the "Ref No".

Since the line file is matched to the header file, you don't need to duplicate data that is already in the header file, such as the transaction/document number, vendor name, date, etc.

Keep in mind that your field names and required fields may be different but the basic principles are the same.

Bill payments may need to be imported after the bills, if you want to show a link between the bill payment and the bills that were paid.


问:
Write dictionnary with tuple containing parameters as unique value for features into postgresql table
In Python 2.7, let a dictionary with features' IDs as keys.

There are thousands of features.

Each feature has a single value, but this value is a tuple containing 6 parameters for the features (for example; size, color, etc.)

On the other hand I have a postgreSQL table in a database where these features parameters must be saved.

The features' IDs  are already set in the table (as well as other informations about these features).

The IDs are unique (they are random (thus not serial) but unique numbers).

There is 6 empty columns with names: "param1", "param2", "param3", ..., "param6".

I already have a tuple containing these names:

```<code>columns = ("param1", "param2", "param3", ..., "param6")
</code>```

The code I have doesn't work for saving these parameters in their respective columns for each feature:

```<code># "view" is the dictionary with features's ID as keys()
# and their 6 params stored in values().
values  = [view[i] for i in view.keys()]
columns =  ("param1","param2","param3","param4","param5","param6")

conn = psycopg2.connect("dbname=mydb user=username password=password")
curs = conn.cursor()

curs.execute("DROP TABLE IF EXISTS mytable;")
curs.execute("CREATE TABLE IF NOT EXISTS mytable (LIKE originaltable including defaults including constraints including indexes);")
curs.execute("INSERT INTO mytable SELECT * from originaltable;")

insertstatmnt  = 'INSERT INTO mytable (%s) values %s'
alterstatement = ('ALTER TABLE mytable '+
                  'ADD COLUMN param1 text,'+
                  'ADD COLUMN param2 text,'+
                  'ADD COLUMN param3 real,'+
                  'ADD COLUMN param4 text,'+
                  'ADD COLUMN param5 text,'+
                  'ADD COLUMN param6 text;'
                  )
curs.execute(alterstatement) # It's working up to this point.
curs.execute(insertstatmnt, (psycopg2.extensions.AsIs(','.join(columns)), tuple(values))) # The problem seems to be here.

conn.commit() # Making change to DB !
curs.close()
conn.close()
</code>```

Here's the error I have:

```<code>curs.execute(insert_statement, (psycopg2.extensions.AsIs(','.join(columns)), tuple(values)))

ProgrammingError: INSERT has more expressions than target columns
</code>```

I must miss something.

How to do that properly?

答:
As I took the syntax of the psycopg2 command from this thread:
Insert Python Dictionary using Psycopg2

and as my values dictionary doesn't exactly follow the same structure as the mentioned example (I also have 1 key as ID, like in this example, but mine has only 1 corresponding value, as a tuple containing my 6-parameters, thus "nested 1 lever deeper" instead of directly 6 values corresponding to the keys) I need to loop through all features to execute one SQL statement per feature:

```<code>[curs.execute(insertstatmnt, (psycopg2.extensions.AsIs(', '.join(columns)), i)) for i in tuple(values)].
</code>```

This, is working.

Body:
In Python 2.7, let a dictionary with features' IDs as keys.

There are thousands of features.

Each feature has a single value, but this value is a tuple containing 6 parameters for the features (for example; size, color, etc.)

On the other hand I have a postgreSQL table in a database where these features parameters must be saved.

The features' IDs  are already set in the table (as well as other informations about these features).

The IDs are unique (they are random (thus not serial) but unique numbers).

There is 6 empty columns with names: "param1", "param2", "param3", ..., "param6".

I already have a tuple containing these names:

columns = ("param1", "param2", "param3", ..., "param6")

The code I have doesn't work for saving these parameters in their respective columns for each feature:

# "view" is the dictionary with features's ID as keys()
# and their 6 params stored in values().
values  = [view[i] for i in view.keys()]
columns =  ("param1","param2","param3","param4","param5","param6")

conn = psycopg2.connect("dbname=mydb user=username password=password")
curs = conn.cursor()

curs.execute("DROP TABLE IF EXISTS mytable;")
curs.execute("CREATE TABLE IF NOT EXISTS mytable (LIKE originaltable including defaults including constraints including indexes);")
curs.execute("INSERT INTO mytable SELECT * from originaltable;")

insertstatmnt  = 'INSERT INTO mytable (%s) values %s'
alterstatement = ('ALTER TABLE mytable '+
                  'ADD COLUMN param1 text,'+
                  'ADD COLUMN param2 text,'+
                  'ADD COLUMN param3 real,'+
                  'ADD COLUMN param4 text,'+
                  'ADD COLUMN param5 text,'+
                  'ADD COLUMN param6 text;'
                  )
curs.execute(alterstatement) # It's working up to this point.
curs.execute(insertstatmnt, (psycopg2.extensions.AsIs(','.join(columns)), tuple(values))) # The problem seems to be here.

conn.commit() # Making change to DB !
curs.close()
conn.close()

Here's the error I have:

curs.execute(insert_statement, (psycopg2.extensions.AsIs(','.join(columns)), tuple(values)))

ProgrammingError: INSERT has more expressions than target columns

I must miss something.

How to do that properly?

Body:
As I took the syntax of the psycopg2 command from this thread:
Insert Python Dictionary using Psycopg2

and as my values dictionary doesn't exactly follow the same structure as the mentioned example (I also have 1 key as ID, like in this example, but mine has only 1 corresponding value, as a tuple containing my 6-parameters, thus "nested 1 lever deeper" instead of directly 6 values corresponding to the keys) I need to loop through all features to execute one SQL statement per feature:

[curs.execute(insertstatmnt, (psycopg2.extensions.AsIs(', '.join(columns)), i)) for i in tuple(values)].

This, is working.


问:
Javascript Find User
I have the below javascript to get the UserID from a online form. This script will go through IE DOM Explorer to find the valued. But when I run the script, it is totally ignoring my "If" statement. It is just providing a value for "NewAuthUserID", without considering the "if". </p>

```<code>(function () {
  var NewAuthUserID = "";
  var UserId = $('tr.background-highlight:contains("REQUESTER PROFILE") + tr').children('td:contains("User ID:")+td').text();
  if ('tr.background-highlight:contains("NEW AUTHORIZED INDIVIDUAL PROFILE:"') {
    var NewAuthUserID = $('td:contains("User ID:")+td:eq(2)').text();
  };
  alert(UserId);
  alert(NewAuthUserID)
})();
</code>```

答:
I suggest formatting your code a bit, this always helps to debug.

The problem is you are trying to use a jQuery selector in your if statement, but you didn't include the $ to evaluate jQuery. It's just evaluating a string, wich results in TRUE (basically doing this: if(true)), so the code block is executed.
Try this instead:

```<code>javascript: (function() {
  var NewAuthUserID = "";
  var UserId = $('tr.background-highlight:contains("REQUESTER PROFILE") + tr').children('td:contains("User ID:")+td').text();
  if ($('tr.background-highlight:contains("NEW AUTHORIZED INDIVIDUAL PROFILE:"').length > 0) {
    var NewAuthUserID = $('td:contains("User ID:")+td:eq(2)').text();
};
  alert(UserId);
  alert(NewAuthUserID)
})();
</code>```

EDIT: I added the length > 0 check on the returned object. It's possible to accomplish this with OP's code, he was just missing those two pieces. :contains is not the same as .text() ==.

Title: Javascript Find User

Body:
I have the below javascript to get the UserID from a online form. This script will go through IE DOM Explorer to find the valued. But when I run the script, it is totally ignoring my "If" statement. It is just providing a value for "NewAuthUserID", without considering the "if".

(function () {
  var NewAuthUserID = "";
  var UserId = $('tr.background-highlight:contains("REQUESTER PROFILE") + tr').children('td:contains("User ID:")+td').text();
  if ('tr.background-highlight:contains("NEW AUTHORIZED INDIVIDUAL PROFILE:"') {
    var NewAuthUserID = $('td:contains("User ID:")+td:eq(2)').text();
  };
  alert(UserId);
  alert(NewAuthUserID)
})();

Body:
I suggest formatting your code a bit, this always helps to debug.

The problem is you are trying to use a jQuery selector in your if statement, but you didn't include the $ to evaluate jQuery. It's just evaluating a string, wich results in TRUE (basically doing this: if(true)), so the code block is executed.
Try this instead:

javascript: (function() {
  var NewAuthUserID = "";
  var UserId = $('tr.background-highlight:contains("REQUESTER PROFILE") + tr').children('td:contains("User ID:")+td').text();
  if ($('tr.background-highlight:contains("NEW AUTHORIZED INDIVIDUAL PROFILE:"').length > 0) {
    var NewAuthUserID = $('td:contains("User ID:")+td:eq(2)').text();
};
  alert(UserId);
  alert(NewAuthUserID)
})();

EDIT: I added the length > 0 check on the returned object. It's possible to accomplish this with OP's code, he was just missing those two pieces. :contains is not the same as .text() ==.


问:
react native navigator:Undefined is not an object(evaluating this.props.navigation.navigate)
I'm not able to understand how to implement navigation in react-native.
as per the doc i have installed the plugin and integrated the code but it keeps giving the error

Undefined is not an object(evaluating this.props.navigation.navigate)

Below is the index.android.js

```<code>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

import Login from './src/pages/Login';
import Home from './src/pages/Home';

import { StackNavigator } from 'react-navigation';

export default class ECart extends Component {
  render() {
    return (
      <App />
    );
  }
}

const App = StackNavigator({
Login:{screen:Login},
Home: {screen: Home}
});

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('ECart', () => ECart);
</code>```

The Login page

```<code>import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Image,
  TextInput,
  Alert,
  Button,
  TouchableOpacity
} from 'react-native';

import { StackNavigator } from 'react-navigation';

import Home from './Home';

export default class Login extends Component {

    constructor(props) {
         super(props);
        this.state = {};
        this.onButtonPress=this.onButtonPress.bind(this);

    }

    onButtonPress= () => {
       alert("ok");
        const { navigate } = this.props.navigation;
        navigate(Home);
        };

    render() {

    return (
        <View style={styles.container}>

                <View style={{justifyContent: 'center',alignItems: 'center',height:250}}>
                    <Image style={{}} source={require('../img/ic_launcher.png')} />
                </View>
              <View style={styles.wrapper}>

                    <View style={styles.inputWrap}>
                        <View style={styles.iconWrap}>
                        <Image style={styles.icon} source={require('../img/icon/ic_email.png')}/>
                        </View>

                        <TextInput
                          style={styles.input}
                          placeholder="Username"
                          underlineColorAndroid="transparent"
                          placeholderTextColor="#939598"
                        />

                    </View>

                    <View style={styles.inputWrap}>

                        <View style={styles.iconWrap}>
                          <Image style={styles.icon} source={require('../img/icon/ic_lock.png')}/>
                        </View>
                        <TextInput
                          style={styles.input}
                          placeholder="Password"
                          secureTextEntry
                          underlineColorAndroid="transparent"
                          placeholderTextColor="#939598"
                        />

                    </View>

                    <TouchableOpacity
                      activeOpacity={0.5}
                      onPress={this.onButtonPress}>
                      <View style={styles.button}>
                          <Text style={styles.buttonText}>Login</Text>
                      </View>
                    </TouchableOpacity>

                    <TouchableOpacity activeOpacity={0.5}>
                      <View style={styles.textWrap}>
                          <Text>Forgot Password.</Text><Text>Reset here</Text>
                      </View>
                    </TouchableOpacity>

              </View>

                <View style={styles.bottomTextWrap}>
                    <Text style={{}}> By clicking Sign In, you agree to our Terms and that you have read our Data Policy, including our Cookie Use.
                    </Text>
                </View>

              <View style={styles.bottomTextWrap}>
               <Text> Copyright  2017 Suyati Technologies
               </Text>
             </View>

        </View>

    );
  }

}

const styles= StyleSheet.create({
  container:{
    flex:1,
    backgroundColor: '#FFFFFF'
  },

  inputWrap:{
    flexDirection:"row",
    marginVertical:10,
    height:50,
    borderWidth:1,
    borderColor:'#939598',
    backgroundColor:'transparent',
  },
  textWrap:{
    flexDirection:"row",
    backgroundColor:'transparent',
    justifyContent:'center',
    alignItems:'center',
    marginVertical:10,
    paddingHorizontal:20
  },
  bottomTextWrap:{
    flex:1,
    flexDirection:"row",
    backgroundColor:'transparent',
    justifyContent: 'center',
    alignItems:'flex-end',
    marginVertical:10
  },
  text:{
    justifyContent:'center',
    alignItems:'center'
  },

  input:{
    flex:1,
    paddingHorizontal:10,
    backgroundColor:"transparent",
    color:'#939598'
  },
  wrapper:{
    paddingHorizontal:30
  },
  iconWrap  :{
    paddingHorizontal:7,
    justifyContent:'center',
    alignItems:'center',
    borderColor:'#939598'
  },
  icon:{
    width:20,
    height:20
  },
  button:{
    backgroundColor:'#13AFBC',
    paddingVertical:10,
    marginVertical:10,
    justifyContent:'center',
    alignItems:'center'
  },
  buttonText:{
    color:'#FFFFFF',
    fontSize:18
  }
})
</code>```

I'm trying to navigate to the home screen.
I'm finding react-native a bit difficult.
If anyone could guide me in the right direction it will be very helpful as i'm stuck at it and need a new approach.

EDIT-I changed the code but still it wont navigate.I get the alert but it stays on the loginpage

Thanks!

答:
It seems that you have copy-pasted code from different sources(maybe tutorials) and hope it will work, but usually it doesn't. In your code you have several mistakes.

First of all, in index.android.js file you have ECart component, which is passed to AppRegistry.registerComponent() function. So, this component is a starting point for you application. You also have App variable, which is actually also a component, but you never use it. So now, your app doesn't use react-navigation, as it is not included anyhow. In order to use navigation library, you have to pass it to the app registry on some level. For example like this

```<code>const App = StackNavigator({
   Login: {screen: Login},
   Home: {screen: Home},
});

export default class ECart extends Component {
  render() {
    return (
      <App />
    );
  }
}
</code>```

This way, Ecart is passed to AppRegistry, and it has App (navigation component), which will handle navigations. Because App is responsible for navigation, you should declare your 'routes' and corresponding components that navigation component, like i included Login Screen above. Because Login is first in your StackNavigator declaration, it will be first screen when app is loaded.

Now, every compononent that you passed through StackNavigator will have navigation prop, passed by react-navigation. With that prop, you can navigate to other screens in your app. So, because you in your code Login component is not passed to StackNavigator, this.props.navigation will be undefined. And when you try to access this.props.navigation.navigate, it will throw an error, where it says, that undefined is not an object.This explains your main error, but it is not only error in the code you paste here.

In your Login component, you have

```<code>onButtonPress= () => {
    navigate(Home, { name: 'Jane' });
};
</code>```

which calls navigate function, but it is not declared anyware. So, when  you will resolve first error, you will see another error when you press your button, Undefined is not a function. So, to solve this you have to do two things. First, declare navigate function, second bind onButtonPress method.

```<code>onButtonPress() {
    const { navigate } = this.props.navigation;
    navigate('Home', { name: 'Jane' });
};
</code>```

and bind this method like

```<code>constructor(props) {
    super(props);
    this.state = {};

    this.onButtonPress=this.onButtonPress.bind(this);
}
</code>```

If you are thinking, what the hell is binding, take a look at this video

Body:
I'm not able to understand how to implement navigation in react-native.
as per the doc i have installed the plugin and integrated the code but it keeps giving the error

Undefined is not an object(evaluating this.props.navigation.navigate)

Below is the index.android.js

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

import Login from './src/pages/Login';
import Home from './src/pages/Home';

import { StackNavigator } from 'react-navigation';

export default class ECart extends Component {
  render() {
    return (
      <App />
    );
  }
}

const App = StackNavigator({
Login:{screen:Login},
Home: {screen: Home}
});

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('ECart', () => ECart);

The Login page

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Image,
  TextInput,
  Alert,
  Button,
  TouchableOpacity
} from 'react-native';

import { StackNavigator } from 'react-navigation';

import Home from './Home';

export default class Login extends Component {

    constructor(props) {
         super(props);
        this.state = {};
        this.onButtonPress=this.onButtonPress.bind(this);

    }

    onButtonPress= () => {
       alert("ok");
        const { navigate } = this.props.navigation;
        navigate(Home);
        };

    render() {

    return (
        <View style={styles.container}>

                <View style={{justifyContent: 'center',alignItems: 'center',height:250}}>
                    <Image style={{}} source={require('../img/ic_launcher.png')} />
                </View>
              <View style={styles.wrapper}>

                    <View style={styles.inputWrap}>
                        <View style={styles.iconWrap}>
                        <Image style={styles.icon} source={require('../img/icon/ic_email.png')}/>
                        </View>

                        <TextInput
                          style={styles.input}
                          placeholder="Username"
                          underlineColorAndroid="transparent"
                          placeholderTextColor="#939598"
                        />

                    </View>

                    <View style={styles.inputWrap}>

                        <View style={styles.iconWrap}>
                          <Image style={styles.icon} source={require('../img/icon/ic_lock.png')}/>
                        </View>
                        <TextInput
                          style={styles.input}
                          placeholder="Password"
                          secureTextEntry
                          underlineColorAndroid="transparent"
                          placeholderTextColor="#939598"
                        />

                    </View>

                    <TouchableOpacity
                      activeOpacity={0.5}
                      onPress={this.onButtonPress}>
                      <View style={styles.button}>
                          <Text style={styles.buttonText}>Login</Text>
                      </View>
                    </TouchableOpacity>

                    <TouchableOpacity activeOpacity={0.5}>
                      <View style={styles.textWrap}>
                          <Text>Forgot Password.</Text><Text>Reset here</Text>
                      </View>
                    </TouchableOpacity>

              </View>

                <View style={styles.bottomTextWrap}>
                    <Text style={{}}> By clicking Sign In, you agree to our Terms and that you have read our Data Policy, including our Cookie Use.
                    </Text>
                </View>

              <View style={styles.bottomTextWrap}>
               <Text> Copyright  2017 Suyati Technologies
               </Text>
             </View>

        </View>

    );
  }

}

const styles= StyleSheet.create({
  container:{
    flex:1,
    backgroundColor: '#FFFFFF'
  },

  inputWrap:{
    flexDirection:"row",
    marginVertical:10,
    height:50,
    borderWidth:1,
    borderColor:'#939598',
    backgroundColor:'transparent',
  },
  textWrap:{
    flexDirection:"row",
    backgroundColor:'transparent',
    justifyContent:'center',
    alignItems:'center',
    marginVertical:10,
    paddingHorizontal:20
  },
  bottomTextWrap:{
    flex:1,
    flexDirection:"row",
    backgroundColor:'transparent',
    justifyContent: 'center',
    alignItems:'flex-end',
    marginVertical:10
  },
  text:{
    justifyContent:'center',
    alignItems:'center'
  },

  input:{
    flex:1,
    paddingHorizontal:10,
    backgroundColor:"transparent",
    color:'#939598'
  },
  wrapper:{
    paddingHorizontal:30
  },
  iconWrap  :{
    paddingHorizontal:7,
    justifyContent:'center',
    alignItems:'center',
    borderColor:'#939598'
  },
  icon:{
    width:20,
    height:20
  },
  button:{
    backgroundColor:'#13AFBC',
    paddingVertical:10,
    marginVertical:10,
    justifyContent:'center',
    alignItems:'center'
  },
  buttonText:{
    color:'#FFFFFF',
    fontSize:18
  }
})

I'm trying to navigate to the home screen.
I'm finding react-native a bit difficult.
If anyone could guide me in the right direction it will be very helpful as i'm stuck at it and need a new approach.

EDIT-I changed the code but still it wont navigate.I get the alert but it stays on the loginpage

Thanks!

Body:
It seems that you have copy-pasted code from different sources(maybe tutorials) and hope it will work, but usually it doesn't. In your code you have several mistakes.

First of all, in index.android.js file you have ECart component, which is passed to AppRegistry.registerComponent() function. So, this component is a starting point for you application. You also have App variable, which is actually also a component, but you never use it. So now, your app doesn't use react-navigation, as it is not included anyhow. In order to use navigation library, you have to pass it to the app registry on some level. For example like this

const App = StackNavigator({
   Login: {screen: Login},
   Home: {screen: Home},
});

export default class ECart extends Component {
  render() {
    return (
      <App />
    );
  }
}

This way, Ecart is passed to AppRegistry, and it has App (navigation component), which will handle navigations. Because App is responsible for navigation, you should declare your 'routes' and corresponding components that navigation component, like i included Login Screen above. Because Login is first in your StackNavigator declaration, it will be first screen when app is loaded.

Now, every compononent that you passed through StackNavigator will have navigation prop, passed by react-navigation. With that prop, you can navigate to other screens in your app. So, because you in your code Login component is not passed to StackNavigator, this.props.navigation will be undefined. And when you try to access this.props.navigation.navigate, it will throw an error, where it says, that undefined is not an object.This explains your main error, but it is not only error in the code you paste here.

In your Login component, you have

onButtonPress= () => {
    navigate(Home, { name: 'Jane' });
};

which calls navigate function, but it is not declared anyware. So, when  you will resolve first error, you will see another error when you press your button, Undefined is not a function. So, to solve this you have to do two things. First, declare navigate function, second bind onButtonPress method.

onButtonPress() {
    const { navigate } = this.props.navigation;
    navigate('Home', { name: 'Jane' });
};

and bind this method like

constructor(props) {
    super(props);
    this.state = {};

    this.onButtonPress=this.onButtonPress.bind(this);
}

If you are thinking, what the hell is binding, take a look at this video


答:
Firstly, I'd suggest to check out how the if statement works: https://www.w3schools.com/js/js_if_else.asp

You need the if statement conditional to return true or false.  Right now you're TRYING to use jquery to select things but even that has a syntax issues.  Not only that but once the syntax is fixed it STILL won't do what you're attempting to do because you're putting something that will always evaluate to true as the conditional.  That jquery selector just returns a function, not a boolean like it looks like you're intending to do.  Try this:

```<code>(function(){
    var NewAuthUserID = "";
    var UserId=$('tr.background-highlight:contains("REQUESTER PROFILE") + tr').children('td:contains("User ID:")+td').text();
    if($('tr.background-highlight').text() == "NEW AUTHORIZED INDIVIDUAL PROFILE:")){
      var NewAuthUserID=$('td:contains("User ID:")+td:eq(2)').text();
    }
    alert(UserId);
    alert(NewAuthUserID)
  })();
</code>```

Notice how I'm snagging the text that you're trying to test against with jquery and expressing it with a conditional instead?  In this manner, it will return the boolean: true/false which is what you need to get the if statement to trigger.

Also if you check your syntax, you were missing the $() wrapper around your if statement, but you have a string that looked like it was trying to snag text via jquery.

Title: Javascript Find User

Body:
Firstly, I'd suggest to check out how the if statement works: https://www.w3schools.com/js/js_if_else.asp

You need the if statement conditional to return true or false.  Right now you're TRYING to use jquery to select things but even that has a syntax issues.  Not only that but once the syntax is fixed it STILL won't do what you're attempting to do because you're putting something that will always evaluate to true as the conditional.  That jquery selector just returns a function, not a boolean like it looks like you're intending to do.  Try this:

(function(){
    var NewAuthUserID = "";
    var UserId=$('tr.background-highlight:contains("REQUESTER PROFILE") + tr').children('td:contains("User ID:")+td').text();
    if($('tr.background-highlight').text() == "NEW AUTHORIZED INDIVIDUAL PROFILE:")){
      var NewAuthUserID=$('td:contains("User ID:")+td:eq(2)').text();
    }
    alert(UserId);
    alert(NewAuthUserID)
  })();

Notice how I'm snagging the text that you're trying to test against with jquery and expressing it with a conditional instead?  In this manner, it will return the boolean: true/false which is what you need to get the if statement to trigger.

Also if you check your syntax, you were missing the $() wrapper around your if statement, but you have a string that looked like it was trying to snag text via jquery.


问:
Is JQGrid free?
Download JQGrid js file from http://www.trirand.com/blog/ . Is it free?

What is this http://www.trirand.net/demoaspnetmvc.aspx ? . I see price and license.

Someone clarify please.

答:
From http://www.trirand.com/jqgridwiki/doku.php

"Tony developed jqGrid and made it available for free as a way of making a contribution to the open-source community.
In addition to the free jqGrid, Trirand also develops commercially-available, server-side grid components for PHP and ASP.NET. These components are not required for jqGrid to work, but they speed up the process of making complete grid solutions, and they save developers the effort of writing server-side code. "

So, yes, it's free.

Title: Is JQGrid free?


问:
RxJava2: Subscription not reached
I've created this subscription that creates another subscription:

```<code>this.loggingInterval$
    .filter(interval -> interval > 0)
    .doAfterNext(
        interval ->
        {
            Observable.interval(interval, TimeUnit.SECONDS)
                .doOnNext(t -> this.readAdditionalConfigurationFile())
                .doOnError(t -> LoggerFactory.getLogger(this.getClass()).error(t.toString()))
                .takeUntil(this.destroy$)
                .subscribe();
        }
    )
    .takeUntil(this.destroy$)
    .subscribe();
</code>```

So, each time the interval changes and it's greater than 0 I build another subscription reading configuration file each new interval seconds. It's destroyed when destroy$ emits true.

The problem is interval.doOnNext() is never reached.

```<code>this.destroy$ = BehaviorSubject.createDefault(false);
this.loggingInterval$ = BehaviorSubject.createDefault(10);
</code>```

Any ideas?

答:
It's an antipattern to create a subscription within an observable; there's many easier ways to do it.

```<code>this
.loggingInterval$
.filter(interval -> interval > 0)
.distinctUntilChanged()
.switchMap(interval -> Observable.interval(interval, TimeUnit.SECONDS, Schedulers.io()))
.doOnNext(dummy -> this.readAdditionalConfigurationFile())
.doOnError(t -> LoggerFactory.getLogger(this.getClass()).error(t.toString()))
.takeUntil(this.destroy$)
.subscribe();
</code>```

The above also has the benefit of terminating the whole chain if the subscription gets unsubscribed (which is what your destroy$ is supposed to do, right?).

Title: RxJava2: Subscription not reached

Body:
I've created this subscription that creates another subscription:

this.loggingInterval$
    .filter(interval -> interval > 0)
    .doAfterNext(
        interval ->
        {
            Observable.interval(interval, TimeUnit.SECONDS)
                .doOnNext(t -> this.readAdditionalConfigurationFile())
                .doOnError(t -> LoggerFactory.getLogger(this.getClass()).error(t.toString()))
                .takeUntil(this.destroy$)
                .subscribe();
        }
    )
    .takeUntil(this.destroy$)
    .subscribe();

So, each time the interval changes and it's greater than 0 I build another subscription reading configuration file each new interval seconds. It's destroyed when destroy$ emits true.

The problem is interval.doOnNext() is never reached.

this.destroy$ = BehaviorSubject.createDefault(false);
this.loggingInterval$ = BehaviorSubject.createDefault(10);

Any ideas?

Body:
It's an antipattern to create a subscription within an observable; there's many easier ways to do it.

this
.loggingInterval$
.filter(interval -> interval > 0)
.distinctUntilChanged()
.switchMap(interval -> Observable.interval(interval, TimeUnit.SECONDS, Schedulers.io()))
.doOnNext(dummy -> this.readAdditionalConfigurationFile())
.doOnError(t -> LoggerFactory.getLogger(this.getClass()).error(t.toString()))
.takeUntil(this.destroy$)
.subscribe();

The above also has the benefit of terminating the whole chain if the subscription gets unsubscribed (which is what your destroy$ is supposed to do, right?).


问:
Using FromUri to bind object without parameter name prefixes
When using ASP.NET WebApi2 and Swashbuckle/Swagger, I am trying to bind an object using the FromUri attribute, something like this:

```<code>[RoutePrefix("api/v1/example")]
public class ExampleController : ApiController
{
    [HttpGet]
    [Route("{id}")]
    public ExampleModel Get(string id, [FromUri]ExampleModel searchCriteria)
    {
    ...
    }
}

public class ExampleModel
{
    public string id { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
}
</code>```

I find that the URL to perform this GET operation and search by last name ends up being something like:

```<code>http://localhost:52259/api/v1/example/1?searchCriteria.firstName=paul
</code>```

How can I remove the "searchCriteria" prefix from the query parameter? I want to keep it as an ExampleModel object in the controller's method signature, but be able to use (and have this reflected in the Swagger UI docs):

```<code>http://localhost:52259/api/v1/example/1?firstName=paul
</code>```

答:
There's a Name property on the FromUri attribute.  If I set that to an empty string, it makes the Swagger UI docs appear without the "searchCriteria." prefix:

```<code>public ExampleModel Get(string id, [FromUri(Name = "")]ExampleModel searchCriteria)
{
...
}
</code>```

It appears that the controller receives the firstName regardless of whether or not there is a "searchCriteria." prefix as part of the query parameter name.

Body:
When using ASP.NET WebApi2 and Swashbuckle/Swagger, I am trying to bind an object using the FromUri attribute, something like this:

[RoutePrefix("api/v1/example")]
public class ExampleController : ApiController
{
    [HttpGet]
    [Route("{id}")]
    public ExampleModel Get(string id, [FromUri]ExampleModel searchCriteria)
    {
    ...
    }
}

public class ExampleModel
{
    public string id { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
}

I find that the URL to perform this GET operation and search by last name ends up being something like:

http://localhost:52259/api/v1/example/1?searchCriteria.firstName=paul

How can I remove the "searchCriteria" prefix from the query parameter? I want to keep it as an ExampleModel object in the controller's method signature, but be able to use (and have this reflected in the Swagger UI docs):

http://localhost:52259/api/v1/example/1?firstName=paul

Body:
There's a Name property on the FromUri attribute.  If I set that to an empty string, it makes the Swagger UI docs appear without the "searchCriteria." prefix:

public ExampleModel Get(string id, [FromUri(Name = "")]ExampleModel searchCriteria)
{
...
}

It appears that the controller receives the firstName regardless of whether or not there is a "searchCriteria." prefix as part of the query parameter name.


问:
In python, search strings using regular expression and replace it with another
I have a db.sql file that includes lots of urls like as follows.

```<code>....<td class=\"column-1\"><a href=\"http://geni.us/4Lk5\" rel=nofollow\"><img src=\"http://www.toprateten.com/wp-content/uploads/2016/08/25460A-Panini-Press-Gourmet-Sandwich-Maker.jpg \" alt=\"25460A Panini Press Gourmet Sandwich Maker\" height=\"100\" width=\"100\"></a></td><td class=\"column-2\"><a href=\"http://geni.us/4Lk5\" rel=\"nofollow\">25460A Panini Press Gourmet Sandwich Maker</a></td><td class....
</code>```

As you can see, there is http://geni.us/4Lk5\ in the file.

I have another product.csv files that contains ID (like 4LK5 above) and Amazon product URL like as follows.

```<code>4Lk5    8738    8/16/2016 0:20  https://www.amazon.com/gp/product/B00IWOJRSM/ref=as_li_qf_sp_asin_il_tl?ie=UTF8
Jx9Aj2  8738    8/22/2016 20:16 https://www.amazon.com/gp/product/B007EUSL5U/ref=as_li_qf_sp_asin_il_tl?ie=UTF8
9sl2    8738    8/22/2016 20:18 https://www.amazon.com/gp/product/B00C3GQGVG/ref=as_li_qf_sp_asin_il_tl?ie=UTF8
</code>```

As you can see, there is 4LK5 which matches with Amazon product URL.

I have already read the csv file and pick only ID and Amazon product url with python.

```<code>def openFile(filename, mode):
    index = 0
    result = []
    with open(filename, mode) as csvfile:
        spamreader = csv.reader(csvfile, delimiter = ',', quotechar = '\n')
        for row in spamreader:
            result.append({
                "genu_id": row[0],
                "amazon_url": row[3]
            });
    return result
</code>```

I have to add some code to search appropriate URL with genu_id in the db.sql and replace with amazon_url described on the code above.

Please help me.

答:
There is no need for regex if you have such a predefined structure - if all links are in the form of http://geni.us/<geni_id> you can do it with simple str.replace() by reading each row of your CSV and replacing the matches in your SQL file. Something like:

```<code>import csv

with open("product.csv", "rb") as source, open("db.sql", "r+") as target:  # open the files
    sql_contents = target.read()  # read the SQL file contents
    reader = csv.reader(source, delimiter="\t")  # build a CSV reader, tab as a delimiter
    for row in reader:  # read the CSV line by line
        # replace any match of http://geni.us/<first_column> with third column's value
        sql_contents = sql_contents.replace("http://geni.us/{}".format(row[0]), row[3])
    target.seek(0)  # seek back to the start of your SQL file
    target.truncate()  # truncate the rest
    target.write(sql_contents)  # write back the changed content
    # ...
    # Profit? :D
</code>```

Of course, if your original CSV file is comma-delimited, replace the delimiter in the csv.reader() call - the one you presented here seems tab-delimited.

Body:
I have a db.sql file that includes lots of urls like as follows.

....	25460A Panini Press Gourmet Sandwich Maker	<td class....

As you can see, there is http://geni.us/4Lk5\ in the file.

I have another product.csv files that contains ID (like 4LK5 above) and Amazon product URL like as follows.

4Lk5    8738    8/16/2016 0:20  https://www.amazon.com/gp/product/B00IWOJRSM/ref=as_li_qf_sp_asin_il_tl?ie=UTF8
Jx9Aj2  8738    8/22/2016 20:16 https://www.amazon.com/gp/product/B007EUSL5U/ref=as_li_qf_sp_asin_il_tl?ie=UTF8
9sl2    8738    8/22/2016 20:18 https://www.amazon.com/gp/product/B00C3GQGVG/ref=as_li_qf_sp_asin_il_tl?ie=UTF8

As you can see, there is 4LK5 which matches with Amazon product URL.

I have already read the csv file and pick only ID and Amazon product url with python.

def openFile(filename, mode):
    index = 0
    result = []
    with open(filename, mode) as csvfile:
        spamreader = csv.reader(csvfile, delimiter = ',', quotechar = '\n')
        for row in spamreader:
            result.append({
                "genu_id": row[0],
                "amazon_url": row[3]
            });
    return result

I have to add some code to search appropriate URL with genu_id in the db.sql and replace with amazon_url described on the code above.

Please help me.

Body:
There is no need for regex if you have such a predefined structure - if all links are in the form of http://geni.us/<geni_id> you can do it with simple str.replace() by reading each row of your CSV and replacing the matches in your SQL file. Something like:

import csv

with open("product.csv", "rb") as source, open("db.sql", "r+") as target:  # open the files
    sql_contents = target.read()  # read the SQL file contents
    reader = csv.reader(source, delimiter="\t")  # build a CSV reader, tab as a delimiter
    for row in reader:  # read the CSV line by line
        # replace any match of http://geni.us/<first_column> with third column's value
        sql_contents = sql_contents.replace("http://geni.us/{}".format(row[0]), row[3])
    target.seek(0)  # seek back to the start of your SQL file
    target.truncate()  # truncate the rest
    target.write(sql_contents)  # write back the changed content
    # ...
    # Profit? :D

Of course, if your original CSV file is comma-delimited, replace the delimiter in the csv.reader() call - the one you presented here seems tab-delimited.


问:
How to apply machine learning to 3D point cloud output which has different number of of points for each frame?
Specifically, my question is every consequent frame has different number of points and KNN/SVM fails to implement unless I have the same number of points for each frame. So how to apply ml on 3D frames which have are different in size? My ply output file consists of x,y,z coordinates for each point and more than 10000 points per frame.</p>

答:
You can extract global descriptors from each pointcloud and train a machine learning algorithm like a SVM or an ANN with them.

There are a lot of different global descriptors, here you can take a look at a few of them: PCL Descriptors

Once you have them train a machine learning algorithm like the ones shown in Python Machine Learning Classification


问:
Take from a list only the element i just clicked and use it
i have a list and when someone clicks on an li element then with $.ajax()  i fetch the specific data it wants.

for ie :

```<code><li id="test1">test 1 </li>
<li id="test2">test 2 </li>
<li id="test3">test 3 </li>
...
<li id="testN">test N </li>
</code>```

So the ajax part is for test 1 :

```<code>$('#test1').click(function() {

 $.ajax({
  url: 'fetch.php',
  type: 'POST',
  data: { temp : 'test1'},
  success: function(data) {
    $('#test1').append(data);
  }
});
</code>```

and the same for 2,3,4...N

But the problem is it comes too much of code..ok its just copy paste but can i do it another way? meaning when i click test1 element jQuery finds out what element i clicked and runs for it...

Sorry my bad english
thanks

答:
Try:

```<code><li class="test" id="test1">test 1 </li>
<li class="test" id="test2">test 2 </li>
<li class="test" id="test3">test 3 </li>
...
<li class="test" id="testN">test N </li>
</code>```

and then

```<code>$('.test').click(function() {
    var $this = $(this);
    $.ajax({
         url: 'fetch.php',
         type: 'POST',
         data: { temp : $this.attr('id') },
         success: function(data) {
             $this.append(data);
        }
    });
});
</code>```

Body:
i have a list and when someone clicks on an li element then with $.ajax()  i fetch the specific data it wants.

for ie :

test 1

test 2

test 3

...

test N

So the ajax part is for test 1 :

$('#test1').click(function() {

 $.ajax({
  url: 'fetch.php',
  type: 'POST',
  data: { temp : 'test1'},
  success: function(data) {
    $('#test1').append(data);
  }
});

and the same for 2,3,4...N

But the problem is it comes too much of code..ok its just copy paste but can i do it another way? meaning when i click test1 element jQuery finds out what element i clicked and runs for it...

Sorry my bad english
thanks

Body:
Try:

<li class="test" id="test1">test 1 </li>
<li class="test" id="test2">test 2 </li>
<li class="test" id="test3">test 3 </li>
...
<li class="test" id="testN">test N </li>

and then

$('.test').click(function() {
    var $this = $(this);
    $.ajax({
         url: 'fetch.php',
         type: 'POST',
         data: { temp : $this.attr('id') },
         success: function(data) {
             $this.append(data);
        }
    });
});


问:
How to bind onclick handlers to `this` properly on React
Explanation to why this is not a duplicate: My code is already working, I have included as a comment. The question is why the this context change when I include it to click handler function.

I'm attempting a calculator project in React. The goal is to attach onclick handlers to number buttons so the numbers are displayed on the calculator display area. If the handler is written directly to render method it is working, however, if I'm trying from the ComponentDidMount I get an error this.inputDigit is not a function. How do I bind this.inputDigit(digit) properly?

```<code>import React from 'react';
import './App.css';

export default class Calculator extends React.Component {

// display of calculator initially zero
state = {
  displayValue: '0'
}

//click handler function
inputDigit(digit){
  const { displayValue } = this.state;
  this.setState({
    displayValue: displayValue+String(digit)
  })
}

componentDidMount(){

  //Get all number keys and attach click handler function
  var numberKeys = document.getElementsByClassName("number-keys");
  var myFunction = function() {
    var targetNumber = Number(this.innerHTML);
    return this.inputDigit(targetNumber); // This is not working
  };
  for (var i = 0; i < numberKeys.length; i++) {
    numberKeys[i].onclick = myFunction;
  }

}

render() {
  const { displayValue } = this.state;
  return (
    <div className="calculator">
      <div className="calculator-display">{displayValue}</div>
      <div className="calculator-keypad">
        <div className="input-keys">

          <div className="digit-keys">
            {/*<button className="number-keys" onClick={()=> this.inputDigit(0)}>0</button> This will Work*/}}
            <button className="number-keys">0</button>
            <button className="number-keys1">1</button>
            <button className="number-keys">2</button>
            <button className="number-keys">3</button>
            <button className="number-keys">4</button>
            <button className="number-keys">5</button>
            <button className="number-keys">6</button>
            <button className="number-keys">7</button>
            <button className="number-keys">8</button>
            <button className="number-keys">9</button>
          </div>
        </div>
      </div>
    </div>
  )
 }
}
</code>```

答:
Thats because you are writing it inside a function which is not bound,

Use

```<code>var myFunction = function() {
    var targetNumber = Number(this.innerHTML);
    return this.inputDigit(targetNumber);
  }.bind(this);
</code>```

or

```<code>const myFunction = () => {
    var targetNumber = Number(this.innerHTML);
    return this.inputDigit(targetNumber);
}
</code>```

After this you need to bind the inputDigit function as well since it also uses setState

```<code>//click handler function
inputDigit = (digit) => {
  const { displayValue } = this.state;
  this.setState({
    displayValue: displayValue+String(digit)
  })
}
</code>```

Since you want to use the button text as well, in that case you should use a separate variable in place of this to call the inputDigit function like

class Calculator extends React.Component {

// display of calculator initially zero
state = {
  displayValue: '0'
}

//click handler function
inputDigit(digit){
  const { displayValue } = this.state;
  this.setState({
    displayValue: displayValue+String(digit)
  })
}

componentDidMount(){

  //Get all number keys and attach click handler function
  var numberKeys = document.getElementsByClassName("number-keys");
  var that = this;
  var myFunction = function() {
    var targetNumber = Number(this.innerHTML);
    console.log(targetNumber);
    return that.inputDigit(targetNumber); // This is not working
  };
  for (var i = 0; i < numberKeys.length; i++) {
    numberKeys[i].onclick = myFunction;
  }

}

render() {
  const { displayValue } = this.state;
  return (

{displayValue}

            {/*<button className="number-keys" onClick={()=> this.inputDigit(0)}>0</button> This will Work*/}
            <button className="number-keys">0</button>
            <button className="number-keys">1</button>
            <button className="number-keys">2</button>
            <button className="number-keys">3</button>
            <button className="number-keys">4</button>
            <button className="number-keys">5</button>
            <button className="number-keys">6</button>
            <button className="number-keys">7</button>
            <button className="number-keys">8</button>
            <button className="number-keys">9</button>

  )
 }
}

ReactDOM.render(<Calculator/>, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div></code>```

Body:
Explanation to why this is not a duplicate: My code is already working, I have included as a comment. The question is why the this context change when I include it to click handler function.

I'm attempting a calculator project in React. The goal is to attach onclick handlers to number buttons so the numbers are displayed on the calculator display area. If the handler is written directly to render method it is working, however, if I'm trying from the ComponentDidMount I get an error this.inputDigit is not a function. How do I bind this.inputDigit(digit) properly?

import React from 'react';
import './App.css';

export default class Calculator extends React.Component {

// display of calculator initially zero
state = {
  displayValue: '0'
}

//click handler function
inputDigit(digit){
  const { displayValue } = this.state;
  this.setState({
    displayValue: displayValue+String(digit)
  })
}

componentDidMount(){

  //Get all number keys and attach click handler function
  var numberKeys = document.getElementsByClassName("number-keys");
  var myFunction = function() {
    var targetNumber = Number(this.innerHTML);
    return this.inputDigit(targetNumber); // This is not working
  };
  for (var i = 0; i < numberKeys.length; i++) {
    numberKeys[i].onclick = myFunction;
  }

}

render() {
  const { displayValue } = this.state;
  return (

{displayValue}

            {/*<button className="number-keys" onClick={()=> this.inputDigit(0)}>0</button> This will Work*/}}
            <button className="number-keys">0</button>
            <button className="number-keys1">1</button>
            <button className="number-keys">2</button>
            <button className="number-keys">3</button>
            <button className="number-keys">4</button>
            <button className="number-keys">5</button>
            <button className="number-keys">6</button>
            <button className="number-keys">7</button>
            <button className="number-keys">8</button>
            <button className="number-keys">9</button>

  )
 }
}

Body:
Thats because you are writing it inside a function which is not bound,

Use

var myFunction = function() {
    var targetNumber = Number(this.innerHTML);
    return this.inputDigit(targetNumber);
  }.bind(this);

or

const myFunction = () => {
    var targetNumber = Number(this.innerHTML);
    return this.inputDigit(targetNumber);
}

After this you need to bind the inputDigit function as well since it also uses setState

//click handler function
inputDigit = (digit) => {
  const { displayValue } = this.state;
  this.setState({
    displayValue: displayValue+String(digit)
  })
}

Since you want to use the button text as well, in that case you should use a separate variable in place of this to call the inputDigit function like

class Calculator extends React.Component {

// display of calculator initially zero
state = {
  displayValue: '0'
}

//click handler function
inputDigit(digit){
  const { displayValue } = this.state;
  this.setState({
    displayValue: displayValue+String(digit)
  })
}

componentDidMount(){

  //Get all number keys and attach click handler function
  var numberKeys = document.getElementsByClassName("number-keys");
  var that = this;
  var myFunction = function() {
    var targetNumber = Number(this.innerHTML);
    console.log(targetNumber);
    return that.inputDigit(targetNumber); // This is not working
  };
  for (var i = 0; i < numberKeys.length; i++) {
    numberKeys[i].onclick = myFunction;
  }

}

render() {
  const { displayValue } = this.state;
  return (
    <div className="calculator">
      <div className="calculator-display">{displayValue}</div>
      <div className="calculator-keypad">
        <div className="input-keys">

          <div className="digit-keys">
            {/*<button className="number-keys" onClick={()=> this.inputDigit(0)}>0</button> This will Work*/}
            <button className="number-keys">0</button>
            <button className="number-keys">1</button>
            <button className="number-keys">2</button>
            <button className="number-keys">3</button>
            <button className="number-keys">4</button>
            <button className="number-keys">5</button>
            <button className="number-keys">6</button>
            <button className="number-keys">7</button>
            <button className="number-keys">8</button>
            <button className="number-keys">9</button>
          </div>
        </div>
      </div>
    </div>
  )
 }
}

ReactDOM.render(<Calculator/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


问:
How to reference definition variables nested in a class from main
I would like to know how (in Python) to reference a variable that is inside a def, inside a class. For example:

```<code>class class_name():
    .
    .    # Some more definitions in here
    .

    def definition_name():
        variable_of_interest = 10    # 10 chosen arbitrarily
    .
    .    # Some more definitions in here
    .

if __name__ == '__main__':
    # Here I want to reference variable_of_interest. Example:
    if variable_of_interest = 10
        do stuff
</code>```

Even better, how can I reference the variable in main if the example looks like:

```<code>class class_name():

    def __init__(self):
        # Some code
        def _another_definition():
            variable_of_interest = 10

if __name__ == '__main__':
    #same as before
</code>```

So basically how do I reference a variable that is placed like Class()>Def()>Def()>Variable in main?

答:
What you're calling a def is actually either a function or in this case a method in a class.

Variables defined in a method are normally not available. That's the whole idea of encapsulation.

If you want to access variables in a class they should either class or instance variables.

A variable defined in an instance, a member, would need to be accessed as part of an instance of the class. It's defined in __init__().

For example:

```<code>class MyClass:
    def __init__(self):
        self.data = []
</code>```

Accessed as:

```<code>x = MyClass() # instantiate an object of this class
x.data # access instance member
</code>```

A class variable can be defined at the top of the class definition:

```<code>class MyClass:
    """A simple example class"""
    i = 12345
</code>```

Then it would be accessed with MyClass.i.

Look at this Python tutorial on classes to understand this better.

If you really want to have a variable in a class method also be accessible directly in the main context then you can make it a global variable by preceding it with global. Otherwise variables are by default local and only accessible in the same scope.

Body:
I would like to know how (in Python) to reference a variable that is inside a def, inside a class. For example:

class class_name():
    .
    .    # Some more definitions in here
    .

    def definition_name():
        variable_of_interest = 10    # 10 chosen arbitrarily
    .
    .    # Some more definitions in here
    .

if __name__ == '__main__':
    # Here I want to reference variable_of_interest. Example:
    if variable_of_interest = 10
        do stuff

Even better, how can I reference the variable in main if the example looks like:

class class_name():

    def __init__(self):
        # Some code
        def _another_definition():
            variable_of_interest = 10

if __name__ == '__main__':
    #same as before

So basically how do I reference a variable that is placed like Class()>Def()>Def()>Variable in main?

Body:
What you're calling a def is actually either a function or in this case a method in a class.

Variables defined in a method are normally not available. That's the whole idea of encapsulation.

If you want to access variables in a class they should either class or instance variables.

A variable defined in an instance, a member, would need to be accessed as part of an instance of the class. It's defined in __init__().

For example:

class MyClass:
    def __init__(self):
        self.data = []

Accessed as:

x = MyClass() # instantiate an object of this class
x.data # access instance member

A class variable can be defined at the top of the class definition:

class MyClass:
    """A simple example class"""
    i = 12345

Then it would be accessed with MyClass.i.

Look at this Python tutorial on classes to understand this better.

If you really want to have a variable in a class method also be accessible directly in the main context then you can make it a global variable by preceding it with global. Otherwise variables are by default local and only accessible in the same scope.


问:
Can I check for numeric input only in javascript?
I am checking if a input field is empty but would like to check if it is numeric since it is a street address. I only want numeric to be allowed, no alpha even though an address might be like 123a or something else.

I want to keep the same format cause I'm checking other fields in the same function and want it to be the same. Below is what I have for empty field. What is the easiest way to change it to check for numeric only. I was trying if( !isNumeric (numbr.value)) but it isn't working.

```<code>var numbr = document.getElementById( "numbr" );
if( numbr.value == "")  {
    error = "Address number must be entered. Numeric only.";
    document.getElementById( "error_para" ).innerHTML = error;
    return false;
    }
</code>```

答:
I used isNaN and it worked.</p>

```<code>var numbr = document.getElementById( "numbr" );
if(isNaN(numbr.value))  {
    error = "Address number must numeric only.";
    document.getElementById( "error_para" ).innerHTML = error;
    return false;
    }
</code>```

Body:
I am checking if a input field is empty but would like to check if it is numeric since it is a street address. I only want numeric to be allowed, no alpha even though an address might be like 123a or something else.

I want to keep the same format cause I'm checking other fields in the same function and want it to be the same. Below is what I have for empty field. What is the easiest way to change it to check for numeric only. I was trying if( !isNumeric (numbr.value)) but it isn't working.

var numbr = document.getElementById( "numbr" );
if( numbr.value == "")  {
    error = "Address number must be entered. Numeric only.";
    document.getElementById( "error_para" ).innerHTML = error;
    return false;
    }

Body:
I used isNaN and it worked.

var numbr = document.getElementById( "numbr" );
if(isNaN(numbr.value))  {
    error = "Address number must numeric only.";
    document.getElementById( "error_para" ).innerHTML = error;
    return false;
    }


问:
How to setup a Mac to build iOS apps using Xamarin.Forms with VS2017?
I have Visual Studio 2017 on a Windows computer with Xamarin installed. I know that I need to connect to a Mac in order to build iOS apps. I don't, however, know how to set up the Mac in order to do that. I've found some information on the web. However, at least some of it seems to be outdated. For example - I'm told to use Xamarin Studio. Which seems to have been superseded by VS. Also, it seems that VS2017 can do more by itself than previous versions of VS.

So, What do I need on the Mac, when using VS2017, in order to build Xamarin.Forms apps for iOS?

答: You need to install Xcode and at least start it once and accept the EULA. Then you also need to install Visual Studio for Mac, which will pull in all requirements for you, as mentioned in the comments, this guide should still get you a long way there, just replace Xamarin Studio with Visual Studio for Mac.</p>


问:
using an expression to show or hide rectangle based on a parameter value (SSRS)
Trying to show/hide a couple of rectangles in SSRS based on an expression which uses the value of a parameter in the report. See the screenshots for more details. When the '-Cover pages' label is picked I want it to display the rectangle but I consistently get the following errors. It can't seem to convert and read the parameter expression no matter what I do.

The expression I'm trying to use is:

```<code>=iif(Parameters!specparam.Value="-Cover Pages",true,false)
</code>```

答:
It looks like the label of your parameter is what you're looking for based on the image provided and your expression. Try to switch instead to:

```<code>=IIF(Parameters!specparam.Label="-Cover Pages",TRUE,FALSE)
</code>```

(Note: I switched specparam.Value to specparam.Label.

Body:
Trying to show/hide a couple of rectangles in SSRS based on an expression which uses the value of a parameter in the report. See the screenshots for more details. When the '-Cover pages' label is picked I want it to display the rectangle but I consistently get the following errors. It can't seem to convert and read the parameter expression no matter what I do.

The expression I'm trying to use is:

=iif(Parameters!specparam.Value="-Cover Pages",true,false)

Body:
It looks like the label of your parameter is what you're looking for based on the image provided and your expression. Try to switch instead to:

=IIF(Parameters!specparam.Label="-Cover Pages",TRUE,FALSE)

(Note: I switched specparam.Value to specparam.Label.


问:
How to Specify a Class as a Method Return Type
I am viewing a method that begins with the syntax:

```<code>private myClass MyMethod(myArgs)
</code>```

What is the unattached myClass after the access modifier? I was under the impression a return type was limited to bool, int, or other simple types, not an entire class.

答:
This question was kindly answered above by Ed Plunkett.

That is type of the property, or the return type of the method,
  respectively. If you call MyMethod(), it will return an instance of a
  class named myClass, or it might return null. If you try to assign
  anything to MyProp but a myClass or null, the compiler will not allow
  you to do that. That means that when you use the value of MyProp, you
  can be assured that the thing it holds will be either null, or
  myClass.

There is further information here:
return class from function in c#.

Body:
I am viewing a method that begins with the syntax:

private myClass MyMethod(myArgs)

What is the unattached myClass after the access modifier? I was under the impression a return type was limited to bool, int, or other simple types, not an entire class.


问:
How can I use advanced regex in a boto3 ec2 instance filter?
I'm trying to match EC2 instance names not starting with a hyphen (-), so I can to skip instance names starting with a - from the shutdown process. If I use a ^ or *, these basic regex operators work fine, but if I try to use more advanced pattern matching, it's not matching properly. The pattern [a-zA-Z0-9] is being ignored and returns no instances.</p>

```<code>import boto3

# Enter the region your instances are in, e.g. 'us-east-1'
region = 'us-east-1'

#def lambda_handler(event, context):
def lambda_handler():

    ec2 = boto3.resource('ec2', region_name=region)

    filters= [{
        'Name':'tag:Name',
        #'Values':['-*']
        'Values':['^[a-zA-Z0-9]*']
        },
        {
        'Name': 'instance-state-name',
        'Values': ['running']
        }]

    instances = ec2.instances.filter(Filters=filters)

    for instance in instances:
        for tags in instance.tags:
            if tags["Key"] == 'Name':
                name = tags["Value"]

        print 'Stopping instance: ' + name + ' (' + instance.id + ')'
        instance.stop(DryRun=True)

lambda_handler()
</code>```

答:
When using the CLI and various APIs, EC2 instance filtering is not done by "regex". Instead, the filters are simple * and ? wildcards.

According to this document, Listing and Filtering Your Resources, it does mention regex filtering. However, it's unclear in that section whether it's supported in the APIs or just the AWS Management Console.

However, later in the same document, in the "Listing and Filtering Using the CLI and API", it says:

You can also use wildcards with the filter values. An asterisk (*) matches zero or more characters, and a question mark (?) matches exactly one character. For example, you can use database as a filter value to get all EBS snapshots that include database in the description.

In this section, there is no mention of regex support.

Conclusion, I suspect that regex filtering is only supported in the Management Console UI.

Body:
I'm trying to match EC2 instance names not starting with a hyphen (-), so I can to skip instance names starting with a - from the shutdown process. If I use a ^ or *, these basic regex operators work fine, but if I try to use more advanced pattern matching, it's not matching properly. The pattern [a-zA-Z0-9] is being ignored and returns no instances.

import boto3

# Enter the region your instances are in, e.g. 'us-east-1'
region = 'us-east-1'

#def lambda_handler(event, context):
def lambda_handler():

    ec2 = boto3.resource('ec2', region_name=region)

    filters= [{
        'Name':'tag:Name',
        #'Values':['-*']
        'Values':['^[a-zA-Z0-9]*']
        },
        {
        'Name': 'instance-state-name',
        'Values': ['running']
        }]

    instances = ec2.instances.filter(Filters=filters)

    for instance in instances:
        for tags in instance.tags:
            if tags["Key"] == 'Name':
                name = tags["Value"]

        print 'Stopping instance: ' + name + ' (' + instance.id + ')'
        instance.stop(DryRun=True)

lambda_handler()


答:
Bind it in the constructor</p>

```<code>constructor(props) {
    super(props);
    this.inputDigit = this.inputDigit.bind(this);
}
</code>```

Title: How to bind onclick handlers to `this` properly on React

Body:
Bind it in the constructor

constructor(props) {
    super(props);
    this.inputDigit = this.inputDigit.bind(this);
}


问:
How to write a shell script that runs next command even if current command fails?
I currently need to automate a task where I need to execute 5 commands, even if any command fails, all next commands should get executed, currently if 4th commands fails, shell script exits and dont run 5th command.

So, what should I do so that, shell script run all the next commands even if current command fails?

答:
Assuming that you have bash as your script interpreter
(or /bin/sh is a symbolic link to bash),
please check if your script does not have

```<code>set -e
</code>```

anywhere in the code.

Body:
Assuming that you have bash as your script interpreter
(or /bin/sh is a symbolic link to bash),
please check if your script does not have

set -e

anywhere in the code.

ContentLicense: CC BY-SA 4.0


问:
Where does the Traits/UI notification exception handler put its log file?
I'm getting this, from a Traits/UI application running under Windows7Pro:

```<code>> Exception occurred in traits notification handler. Please check the
> log file for details.
</code>```

Where can I find the log file that it speaks of?

答:
1) If your application has configured a log file, the traits logging will be there by default, otherwise I think there will be no log file. It's simple to configure; see https://docs.python.org/2/howto/logging.html#logging-to-a-file

2) But the info in that file might not actually be very useful for debugging, unless you take additional steps. See http://traits.readthedocs.io/en/latest/traits_user_manual/debugging.html#re-raising-exceptions-in-change-handlers

Body:
I'm getting this, from a Traits/UI application running under Windows7Pro:

> Exception occurred in traits notification handler. Please check the
> log file for details.

Where can I find the log file that it speaks of?


问:
Vba Access error 91
I try to run this code

Public Sub Production_UpdateStatus(ByVal lngProductionId As Long, _
                                   ByVal NewProductionStatus As eProductionStatus)
Dim oDb As DAO.Database
Dim oRst As DAO.Recordset
Dim StrSql As String
Dim strProductionStatus As String

On Error GoTo Err_Infos

GetCurrentProductionStatusString NewProductionStatus, strProductionStatus

Set oDb = CurrentDb

'Mise a jour du staut de production
StrSql = "UPDATE tProduction SET tProduction.Statut= '" & strProductionStatus & "'" _
           & " WHERE (tProduction.IdProduction=" & lngProductionId & ");"
oDb.Execute StrSql

'Fermeture des connexions
oRst.Close
oDb.Close
Set oDb = Nothing
Set oRst = Nothing

Exit_currentSub:
    Exit Sub

Err_Infos:
    MsgBox "Erreur #" & Err.Number & " : " & Err.Description
    Resume Exit_currentSub

End Sub
```

<p>This code work but give me error 91. </p>

<blockquote>
  <p>Object variable or With block variable not set</p>
</blockquote>

<p>It generate the following SQL query : </p>

<pre class="lang-sql prettyprint-override"><code>UPDATE tProduction SET tProduction.Statut= 'Nouvelle' WHERE (tProduction.IdProduction=2);
</code>```

When I test direct query, I do not have any error. Could you help me to eliminate this error ?

Thanks

答: Try to remove the oRst related code lines. This variable is not initialized and not used.</p>

Title: Vba Access error 91

Body:
I try to run this code

Public Sub Production_UpdateStatus(ByVal lngProductionId As Long, _
                                   ByVal NewProductionStatus As eProductionStatus)
Dim oDb As DAO.Database
Dim oRst As DAO.Recordset
Dim StrSql As String
Dim strProductionStatus As String

On Error GoTo Err_Infos

GetCurrentProductionStatusString NewProductionStatus, strProductionStatus

Set oDb = CurrentDb

'Mise a jour du staut de production
StrSql = "UPDATE tProduction SET tProduction.Statut= '" & strProductionStatus & "'" _
           & " WHERE (tProduction.IdProduction=" & lngProductionId & ");"
oDb.Execute StrSql

'Fermeture des connexions
oRst.Close
oDb.Close
Set oDb = Nothing
Set oRst = Nothing

Exit_currentSub:
    Exit Sub

Err_Infos:
    MsgBox "Erreur #" & Err.Number & " : " & Err.Description
    Resume Exit_currentSub

End Sub

This code work but give me error 91.

Object variable or With block variable not set

It generate the following SQL query :

UPDATE tProduction SET tProduction.Statut= 'Nouvelle' WHERE (tProduction.IdProduction=2);

When I test direct query, I do not have any error. Could you help me to eliminate this error ?

Thanks