问:
Could not convert string to float in generator
I am trying to do some basic operations with a nest listed of data in Python 2.7.  A simplified version of my data is presented below:

```<code>resultlistdata = [
['sell','EURUSD',-1092.0,'Sometext'],
['buy','GBPUSD',2342.0,'Moretext'],
['buy','EURUSD',2122.0,'Yetmoretext'],
['not opened','','',''],
['sell','EURJPY',-483,'Difftext'],
['sell','EURJPY',269,'Anothertext'],
etc...
]
</code>```

The list is a few thousand lines long.  I'm trying to count the number of times the third item in the list is greater than or equal to zero (so the correct result in the case above would be 3).  I am using the generator expression (or is it list comprehension?):

```<code>profittrades = sum(1 for x in resultdatalist if x[2] >= 0)
</code>```

which gives an answer equal to the number of items in the list (so 6 in the case above, which is wrong).  I have also tried:

```<code>profittrades = sum(1 for x in resultdatalist if float(x[2]) >= 0)
</code>```

which gives the error "ValueError:  Could not convert string to float".

I am almost certain the problem is caused by the line where the 'not opened' occurs, and it cannot convert the empty string to a float, I just don't know what to do about it!

Is there a way to do the counting using a 'one-liner' list comprehension approach, or do I need to make a loop?

The "resultslistdata" is compiled by me, so if there is something clever I can do when creating it that would help I can give it a try.  Im reluctant to enter a value of "0" as the profit for trades that are "never opened" because later when I do averages it will skew my results (?!).

Thank you to anyone who can help me!

答:
Using python 3.5 I can do:

```<code>profittrades = sum(
    1 for x in resultdatalist if float(x[2] if x[2] != "" else -1) >= 0
)
</code>```

I don't know though if this still working in earlier version of python.

Body:
I am trying to do some basic operations with a nest listed of data in Python 2.7.  A simplified version of my data is presented below:

resultlistdata = [
['sell','EURUSD',-1092.0,'Sometext'],
['buy','GBPUSD',2342.0,'Moretext'],
['buy','EURUSD',2122.0,'Yetmoretext'],
['not opened','','',''],
['sell','EURJPY',-483,'Difftext'],
['sell','EURJPY',269,'Anothertext'],
etc...
]

The list is a few thousand lines long.  I'm trying to count the number of times the third item in the list is greater than or equal to zero (so the correct result in the case above would be 3).  I am using the generator expression (or is it list comprehension?):

profittrades = sum(1 for x in resultdatalist if x[2] >= 0)

which gives an answer equal to the number of items in the list (so 6 in the case above, which is wrong).  I have also tried:

profittrades = sum(1 for x in resultdatalist if float(x[2]) >= 0)

which gives the error "ValueError:  Could not convert string to float".

I am almost certain the problem is caused by the line where the 'not opened' occurs, and it cannot convert the empty string to a float, I just don't know what to do about it!

Is there a way to do the counting using a 'one-liner' list comprehension approach, or do I need to make a loop?

The "resultslistdata" is compiled by me, so if there is something clever I can do when creating it that would help I can give it a try.  Im reluctant to enter a value of "0" as the profit for trades that are "never opened" because later when I do averages it will skew my results (?!).

Thank you to anyone who can help me!

Body:
Using python 3.5 I can do:

profittrades = sum(
    1 for x in resultdatalist if float(x[2] if x[2] != "" else -1) >= 0
)

I don't know though if this still working in earlier version of python.


来源: stackexchange

问:
Two step SQL Statement in only one SQL
I want to perform a efficent SQL-statement, but I don't know how to build the query correctly.

I have the following tables:

```<code>t1(user_id, test_id, module_id, save_id)
t2(save_id, answer_id)
</code>```

save_id from t2 is a foreign key for t1.save_id

So some entries:

```<code>T1:
1, 3, 4, 40
1, 5, 33, 80
2, 5, 33, 90
2, 6, 7, 82
T2:
80, A2
</code>```

So now I want all user_ids and the value of the answer_id, which have an entry for test_id=3 and module_id=4 (only these users!). The value of the searched answer is always from test_id=5 and module_id=33, the only variable thing is the save_id of the answer. I think, this can be linked through a normal JOIN, but how can I isolate only users, for who a entry exists with test_id=3 and module_id=4. In this example I only want to get user 1, user 2 is not relevant, because there is noch entry for test_id=3 and module_id=4.

答: Just add a where clause to your join Select * FROM Table1 t1 JOIN Table2 t2 ON t1.id = t2.t1_id WHERE t1.foo = "bar" AND t2.bar = "foo";

ContentLicense: CC BY-SA 3.0

Title: Two step SQL Statement in only one SQL

Body:
I want to perform a efficent SQL-statement, but I don't know how to build the query correctly.

I have the following tables:

t1(user_id, test_id, module_id, save_id)
t2(save_id, answer_id)

save_id from t2 is a foreign key for t1.save_id

So some entries:

T1:
1, 3, 4, 40
1, 5, 33, 80
2, 5, 33, 90
2, 6, 7, 82
T2:
80, A2

So now I want all user_ids and the value of the answer_id, which have an entry for test_id=3 and module_id=4 (only these users!). The value of the searched answer is always from test_id=5 and module_id=33, the only variable thing is the save_id of the answer. I think, this can be linked through a normal JOIN, but how can I isolate only users, for who a entry exists with test_id=3 and module_id=4. In this example I only want to get user 1, user 2 is not relevant, because there is noch entry for test_id=3 and module_id=4.


问:
How do I copy only the required rows from one csv file to other csv file using python?
I am trying to write a program that copies rows of one.csv file to five.csv only if there is atleast one of the following('Urology','Urologist','Urologists','MD','D.name') in second column of one.csv file.

for example:
one.csv file looks like this(below).

```<code>date        D.name      location        speciality      comment
12th may    sth MD          MS          urologist       very good
12th June   sth             MS          urologist       very good
</code>```

now after running my code I should get five.csv file with following contents(below).

```<code>date        D.name      location        speciality      comment
12th may    sth MD          MS          urologist       very good
</code>```

only the row that has at least one of the following ('Urology','Urologist','Urologists', 'MD','Doctor Name') is supposed to be copied to five.csv.

But, I am getting this instead

```<code>12th may    urologist           MS          urologist       very good
12th June   urologist           MS          urologist       very good
</code>```

There is no heading row and the 'speciality' seems to have doubled by replacing D.name column in the new file. I have been trying to fix this since yesterday but no solution at all.

How do I fix this ?

This is my code :

```<code>import csv
input = open('test.csv', 'rb')
output = open('first_test.csv', 'wb')
writer = csv.writer(output)
for row in csv.reader(input):
    for row[1] in row:
        if (('Urology' in row[1]) or ('Urologist' in row[1]) or ('Urologists' in row[1]) or ('MD' in row[1]) or ('D.name' in row[1])):
            writer.writerow(row)
</code>```

答:
Another cleaner way would be have all the to-be-searched string saved in a tuple and use any operator to search all strings. This will avoid adding an additional condition in if condition instead you just need to add new string in expected tuple.

```<code>import platform
import csv

def readWrite():
  ## List all the to-be-searched strings
  expected = ('Urology', 'Urologist', 'Urologists', 'MD', 'D.name')
  with open('test.csv', 'r') as input, open('first_test.csv', 'w') as output:
    writer = csv.writer(output)
    for row in csv.reader(input):
      ## search all strings in above listed list
      if any(string in row[1] for string in expected):
        writer.writerow(row)
  with open('first_test.csv', 'r') as f:
    print (f.read())

print("Python version : " + platform.python_version())
readWrite()
</code>```

Sample Run

```<code>Python version : 3.6.1
date,D.name,location,speciality,comment

12th may,sth MD,MS,urologist,very good
</code>```

Body:
I am trying to write a program that copies rows of one.csv file to five.csv only if there is atleast one of the following('Urology','Urologist','Urologists','MD','D.name') in second column of one.csv file.

for example:
one.csv file looks like this(below).

date        D.name      location        speciality      comment
12th may    sth MD          MS          urologist       very good
12th June   sth             MS          urologist       very good

now after running my code I should get five.csv file with following contents(below).

date        D.name      location        speciality      comment
12th may    sth MD          MS          urologist       very good

only the row that has at least one of the following ('Urology','Urologist','Urologists', 'MD','Doctor Name') is supposed to be copied to five.csv.

But, I am getting this instead

12th may    urologist           MS          urologist       very good
12th June   urologist           MS          urologist       very good

There is no heading row and the 'speciality' seems to have doubled by replacing D.name column in the new file. I have been trying to fix this since yesterday but no solution at all.

How do I fix this ?

This is my code :

import csv
input = open('test.csv', 'rb')
output = open('first_test.csv', 'wb')
writer = csv.writer(output)
for row in csv.reader(input):
    for row[1] in row:
        if (('Urology' in row[1]) or ('Urologist' in row[1]) or ('Urologists' in row[1]) or ('MD' in row[1]) or ('D.name' in row[1])):
            writer.writerow(row)

Body:
Another cleaner way would be have all the to-be-searched string saved in a tuple and use any operator to search all strings. This will avoid adding an additional condition in if condition instead you just need to add new string in expected tuple.

import platform
import csv

def readWrite():
  ## List all the to-be-searched strings
  expected = ('Urology', 'Urologist', 'Urologists', 'MD', 'D.name')
  with open('test.csv', 'r') as input, open('first_test.csv', 'w') as output:
    writer = csv.writer(output)
    for row in csv.reader(input):
      ## search all strings in above listed list
      if any(string in row[1] for string in expected):
        writer.writerow(row)
  with open('first_test.csv', 'r') as f:
    print (f.read())

print("Python version : " + platform.python_version())
readWrite()

Sample Run

Python version : 3.6.1
date,D.name,location,speciality,comment

12th may,sth MD,MS,urologist,very good


问:
How to join three tables with eloquent using a model
I've never studied Eloquent.  I am studying APIs and I want to get some data as kickly as possible, without writing sql, what is I usually do.

I have the tables: "house" related to "announcement" (one to one) and the "announcement" table is related to "advertiser" (one to many).

When I tried

```<code>       $house = \App\House::where('house_id', $id)->with('announcement', 'advertiser')->first();
</code>```

I get the error:  announcement undefined method.
I think I set up the relationship on the models correctly so I didn't include them here. I want to join using the model House because I am not using the default connection when using Eloquent.

答:
with() must be placed at first, and specify your relationships in an array (if you load more than one)

```<code>$house = \App\House::with(['announcement', 'advertiser'])->where('house_id', $id)->first();
</code>```

Edit :
Sorry, i haven't seen that it's a nested relationship
You can use this code instead of the above one :

```<code>$house = \App\House::with(['announcement', 'announcement.advertiser'])->where('house_id', $id)->first();
</code>```

Body:
I've never studied Eloquent.  I am studying APIs and I want to get some data as kickly as possible, without writing sql, what is I usually do.

I have the tables: "house" related to "announcement" (one to one) and the "announcement" table is related to "advertiser" (one to many).

When I tried

       $house = \App\House::where('house_id', $id)->with('announcement', 'advertiser')->first();

I get the error:  announcement undefined method.
I think I set up the relationship on the models correctly so I didn't include them here. I want to join using the model House because I am not using the default connection when using Eloquent.

Body:
with() must be placed at first, and specify your relationships in an array (if you load more than one)

$house = \App\House::with(['announcement', 'advertiser'])->where('house_id', $id)->first();

Edit :
Sorry, i haven't seen that it's a nested relationship
You can use this code instead of the above one :

$house = \App\House::with(['announcement', 'announcement.advertiser'])->where('house_id', $id)->first();


问:
Windows Identity always anonymous in ASP.NET request pipeline
I'm trying to create a simple action filter for my MVC site that checks the current Windows user against those allowed access to the site. For some reason, the filterContext.HttpContext.User.Identity object is always set to anonymous with no username. I've tried to grab it at different stages (OnAuthenticate and OnAuthorize), but it's always anonymous.

I currently have anonymous and Windows authentication enabled in IIS (actually followed this example to configure the Windows Auth feature), and I have the following block in the system.web node of my web.config:

```<code><authentication mode="Windows" />
<authorization>
  <allow users="*" />
  <deny users="?" />
</authorization>
</code>```

However for some reason, the Identity is always anonymous with no username. I have to be missing something here. With Windows Auth set in IIS, I'm always prompted for the username/password combo (which actually fails with HTTP401.1 error 0xc000006d, though I think this might be because I have a custom host header setup for development). I've also read a few articles that suggest this is because my site is determined to be in the internet zone and the answers always state to add the site to the intranet zone in Internet Explorer. This seems like a band-aid fix though, and not the actual solution.

Ideally, I would like to have the following:

User browses to my site

Behind the scenes, their Windows username is picked up, and authenticated against allowed users managed by the app

User authenticated successfully, page loads, user is none the wiser they were authenticated

What do I need to do to achieve this?

Thanks in advance for any help. Please let me know if I can provide more context.

Edit: Forgot to add I'm running this on Windows 7 SP1, IIS 7.5

答:
In your solution explorer, press F4 over the project, and change Windows Authentication to Enable if you are running your project from Visual Studio;

In IIS select your WebSite -> Authentication and Disable Anonymous Authentication  and make sure that "Windows Authentication" if Enable

Body:
I'm trying to create a simple action filter for my MVC site that checks the current Windows user against those allowed access to the site. For some reason, the filterContext.HttpContext.User.Identity object is always set to anonymous with no username. I've tried to grab it at different stages (OnAuthenticate and OnAuthorize), but it's always anonymous.

I currently have anonymous and Windows authentication enabled in IIS (actually followed this example to configure the Windows Auth feature), and I have the following block in the system.web node of my web.config:

<authentication mode="Windows" />
<authorization>
  <allow users="*" />
  <deny users="?" />
</authorization>

However for some reason, the Identity is always anonymous with no username. I have to be missing something here. With Windows Auth set in IIS, I'm always prompted for the username/password combo (which actually fails with HTTP401.1 error 0xc000006d, though I think this might be because I have a custom host header setup for development). I've also read a few articles that suggest this is because my site is determined to be in the internet zone and the answers always state to add the site to the intranet zone in Internet Explorer. This seems like a band-aid fix though, and not the actual solution.

Ideally, I would like to have the following:

User browses to my site

Behind the scenes, their Windows username is picked up, and authenticated against allowed users managed by the app

User authenticated successfully, page loads, user is none the wiser they were authenticated

What do I need to do to achieve this?

Thanks in advance for any help. Please let me know if I can provide more context.

Edit: Forgot to add I'm running this on Windows 7 SP1, IIS 7.5


问:
Using Selenium, Python script to open Firefox, not going to URL provided

Problem

I'm following of the examples listed on the documentation here. Basically, just trying to get Selenium to open Firefox, take me to a site, make a query and then close the browser.

I've been running into an issue where Selenium will open the browser, but then not go to the specified website. In other cases, I receive an error, I should mention this error only appear after upgrading Selenium.

```<code>Traceback (most recent call last):
  File "script.py", line 4, in <module>
    browser = webdriver.Firefox()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 142, in __init__
    self.service.start()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 74, in start
    stdout=self.log_file, stderr=self.log_file)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 8] Exec format error
</code>```

I'm using the latest version of Firefox, 54.0.1

I'm using Python version 2.7.11

And I have Selenium version 3.4.3

script.py

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()

browser.get('http://www.yahoo.com')
assert 'Yahoo!' in browser.title

elem = browser.find_element_by_name('p')  # Find the search box
elem.send_keys('seleniumhq' + Keys.RETURN)

browser.quit()
</code>```

答:
In this case, these were the steps I took to solve this issue.

Updated Firefox to the latest version

Updated Selenium as well

Removed incorrect version of geckodriver from bin folder

Updated xcode in App Store

Used brew install geckodriver to get correct version into bin folder

Used brew link

Ran script.py

Body:
Problem

I'm following of the examples listed on the documentation here. Basically, just trying to get Selenium to open Firefox, take me to a site, make a query and then close the browser.

I've been running into an issue where Selenium will open the browser, but then not go to the specified website. In other cases, I receive an error, I should mention this error only appear after upgrading Selenium.

Traceback (most recent call last):
  File "script.py", line 4, in <module>
    browser = webdriver.Firefox()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 142, in __init__
    self.service.start()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 74, in start
    stdout=self.log_file, stderr=self.log_file)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 8] Exec format error

I'm using the latest version of Firefox, 54.0.1

I'm using Python version 2.7.11

And I have Selenium version 3.4.3

script.py

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()

browser.get('http://www.yahoo.com')
assert 'Yahoo!' in browser.title

elem = browser.find_element_by_name('p')  # Find the search box
elem.send_keys('seleniumhq' + Keys.RETURN)

browser.quit()


问:
Inflation function in R broom package not working as expected
I expect the below code

```<code>library(dplyr)
library(broom)

d <- data.frame(a = 1:3, b = 8:10)

d %>% inflate(x = c("apple", "orange"), y = c("car", "boat"))
</code>```

to give me a 12 x 4 data frame that looks like this:

```<code>## 1 apple boat 1 8
## 2 apple boat 2 9
## 3 apple boat 3 10
## 4 apple car 1 8
## 5 apple car 2 9
## 6 apple car 3 10
## 7 orange boat 1 8
## 8 orange boat 2 9
## 9 orange boat 3 10
## 10 orange car 1 8
## 11 orange car 2 9
## 12 orange car 3 10
</code>```

but instead it gives me this:

```<code># A tibble: 4 x 2
# Groups:   x, y [4]
       x     y
   <chr> <chr>
1  apple  boat
2  apple   car
3 orange  boat
4 orange   car
</code>```

It seems that d is ignored. What's going on?

答:
Try tidyr::crossing:

library(tidyr)

d <- data.frame(a = 1:3,
                b = 8:10)

d %>% crossing(x = c("apple", "orange"),
               y = c("car", "boat"))
#>    a  b      x    y
#> 1  1  8  apple boat
#> 2  1  8  apple  car
#> 3  1  8 orange boat
#> 4  1  8 orange  car
#> 5  2  9  apple boat
#> 6  2  9  apple  car
#> 7  2  9 orange boat
#> 8  2  9 orange  car
#> 9  3 10  apple boat
#> 10 3 10  apple  car
#> 11 3 10 orange boat
#> 12 3 10 orange  car
```

Body:
I expect the below code

library(dplyr)
library(broom)

d <- data.frame(a = 1:3, b = 8:10)

d %>% inflate(x = c("apple", "orange"), y = c("car", "boat"))

to give me a 12 x 4 data frame that looks like this:

## 1 apple boat 1 8
## 2 apple boat 2 9
## 3 apple boat 3 10
## 4 apple car 1 8
## 5 apple car 2 9
## 6 apple car 3 10
## 7 orange boat 1 8
## 8 orange boat 2 9
## 9 orange boat 3 10
## 10 orange car 1 8
## 11 orange car 2 9
## 12 orange car 3 10

but instead it gives me this:

# A tibble: 4 x 2
# Groups:   x, y [4]
       x     y
   <chr> <chr>
1  apple  boat
2  apple   car
3 orange  boat
4 orange   car

It seems that d is ignored. What's going on?


问:
Why does Rails use plurals for new and create?
I understand why a Rails index method would use the plural form of a resource - we're showing all projects, for example.

And I understand why the show method would use the singular form - we only want to see one project, with a particular ID.

But I don't understand why new and create would use the plural. Is there a way to create more than one project at a time? Is there some other reasoning for using the plural here that someone could explain?

答:
I thought they were always plural. Scroll down a bit on this page for an example of the routes generated by resources :photos

Whether you're GETting a single resource or POSTing to the collection, you're still in the domain of photos. So, search the domain of photos given an id, POST a new photo to the domain of photos, etc.

ContentLicense: CC BY-SA 2.5


问:
Editing the weight of many product variations in WooCommerce
How can I edit the weight of many product variations in WooCommerce?</p>

答:
First you get an array of your Product Variations IDs this way:

```<code>global $wpdb;
$posts_table = $wpdb->prefix . "posts";
$variation_ids = $wpdb->get_col( "SELECT `ID` FROM $posts_table WHERE `post_status` LIKE 'publish' AND `post_type` LIKE 'product_variation'");
</code>```

Then you can edit the weight for this product variations this way:

```<code>// Iterating through all product variations
foreach( $variation_ids as $variation_id ){

    // Get an instance of the product variation object
    $variation_object = wc_get_product($variation_id);

    // Get the variation weight
    $weight = $variation_object->get_weight();

    ## -- USE CONDITIONS TO SET / UPDATE WEIGHT AS YOU NEED -- ##

    // Example of conditions below
    if( $weight <= 0.2 && $weight > 0.3 ){
        $variation_object->set_weight(0.28);
    } elseif( $weight <= 0.3 && $weight > 0.5 ){
        $variation_object->set_weight(0.42);
    }

    // Example of empty weight condition
    if( empty($weight) ){
        $variation_object->set_weight(0.16);
    }

    // Example Based on variation IDs from 125 to 129
    if($variation_id >= 125 &&  $variation_id < 130 ){
        $variation_object->set_weight(0.45);
    }
}
</code>```

Then you can customize the conditions to match your needs and to embed this in a function to run it once.

You can use any WC_Product and WC_Product_Variation methods on the Product Variation object $variation_object in your conditions too.

This way you will set / update all your multiple needed variations weight

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

This code is tested and works on WooCommerce 3.0+

ContentLicense: CC BY-SA 4.0

Body:
First you get an array of your Product Variations IDs this way:

global $wpdb;
$posts_table = $wpdb->prefix . "posts";
$variation_ids = $wpdb->get_col( "SELECT `ID` FROM $posts_table WHERE `post_status` LIKE 'publish' AND `post_type` LIKE 'product_variation'");

Then you can edit the weight for this product variations this way:

// Iterating through all product variations
foreach( $variation_ids as $variation_id ){

    // Get an instance of the product variation object
    $variation_object = wc_get_product($variation_id);

    // Get the variation weight
    $weight = $variation_object->get_weight();

    ## -- USE CONDITIONS TO SET / UPDATE WEIGHT AS YOU NEED -- ##

    // Example of conditions below
    if( $weight <= 0.2 && $weight > 0.3 ){
        $variation_object->set_weight(0.28);
    } elseif( $weight <= 0.3 && $weight > 0.5 ){
        $variation_object->set_weight(0.42);
    }

    // Example of empty weight condition
    if( empty($weight) ){
        $variation_object->set_weight(0.16);
    }

    // Example Based on variation IDs from 125 to 129
    if($variation_id >= 125 &&  $variation_id < 130 ){
        $variation_object->set_weight(0.45);
    }
}

Then you can customize the conditions to match your needs and to embed this in a function to run it once.

You can use any WC_Product and WC_Product_Variation methods on the Product Variation object $variation_object in your conditions too.

This way you will set / update all your multiple needed variations weight

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

This code is tested and works on WooCommerce 3.0+


问:
Insert/Update/Delete with function in SQL Server
Can we perform Insert/Update/Delete statement with SQL Server Functions. I have tried with but SQL Server error is occured.

Error:

```<code>Invalid use of side-effecting or time-dependent operator in 'DELETE' within a function.
</code>```

AnyBody have any Idea why we can not use Insert/Update/Delete statements with SQL Server functions.

Waiting for your good idea's

答:
Just another alternative using sp_executesql (tested only in SQL 2016).
As previous posts noticed, atomicity must be handled elsewhere.

```<code>CREATE FUNCTION [dbo].[fn_get_service_version_checksum2]
(
    @ServiceId INT
)
RETURNS INT
AS
BEGIN
DECLARE @Checksum INT;
SELECT @Checksum = dbo.fn_get_service_version(@ServiceId);
DECLARE @LatestVersion INT = (SELECT MAX(ServiceVersion) FROM [ServiceVersion] WHERE ServiceId = @ServiceId);
-- Check whether the current version already exists and that it's the latest version.
IF EXISTS(SELECT TOP 1 1 FROM [ServiceVersion] WHERE ServiceId = @ServiceId AND [Checksum] = @Checksum AND ServiceVersion = @LatestVersion)
    RETURN @LatestVersion;
-- Insert the new version to the table.
EXEC sp_executesql N'
INSERT INTO [ServiceVersion] (ServiceId, ServiceVersion, [Checksum], [Timestamp])
VALUES (@ServiceId, @LatestVersion + 1, @Checksum, GETUTCDATE());',
N'@ServiceId INT = NULL, @LatestVersion INT = NULL, @Checksum INT = NULL',
@ServiceId = @ServiceId,
@LatestVersion = @LatestVersion,
@Checksum = @Checksum
;
RETURN @LatestVersion + 1;
END;
</code>```

Body:
Can we perform Insert/Update/Delete statement with SQL Server Functions. I have tried with but SQL Server error is occured.

Error:

Invalid use of side-effecting or time-dependent operator in 'DELETE' within a function.

AnyBody have any Idea why we can not use Insert/Update/Delete statements with SQL Server functions.

Waiting for your good idea's

Body:
Just another alternative using sp_executesql (tested only in SQL 2016).
As previous posts noticed, atomicity must be handled elsewhere.

CREATE FUNCTION [dbo].[fn_get_service_version_checksum2]
(
    @ServiceId INT
)
RETURNS INT
AS
BEGIN
DECLARE @Checksum INT;
SELECT @Checksum = dbo.fn_get_service_version(@ServiceId);
DECLARE @LatestVersion INT = (SELECT MAX(ServiceVersion) FROM [ServiceVersion] WHERE ServiceId = @ServiceId);
-- Check whether the current version already exists and that it's the latest version.
IF EXISTS(SELECT TOP 1 1 FROM [ServiceVersion] WHERE ServiceId = @ServiceId AND [Checksum] = @Checksum AND ServiceVersion = @LatestVersion)
    RETURN @LatestVersion;
-- Insert the new version to the table.
EXEC sp_executesql N'
INSERT INTO [ServiceVersion] (ServiceId, ServiceVersion, [Checksum], [Timestamp])
VALUES (@ServiceId, @LatestVersion + 1, @Checksum, GETUTCDATE());',
N'@ServiceId INT = NULL, @LatestVersion INT = NULL, @Checksum INT = NULL',
@ServiceId = @ServiceId,
@LatestVersion = @LatestVersion,
@Checksum = @Checksum
;
RETURN @LatestVersion + 1;
END;


问:
tcp flood attack not works with hping3
i want to do a dos attack to a website in my virtual machine. i use hping3 for that .

```<code>sudo hping3 -i u1 -S  -c 9999999999 192.168.58.3
</code>```

in this ip address i have an apache server and a DVWA. when i input this ip address to the browser i see two folder : DVWA and html . when i choose DVWA i see the website.
my problem is than althogh i use hping3 for attack and i want the website get down but the website not down and when i ping this ip address ttls are like when attack not occured. i search a lot and do all works i think . i don't know what is the problem. please help me. thanks

答:
Try this:

```<code>$ sudo hping3 -i u1 -S -p 80 192.168.58.3

S - indicates SYN flag
p 80 - Target port 80
i u1 - Wait for 1 micro second between each packet
</code>```

This would send TCP SYN packets to 192.168.58.3.

Title: tcp flood attack not works with hping3

Body:
i want to do a dos attack to a website in my virtual machine. i use hping3 for that .

sudo hping3 -i u1 -S  -c 9999999999 192.168.58.3

in this ip address i have an apache server and a DVWA. when i input this ip address to the browser i see two folder : DVWA and html . when i choose DVWA i see the website.
my problem is than althogh i use hping3 for attack and i want the website get down but the website not down and when i ping this ip address ttls are like when attack not occured. i search a lot and do all works i think . i don't know what is the problem. please help me. thanks

Body:
Try this:

$ sudo hping3 -i u1 -S -p 80 192.168.58.3

S - indicates SYN flag
p 80 - Target port 80
i u1 - Wait for 1 micro second between each packet

This would send TCP SYN packets to 192.168.58.3.


问:
Wordpress custom taxonomy term page not found
For some reason when I click the link to a taxonomy term page, wordpress keeps displaying the index file and says page not found. I have a page with the slug "contributors" using a template that displays the terms of the custom taxonomy "contributor) with a link to it's page, so I click the link and the error occurs.

This is my functions.php code for adding the taxonomy:

```<code>register_taxonomy(
    'contributor',
    'post',
    array(
        'hierarchical' => true,
        'labels' => array(
             'name' => _x( 'Contributors', 'taxonomy general name' ),
             'singular_name' => _x( 'Contributor', 'taxonomy singular name' ),
             'search_items' => __( 'Search Contributors' ),
             'all_items' => __( 'All Contributors' ),
             'parent_item' => __( 'Parent Contributor' ),
             'parent_item_colon' => __( 'Parent Contributor:' ),
             'edit_item' => __( 'Edit Contributor' ),
             'update_item' => __( 'Update Contributor' ),
             'add_new_item' => __( 'Add New Contributor' ),
             'new_item_name' => __( 'New Contributor Name' ),
             'menu_name' => __( 'Contributors' ),
         ),
        'show_tagcloud' => true
    )
);
</code>```

Does anyone know why, even when including a file called taxonomy-contributor.php, the error still occurs?

答: i had a simular problem. what helped me was to flush permalinks after including the taxonomie links in the menu by going to Settings / Permalinks and simply saving.</p>

Body:
For some reason when I click the link to a taxonomy term page, wordpress keeps displaying the index file and says page not found. I have a page with the slug "contributors" using a template that displays the terms of the custom taxonomy "contributor) with a link to it's page, so I click the link and the error occurs.

This is my functions.php code for adding the taxonomy:

register_taxonomy(
    'contributor',
    'post',
    array(
        'hierarchical' => true,
        'labels' => array(
             'name' => _x( 'Contributors', 'taxonomy general name' ),
             'singular_name' => _x( 'Contributor', 'taxonomy singular name' ),
             'search_items' => __( 'Search Contributors' ),
             'all_items' => __( 'All Contributors' ),
             'parent_item' => __( 'Parent Contributor' ),
             'parent_item_colon' => __( 'Parent Contributor:' ),
             'edit_item' => __( 'Edit Contributor' ),
             'update_item' => __( 'Update Contributor' ),
             'add_new_item' => __( 'Add New Contributor' ),
             'new_item_name' => __( 'New Contributor Name' ),
             'menu_name' => __( 'Contributors' ),
         ),
        'show_tagcloud' => true
    )
);

Does anyone know why, even when including a file called taxonomy-contributor.php, the error still occurs?


问:
Get sum of numbers within range (from 0 to user input)
This is the code i am using, its purpose is for the user to enter an integer, the program will then take the sum of all the numbers up to and including the one entered. There is probable an easier way to do this </p>

```<code> sum = 0
 puts "please enter a number"
 counter = gets.chomp.to_i
 begin
  sum += counter
  counter -= 1
 end while counter == 0
</code>```

答:
As I understand you are trying to sum elements of range. Giving number 3, you want to get sum which is 6.

One way (time consuming) is to use inject or sum. You can try following:

```<code>1. [*1..value].sum
2. [*1..value].inject(:+)
</code>```

The other (recommended), very efficient way is to use this equation:

```<code>(value + 1) * (value) / 2
</code>```

Body:
This is the code i am using, its purpose is for the user to enter an integer, the program will then take the sum of all the numbers up to and including the one entered. There is probable an easier way to do this

 sum = 0
 puts "please enter a number"
 counter = gets.chomp.to_i
 begin
  sum += counter
  counter -= 1
 end while counter == 0

Body:
As I understand you are trying to sum elements of range. Giving number 3, you want to get sum which is 6.

One way (time consuming) is to use inject or sum. You can try following:

1. [*1..value].sum
2. [*1..value].inject(:+)

The other (recommended), very efficient way is to use this equation:

(value + 1) * (value) / 2


问:
How to test database migration in Android?
I have an Android app with a database with version 1.

Now I like to change the structure of the database and write all the migration code etc.

The problem I have is how to test this.

I need to repeatedly have the old version of the app with its old DB so I can test the update process to the new app with the new DB several times.

I thought to simplify things I make a copy of my project and just rename it new - leaving the manifest and everything unchanged!!!!

The idea is to run/install the old version of the app with the old DB structure using Eclipse so I can create the start situation of my update.

Now to simulate the user update to the new app version I install it just over the old version using Eclipse again) - but even without having changed the db I get an error that the DB already exists ???

I am confused (I have only changed the project name, not the manifest) I would have expected that I can just install the new version over the old version and hereby test the user update of the app.

But that does not work.

How would I best do this? (without having the old and the new database code in the very same project. since if I have the same project I have two different data base structures in there and need to build in a switch how it should start up, ie as old or new. I find it cleaner to just write the new version of the app with the new database structure in there)

答:
You can create the main file 'create.sql' and the migrations files called '1.sql, 2.sql,.., n.sql'.
Store all these files in assets for example.

If the user has no database, apply create.sql
If the user needs a database upgrade from A to Z, then apply a+1.sql, a+2.sql, …, z.sql.

You need implement applyUpgrades method that you'll use on upgrade version of DB and for migration tests. It's look like:

```<code>fun Context.applyUpgrades(db: SQLiteDatabase, from: Int, to: Int): Unit =
    (from+1..to).forEach { index ->
      val migrationSql = getMigrationFromAssets(index)
      db.execSQL(migrationSql)
    }
</code>```

Your migration tests will look like:

```<code>@Test
fun upgrade10to11() { // when you upgrade from 10 to 11

    val db = SQLiteDatabase.create(null)

    // apply all previous migrations
    applyUpgrades(db, from = INITIAL, to = 10)

    val valuesBefore = ..

    // our new migration
    applyUpgrades(db, from = 10, to = 11)

    val valuesAfter = ..

    // assert that valuesBefore and valuesAfter are correct
}
</code>```

Also you can check that you did not forget write test for new migration:

```<code>@Test
public void hasAllNecessaryTests() {
  assertEquals(DB_VERSION, 11);
}
</code>```

Trello bless

Body:
You can create the main file 'create.sql' and the migrations files called '1.sql, 2.sql,.., n.sql'.
Store all these files in assets for example.

If the user has no database, apply create.sql
If the user needs a database upgrade from A to Z, then apply a+1.sql, a+2.sql, …, z.sql.

You need implement applyUpgrades method that you'll use on upgrade version of DB and for migration tests. It's look like:

fun Context.applyUpgrades(db: SQLiteDatabase, from: Int, to: Int): Unit =
    (from+1..to).forEach { index ->
      val migrationSql = getMigrationFromAssets(index)
      db.execSQL(migrationSql)
    }

Your migration tests will look like:

@Test
fun upgrade10to11() { // when you upgrade from 10 to 11

    val db = SQLiteDatabase.create(null)

    // apply all previous migrations
    applyUpgrades(db, from = INITIAL, to = 10)

    val valuesBefore = ..

    // our new migration
    applyUpgrades(db, from = 10, to = 11)

    val valuesAfter = ..

    // assert that valuesBefore and valuesAfter are correct
}

Also you can check that you did not forget write test for new migration:

@Test
public void hasAllNecessaryTests() {
  assertEquals(DB_VERSION, 11);
}

Trello bless


问:
Mozilla Firefox download option
Firefox open PDF file in a new tab. Any option to download directly? I use download in a tag.
When we click on download button it will open in a new tab. </p>

<p>DOWNLOAD </p>

答:
You need to add a header in your server that will force the file to download:</p>

```<code>location ~* (.+\.pdf)$ {
    add_header Content-disposition "attachment; filename=$1";
}
</code>```

Title: Mozilla Firefox download option

Body:
Firefox open PDF file in a new tab. Any option to download directly? I use download in a tag.
When we click on download button it will open in a new tab.

DOWNLOAD

Body:
You need to add a header in your server that will force the file to download:

location ~* (.+\.pdf)$ {
    add_header Content-disposition "attachment; filename=$1";
}


问:
Prestashop 1.7 Payment module
I am creating a credit card payment module for prestashop 1.7

I don't know how to send my post values on an external url and receive its response if the transaction is success or failed.

答:
You have to make things like this :

Make a module (https://validator.prestashop.com/generator) and extend
it with PaymentModule, not just Module.

Register interesting hooks (http://build.prestashop.com/news/module-development-changes-in-17/) and make a function like this in your module :

```<code> public function hookHookName($params) {
   // Do things here
 }
</code>```

Play with this Hook specially (first part is hook name and second are $params)  :

```<code>Hook::exec('actionValidateOrder', array(
   'cart' => $this->context->cart,
   'order' => $order,
   'customer' => $this->context->customer,
   'currency' => $this->context->currency,
   'orderStatus' => $order_status
));
</code>```

Make calls (curl / file_get_contents for instance) on that moment before validating anything.

A good way to know how to do it could be to download Paypal Module (it's free) and see how they did it.

Title: Prestashop 1.7 Payment module

Body:
You have to make things like this :

Make a module (https://validator.prestashop.com/generator) and extend
it with PaymentModule, not just Module.

Register interesting hooks (http://build.prestashop.com/news/module-development-changes-in-17/) and make a function like this in your module :

 public function hookHookName($params) {
   // Do things here
 }

Play with this Hook specially (first part is hook name and second are $params)  :

Hook::exec('actionValidateOrder', array(
   'cart' => $this->context->cart,
   'order' => $order,
   'customer' => $this->context->customer,
   'currency' => $this->context->currency,
   'orderStatus' => $order_status
));

Make calls (curl / file_get_contents for instance) on that moment before validating anything.

A good way to know how to do it could be to download Paypal Module (it's free) and see how they did it.


问:
Does CAS Maple use a scripting language for algorithms inside packages?
Does Maple use a scripting language for algorithms inside packages,
like Student[LinearAlgebra]?
What really does command for loading a package, like this:</p>

```<code>with(Student[LinearAlgebra]):
</code>```

答:
The first of your two questions seems to be pretty similar to asking how Maple commands generally work, which is pretty broad so I'll just give a summary.

Question 1)

Maple is an interpreted language. Commands from its Student[LinearAlgebra] package are written in the Maple language, and stored by Maple in a so-called Maple Library archive (a file with filename extension .mla).

You can see and inspect most of the source of those package's exported commands using the Maple commands showstat (or print, when interface(verboseproc) is high enough). Note that the source of most of these commands involves calls to other, internal routines in the package (most of which in turn are written in the Maple language).

Many of the computational commands in the Student[LinearAlgebra] package  involve not much more than to calls to the LinearAlgebra package. Try these Maple commands, as examples:

```<code>showstat(Student:-LinearAlgebra:-ReducedRowEchelonForm);

showstat(:-LinearAlgebra:-ReducedRowEchelonForm);

showstat(:-LinearAlgebra:-LUDecomposition);
</code>```

The Student[LinearAlgebra] package also has some visualization commands, for plotting. Eg,

```<code>showstat(Student:-LinearAlgebra:-EigenPlot);
</code>```

And it also has some commands which launch interactive applets (or "Tutors", which are written using Maple code from its Maplets package which generate Java popup applets). Eg,

```<code>showstat(Student:-LinearAlgebra:-GaussianEliminationTutor);
</code>```

The showstat command displays line numbers for the source. To see it without line numbers, and with syntax-highlighting and indentation, try this,

```<code> interface(verboseproc=3):
 print(:-LinearAlgebra:-LUDecomposition);
</code>```

You can write your own procedures (commands) in Maple, to compute whatever you want, and you can even save them to your own Library archive(s) for re-use later on. But a large portion of Maple is the set of thousands of procedures that have already been developed and are available to you.

If you want to know more then you should be more specific about what you're asking, I think.

Reading the User Manual (and, if you need more information, the Programming Guide) is also a good idea. You can access both from within Maple's Help.

Question 2)

When you issue the command,

```<code>with(Student[LinearAlgebra]):
</code>```

Maple rebinds the names of the exports (commands intended for use directly by the user) from their long-form name to the short-form name. The effect is that you can then use the commands with less manual typing on the keyboard. This act of "loading" the package may also result in some additions being made to the context-sensitive menus (what pops up when you right-click on a Matrix, say).

Even if you don't "load the package" using the with command you can still use the commands from the package. For example, if M is a Matrix then you can always call,

```<code>Student:-LinearAlgebra:-Rank( M );
</code>```

or

```<code>Student[LinearAlgebra][Rank]( M );
</code>```

even if you haven't called with(Student[LinearAlgebra]) beforehand. But once you've executed,

```<code>with(Student[LinearAlgebra]):
</code>```

then you can use the much shorter syntax,

```<code>Rank( M );
</code>```

Body:
Does Maple use a scripting language for algorithms inside packages,
like Student[LinearAlgebra]?
What really does command for loading a package, like this:

with(Student[LinearAlgebra]):

Body:
The first of your two questions seems to be pretty similar to asking how Maple commands generally work, which is pretty broad so I'll just give a summary.

Question 1)

Maple is an interpreted language. Commands from its Student[LinearAlgebra] package are written in the Maple language, and stored by Maple in a so-called Maple Library archive (a file with filename extension .mla).

You can see and inspect most of the source of those package's exported commands using the Maple commands showstat (or print, when interface(verboseproc) is high enough). Note that the source of most of these commands involves calls to other, internal routines in the package (most of which in turn are written in the Maple language).

Many of the computational commands in the Student[LinearAlgebra] package  involve not much more than to calls to the LinearAlgebra package. Try these Maple commands, as examples:

showstat(Student:-LinearAlgebra:-ReducedRowEchelonForm);

showstat(:-LinearAlgebra:-ReducedRowEchelonForm);

showstat(:-LinearAlgebra:-LUDecomposition);

The Student[LinearAlgebra] package also has some visualization commands, for plotting. Eg,

showstat(Student:-LinearAlgebra:-EigenPlot);

And it also has some commands which launch interactive applets (or "Tutors", which are written using Maple code from its Maplets package which generate Java popup applets). Eg,

showstat(Student:-LinearAlgebra:-GaussianEliminationTutor);

The showstat command displays line numbers for the source. To see it without line numbers, and with syntax-highlighting and indentation, try this,

 interface(verboseproc=3):
 print(:-LinearAlgebra:-LUDecomposition);

You can write your own procedures (commands) in Maple, to compute whatever you want, and you can even save them to your own Library archive(s) for re-use later on. But a large portion of Maple is the set of thousands of procedures that have already been developed and are available to you.

If you want to know more then you should be more specific about what you're asking, I think.

Reading the User Manual (and, if you need more information, the Programming Guide) is also a good idea. You can access both from within Maple's Help.

Question 2)

When you issue the command,

with(Student[LinearAlgebra]):

Maple rebinds the names of the exports (commands intended for use directly by the user) from their long-form name to the short-form name. The effect is that you can then use the commands with less manual typing on the keyboard. This act of "loading" the package may also result in some additions being made to the context-sensitive menus (what pops up when you right-click on a Matrix, say).

Even if you don't "load the package" using the with command you can still use the commands from the package. For example, if M is a Matrix then you can always call,

Student:-LinearAlgebra:-Rank( M );

or

Student[LinearAlgebra][Rank]( M );

even if you haven't called with(Student[LinearAlgebra]) beforehand. But once you've executed,

with(Student[LinearAlgebra]):

then you can use the much shorter syntax,

Rank( M );


问:
WordPress generated files edited with HTML
After basic knowledge of HTML/CSS/JS and Jquery, I got myself into WordPress. In order to save time and not build things from zero, I would use pre-made templates, and modify them according to the built of the desired future webpage. There might be a huge misconception in my head, but so far I havent found reply for this solution.

I have a locally running WordPress webpage with the help of WAMP. My webpage would consist 3 separate HTML files, lets say "index.html, contact.html, about.html". My issue is that after generating those pages in WordPress, I dont find any way to modify the HTML file of those sites. Nor locally in my computer, nor in the surface of WordPress. I found the "editor" function in WP, but apparently it lets me to edit only the CSS file.

My main goal is to generate the file with a template, than import it to BRACKETS / ATOM / etc and custom-shape the HTML and CSS on it. What am I missing ?

Thanks,

答:
I think you are using HTML files as a template which are not dynamically converted into wordpress theme. that's why you can't edit these files. You need to follow these steps.
1. your index file must be in index.php not index.html
2. style.css file with valid codes and most important thing is you need to know wordpress theme development. https://developer.wordpress.org/themes/basics/template-files/ This will help you</p>


答:
HTML5 comes equipped with a download attribute, and compatibility is actually pretty good.

Download```

https://www.w3schools.com/tags/att_a_download.asp

Title: Mozilla Firefox download option

Body:
HTML5 comes equipped with a download attribute, and compatibility is actually pretty good.

<a href="path/to/file.pdf" download="filename.pdf">Download</a>

https://www.w3schools.com/tags/att_a_download.asp


问:
Random graph generator
I am interested in generating weighted, directed random graphs with node constraints. Is there a graph generator in R or Python that is customizable? The only one I am aware of is igraph's erdos.renyi.game() but I am unsure if one can customize it.

Edit: the customizations I want to make are 1) drawing a weighted graph and 2) constraining some nodes from drawing edges.

答:
In igraph python, you can use link  the Erdos_Renyi class.

For constraining some nodes from drawing edges, this is controlled by the p value.

```<code>Erdos_Renyi(n, p, m, directed=False, loops=False) #these are the defaults
</code>```

Example:

```<code>from igraph import *

g = Graph.Erdos_Renyi(10,0.1,directed=True)
plot(g)
</code>```

By setting the p=0.1 you can see that some nodes do not have edges.

For the weights you can do something like:

```<code>g.ecount() # to find the number of edges
g.es["weights"] = range(1, g.ecount())
g.es["label"] = weights
plot(g)
</code>```

Result:

Title: Random graph generator

Body:
In igraph python, you can use link  the Erdos_Renyi class.

For constraining some nodes from drawing edges, this is controlled by the p value.

Erdos_Renyi(n, p, m, directed=False, loops=False) #these are the defaults

Example:

from igraph import *

g = Graph.Erdos_Renyi(10,0.1,directed=True)
plot(g)

By setting the p=0.1 you can see that some nodes do not have edges.

For the weights you can do something like:

g.ecount() # to find the number of edges
g.es["weights"] = range(1, g.ecount())
g.es["label"] = weights
plot(g)

Result:


问:
Infinite Loops and Early Return Statements
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

```<code>int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}
</code>```

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

```<code>int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}
</code>```

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

答:
I think the while(true) with break is best for a few reasons.  Introducing a variable to store the exit condition is error prone, more variables means more can go wrong.  Also the break statement is meant specifically for breaking out of loops.  Lastly, contrary to for(;;), while(true) is clean, readable, and concise, where for(;;) is trying to be clever for no good reason.

For an added point, to enhance readability and comprehension put the exit condition(s) nearest to the top of the loop as possible:

```<code>while (true) {

    OutputMenu();

    string UserChoice;
    cin >> UserChoice;

    if (UserChoice == "exit")
        break;

    // process other options here
}
</code>```

Body:
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

Body:
I think the while(true) with break is best for a few reasons.  Introducing a variable to store the exit condition is error prone, more variables means more can go wrong.  Also the break statement is meant specifically for breaking out of loops.  Lastly, contrary to for(;;), while(true) is clean, readable, and concise, where for(;;) is trying to be clever for no good reason.

For an added point, to enhance readability and comprehension put the exit condition(s) nearest to the top of the loop as possible:

while (true) {

    OutputMenu();

    string UserChoice;
    cin >> UserChoice;

    if (UserChoice == "exit")
        break;

    // process other options here
}


问:
How do I fix Dagger 2 error '... cannot be provided [...]'?

This is a Canonical Question because this is a common error with Dagger 2.

If your question was flagged as a duplicate please read this post carefully and make sure to understand what this error means and why it occured. If this post does not work for you make sure to include where and how you provide the mentioned classes and include the full error message in your question like the one here.

I tried to use a dependency with Dagger 2, but I receive the following error when I try to compile my project:

error: com.example.MyDependency cannot be provided without an @Inject constructor or from an @Provides-annotated method.

com.example.MyDependency is provided at

  com.example.MyComponent.myDependency()

What does this mean and how can I fix it?

I have a component and tried to provide a dependency. My basic setup looks like this:

```<code>// this is the dependency I try to use
class MyDependency {}

@Component
interface MyComponent {
    // I want to make it accessible to be used with my component
    MyDependency myDependency();
}
</code>```

答:
tl;dr You forgot to either add an @Inject to your constructor so that Dagger can use Constructor Injection to provide the object, or you need some method in one of your Modules that creates or binds the object.

What's going on?

Have a good look at the error message: It states that you try to request a dependency but Dagger has no way to provide or create it. It simply does not know how to, because it cannot be provided without an @Inject constructor or from an @Provides-annotated method.

A close look at the error message shows the class (a) that you are trying to provide and the component (b) that needs it.

com.example.MyDependency (a) is provided at

  com.example.MyComponent.myDependency() (b)

You have to make sure that (b) can create or provide (a) to fix your issue.

It looks a bit more complex if you tried to inject your dependency somewhere else, but you can still see the full stack of events—in this case a constructor injection missing a dependency. The class (a) that you are trying to provide and the location (b) where Dagger tried injecting it. It also tells you where that dependent class was created (c) and again the component (d) that failed providing (a).

com.example.MyDependency cannot be provided without an @Inject constructor or from an @Provides-annotated method.

  com.example.MyDependency (a) is injected at

  com.example.DependentClass.(dependency) (b)

  com.example.DependentClass is provided at (c)

  com.example.MyComponent.myDependency() (d)

The same applies here: Make sure that (d) knows how to provide (a) and you're good to go.

How do I fix this?

Have a look at the error as shown above. Make sure you understand where it occured and what you are trying to inject. Then tell Dagger how to provide your object.

an @Inject constructor

As the error states, you try to use MyDependency but MyComponent does not know how to do that. If we have a look at the example it becomes clear why:

```<code>class MyDependency {}
</code>```

The class has no @Inject annotated constructor! And there is no other module in the component, so there is nothing Dagger could do.

If you want to use constructor injection you can just add an @Inject annotated constructor and are done. Dagger will see this constructor and know how to create your class.

```<code>class MyDependency {
    @Inject
    MyDependency() { /**/ }
}
</code>```

That is all you have to do when you can make use of constructor injection.

from an @Provides-annotated method

The error message states a second option, which allows you to provide an object if you don't want—or can't—use constructor injection. You can also add a @Provides annotated method to a module and add this module to your component.

```<code>@Module
class MyModule {
    @Provides
    MyDependency provideMyDependency() {
        return new MyDependency();
    }
}

@Component(modules = MyModule.class)
interface MyComponent {
    MyDependency myDependency();
}
</code>```

This way Dagger can use your module to create and provide your dependency. It is a little bit more boilerplate than using Constructor Injection, but you will have to use Modules for everything that needs further setup or that does not have an annotated constructor, e.g. third party libraries like Retrofit, OkHttp, or Gson.

There are also other ways to provide a dependency from a component. A @SubComponent has access to its parents dependencies, and a component dependency can expose some of its dependencies to its dependent components. But at some point everything Dagger provides needs to either have an @Inject constructor or a Module providing it.

But I did add MyDependency!

Pay close attention to the details. You probably are using an interface when you are only providing the implementation, or try to use a parent class when Dagger only knows about the subclass.

Maybe you added a custom @Qualifier or used @Named("typeA") with it. To Dagger this is a completely different object! Double check that you actually provide and request the same dependency.

Read the error and make sure that you either have an @Inject annotated constructor, a module that has a @Provides method that provides that type, or a parent component that does.

What if I want to provide an implementation for my interface?

A simple example like the following shows how one class extends another:

```<code>class MyDependency extends MyBaseDependency {
    @Inject MyDependency() { super(); }
}
</code>```

This will inform Dagger about MyDependency, but not about MyBaseDependency.

If you have one class implementing an interface or extending a super class you have to declare that. If you provide MyDependency this does not mean that Dagger can provide MyBaseDependency. You can use @Binds to tell Dagger about your implementation and provide it when the super class is required.

```<code>@Module
interface MyModule {
    @Binds
    MyBaseDependency provideMyBaseDependency(MyDependency implementation);
}
</code>```

Body:
This is a Canonical Question because this is a common error with Dagger 2.

If your question was flagged as a duplicate please read this post carefully and make sure to understand what this error means and why it occured. If this post does not work for you make sure to include where and how you provide the mentioned classes and include the full error message in your question like the one here.

I tried to use a dependency with Dagger 2, but I receive the following error when I try to compile my project:

error: com.example.MyDependency cannot be provided without an @Inject constructor or from an @Provides-annotated method.

com.example.MyDependency is provided at

  com.example.MyComponent.myDependency()

What does this mean and how can I fix it?

I have a component and tried to provide a dependency. My basic setup looks like this:

// this is the dependency I try to use
class MyDependency {}

@Component
interface MyComponent {
    // I want to make it accessible to be used with my component
    MyDependency myDependency();
}

Body:
tl;dr You forgot to either add an @Inject to your constructor so that Dagger can use Constructor Injection to provide the object, or you need some method in one of your Modules that creates or binds the object.

What's going on?

Have a good look at the error message: It states that you try to request a dependency but Dagger has no way to provide or create it. It simply does not know how to, because it cannot be provided without an @Inject constructor or from an @Provides-annotated method.

A close look at the error message shows the class (a) that you are trying to provide and the component (b) that needs it.

com.example.MyDependency (a) is provided at

  com.example.MyComponent.myDependency() (b)

You have to make sure that (b) can create or provide (a) to fix your issue.

It looks a bit more complex if you tried to inject your dependency somewhere else, but you can still see the full stack of events—in this case a constructor injection missing a dependency. The class (a) that you are trying to provide and the location (b) where Dagger tried injecting it. It also tells you where that dependent class was created (c) and again the component (d) that failed providing (a).

com.example.MyDependency cannot be provided without an @Inject constructor or from an @Provides-annotated method.

  com.example.MyDependency (a) is injected at

  com.example.DependentClass.(dependency) (b)

  com.example.DependentClass is provided at (c)

  com.example.MyComponent.myDependency() (d)

The same applies here: Make sure that (d) knows how to provide (a) and you're good to go.

How do I fix this?

Have a look at the error as shown above. Make sure you understand where it occured and what you are trying to inject. Then tell Dagger how to provide your object.

an @Inject constructor

As the error states, you try to use MyDependency but MyComponent does not know how to do that. If we have a look at the example it becomes clear why:

class MyDependency {}

The class has no @Inject annotated constructor! And there is no other module in the component, so there is nothing Dagger could do.

If you want to use constructor injection you can just add an @Inject annotated constructor and are done. Dagger will see this constructor and know how to create your class.

class MyDependency {
    @Inject
    MyDependency() { /**/ }
}

That is all you have to do when you can make use of constructor injection.

from an @Provides-annotated method

The error message states a second option, which allows you to provide an object if you don't want—or can't—use constructor injection. You can also add a @Provides annotated method to a module and add this module to your component.

@Module
class MyModule {
    @Provides
    MyDependency provideMyDependency() {
        return new MyDependency();
    }
}

@Component(modules = MyModule.class)
interface MyComponent {
    MyDependency myDependency();
}

This way Dagger can use your module to create and provide your dependency. It is a little bit more boilerplate than using Constructor Injection, but you will have to use Modules for everything that needs further setup or that does not have an annotated constructor, e.g. third party libraries like Retrofit, OkHttp, or Gson.

There are also other ways to provide a dependency from a component. A @SubComponent has access to its parents dependencies, and a component dependency can expose some of its dependencies to its dependent components. But at some point everything Dagger provides needs to either have an @Inject constructor or a Module providing it.

But I did add MyDependency!

Pay close attention to the details. You probably are using an interface when you are only providing the implementation, or try to use a parent class when Dagger only knows about the subclass.

Maybe you added a custom @Qualifier or used @Named("typeA") with it. To Dagger this is a completely different object! Double check that you actually provide and request the same dependency.

Read the error and make sure that you either have an @Inject annotated constructor, a module that has a @Provides method that provides that type, or a parent component that does.

What if I want to provide an implementation for my interface?

A simple example like the following shows how one class extends another:

class MyDependency extends MyBaseDependency {
    @Inject MyDependency() { super(); }
}

This will inform Dagger about MyDependency, but not about MyBaseDependency.

If you have one class implementing an interface or extending a super class you have to declare that. If you provide MyDependency this does not mean that Dagger can provide MyBaseDependency. You can use @Binds to tell Dagger about your implementation and provide it when the super class is required.

@Module
interface MyModule {
    @Binds
    MyBaseDependency provideMyBaseDependency(MyDependency implementation);
}


问:
Node.JS and Java PUB/SUB
I'm trying to build an application that the communication will be done by a node.js server. This node server will receive messages from others peers.

My node.js code is:

```<code>var zmq = require('zmq'),
    socket = zmq.socket('sub');

socket.bind('tcp://127.0.0.1:5556', function (err) {
    if (err) {
        console.log('Error: ', err);
        throw err;
    }

    socket.on('message', function (envelope, blank, data) {
        console.log(arguments);
    });

    socket.on('error', function (err) {
        console.log(arguments);
    });
});
</code>```

In the other part of the system, there is a java server that should send messages for this server.
This is my java code:

```<code>Context context = ZMQ.context(1);
Socket publisher = context.socket(ZMQ.PUB);
publisher.connect("tcp://127.0.0.1:5556");
for (int request_nbr = 0; request_nbr < 10; request_nbr++) {
    publisher.send("Hello");
}
</code>```

For now, my java server is running locally and my node.js is running inside a docker with the port 5556 exposed.

I have success sending messages from the java server. But no message is received in my node.js server.

There is any problem in my ZeroMQ initialization?

答:
Yes, there is a problem:

As defined in the ZeroMQ protocol-specifications, the SUB-Formal Scalable Communication Pattern archetype has an empty subscription list upon it's instantiation.

Empty SUB-side subscription is the cause:

Your SUB-side has to indeed subscribe to anything else ( be it at least a "" - yes - an empty string is enough, for starting receiving any and all messages, or may setup some problem/context-specific string(s), as TOPIC-filter, where each message will start to get tested for a presence of at least one of such TOPIC-s, and discarded ( not .recv()-ed or not promoted into the hands of .on( 'message', ... ) handler at all ).

Anyway, enjoy the ZeroMQ powers for the distributed computing!

Title: Node.JS and Java PUB/SUB

Body:
I'm trying to build an application that the communication will be done by a node.js server. This node server will receive messages from others peers.

My node.js code is:

var zmq = require('zmq'),
    socket = zmq.socket('sub');

socket.bind('tcp://127.0.0.1:5556', function (err) {
    if (err) {
        console.log('Error: ', err);
        throw err;
    }

    socket.on('message', function (envelope, blank, data) {
        console.log(arguments);
    });

    socket.on('error', function (err) {
        console.log(arguments);
    });
});

In the other part of the system, there is a java server that should send messages for this server.
This is my java code:

Context context = ZMQ.context(1);
Socket publisher = context.socket(ZMQ.PUB);
publisher.connect("tcp://127.0.0.1:5556");
for (int request_nbr = 0; request_nbr < 10; request_nbr++) {
    publisher.send("Hello");
}

For now, my java server is running locally and my node.js is running inside a docker with the port 5556 exposed.

I have success sending messages from the java server. But no message is received in my node.js server.

There is any problem in my ZeroMQ initialization?


问:
Two different shaped objects collision detection in p5.js
I'm trying to have my Particle object collide and reflect off my Slate object.

If I wanted to use an ellipse, it would be simple because I could just create a radius variable - can't do that with a rectangle.

It's something to do with the distance variable, I just can't figure it out.

```<code>var div;
var movers;

function setup() {
  createCanvas(windowWidth,windowHeight);
  background("#FDEDEB");
  div = new Slate();
  movers = new Particle();
}

function draw() {

  background("#FDEDEB");

  div.display();

  movers.display();
  movers.update();
  movers.move();

  if (movers.hits(div)) {
    console.log("hit");
  }

}

function Slate() {

  this.x = 30;
  this.y = height/2;

  this.display = function() {
  noStroke();
  fill("#DF4655");
  rect(this.x,this.y, 700, 200);

  }
}

function Particle() {
  this.pos = createVector(10,0);
  this.vel = createVector(0,0);
  this.acc = createVector(0.01,0.01);
  this.history = [];

  this.display = function() {
    fill("#DF4655");
    point(this.pos.x,this.pos.y);

    //beginShape();
    for(var j = 0; j < this.history.length; j++) {
      var pos = this.history[j];
      ellipse(pos.x,pos.y, 5, 3);
    }
    //endShape();

  }

  this.update = function() {

    var v = createVector(this.pos.x,this.pos.y);
    this.history.push(v);
    if (this.history.length > 10) {
      this.history.splice(0,1);
    }
  }

  this.hits = function(div) {
        // BOUNCE OFF SLATE
      var d = dist(this.pos.x,this.pos.y,div.x,div.y);
      if (d < 0) {
        console.log('hits');
      }
  }

  this.move = function() {

    this.pos.add(this.vel);
    this.vel.add(this.acc);
    this.vel.limit(10);

    for (var i = 0; i < this.history.length; i++) {
      this.history[i].x += random(-2,2);
      this.history[i].y += random(-2,2);
    }

  }
}
</code>```

答:
If the particle is a point (or can be represented as a point), you need to use point-rectangle collision detection. Basically you would need to check whether the point is between the left and right edges and the top and bottom edges of the rectangle.

```<code>if(pointX > rectX && pointX < rectX + rectWidth && pointY > rectY && pointY < rectY + rectHeight){
  //the point is inside the rectangle
}
</code>```

If the particle is an ellipse and you need to factor in the radius of that ellipse, then you're better off representing the particle as a rectangle, just for collision purposes. Then you can use rectangle-rectangle collision detection. This is also called a bounding box, and it's one of the most common ways to handle collision detection.

```<code>if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){
  //the rectangles are colliding
}
</code>```

Shameless self-promotion: I wrote a tutorial on collision detection available here. It's for Processing, but everything is the same for P5.js.

Body:
I'm trying to have my Particle object collide and reflect off my Slate object.

If I wanted to use an ellipse, it would be simple because I could just create a radius variable - can't do that with a rectangle.

It's something to do with the distance variable, I just can't figure it out.

var div;
var movers;

function setup() {
  createCanvas(windowWidth,windowHeight);
  background("#FDEDEB");
  div = new Slate();
  movers = new Particle();
}

function draw() {

  background("#FDEDEB");

  div.display();

  movers.display();
  movers.update();
  movers.move();

  if (movers.hits(div)) {
    console.log("hit");
  }

}

function Slate() {

  this.x = 30;
  this.y = height/2;

  this.display = function() {
  noStroke();
  fill("#DF4655");
  rect(this.x,this.y, 700, 200);

  }
}

function Particle() {
  this.pos = createVector(10,0);
  this.vel = createVector(0,0);
  this.acc = createVector(0.01,0.01);
  this.history = [];

  this.display = function() {
    fill("#DF4655");
    point(this.pos.x,this.pos.y);

    //beginShape();
    for(var j = 0; j < this.history.length; j++) {
      var pos = this.history[j];
      ellipse(pos.x,pos.y, 5, 3);
    }
    //endShape();

  }

  this.update = function() {

    var v = createVector(this.pos.x,this.pos.y);
    this.history.push(v);
    if (this.history.length > 10) {
      this.history.splice(0,1);
    }
  }

  this.hits = function(div) {
        // BOUNCE OFF SLATE
      var d = dist(this.pos.x,this.pos.y,div.x,div.y);
      if (d < 0) {
        console.log('hits');
      }
  }

  this.move = function() {

    this.pos.add(this.vel);
    this.vel.add(this.acc);
    this.vel.limit(10);

    for (var i = 0; i < this.history.length; i++) {
      this.history[i].x += random(-2,2);
      this.history[i].y += random(-2,2);
    }

  }
}

Body:
If the particle is a point (or can be represented as a point), you need to use point-rectangle collision detection. Basically you would need to check whether the point is between the left and right edges and the top and bottom edges of the rectangle.

if(pointX > rectX && pointX < rectX + rectWidth && pointY > rectY && pointY < rectY + rectHeight){
  //the point is inside the rectangle
}

If the particle is an ellipse and you need to factor in the radius of that ellipse, then you're better off representing the particle as a rectangle, just for collision purposes. Then you can use rectangle-rectangle collision detection. This is also called a bounding box, and it's one of the most common ways to handle collision detection.

if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){
  //the rectangles are colliding
}

Shameless self-promotion: I wrote a tutorial on collision detection available here. It's for Processing, but everything is the same for P5.js.


问:
how to handle Angular 2 CanActivate Route Guards
I have implemented Route Guards on my application. Before the user access the dashboard route, I have checked whether the user has logged in or not.

It get worked fine user access dashboard after logged in , but if the user try to access the route dashboard without logged in am getting blank page . The CanActivate Guard is executed and it return false.

However, I want to redirect the user to the logging page if the CanActivate is failed.

How can I redirect the user to another Route if the Route Guard failed?

This is i what i have followed

import { Routes, RouterModule } from '@angular/router';
import { AccountPage } from './account-page';
import { LoginRouteGuard } from './login-route-guard';
import { SaveFormsGuard } from './save-forms-guard';
const routes: Routes = [
{ path: 'home', component: HomePage },
{
path: 'accounts',
component: AccountPage,
canActivate: [LoginRouteGuard],
canDeactivate: [SaveFormsGuard]
}
];
export const appRoutingProviders: any[] = [];
export const routing = RouterModule.forRoot(routes);```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { CanActivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { LoginService } from './login-service';
@Injectable()
export class LoginRouteGuard implements CanActivate {
constructor(private loginService: LoginService) {}
canActivate() {
return this.loginService.isLoggedIn();
}
}</code>```

答:
1. Create a class which implements CanActivate of router module

```<code>    import {Injectable} from '@angular/core';
    import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
    import { Observable } from 'rxjs/Observable';
    import { LoginService } from './login/login.service';
    // Here LoginService is a custom service to check the user authentication.
    @Injectable()
    export class CanActivateAuthGuard implements CanActivate  {
        constructor(private router: Router, private loginService: LoginService) { };
        canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
            if (this.loginService.GetAuthStatus()) {
                return true;
            } else {
            this.router.navigate(['/login']);
            return false;
            }
        };
    }
</code>```

2. Add the class to provider array to NgModule in the  app.module.ts file

```<code>       import { CanActivateAuthGuard } from './auth.guard';

     @MgModule({
        providers: [
        ...
        CanActivateAuthGuard,
        ...
        ],
     })
</code>```

3. In the router constant use the service in the canActivate (provided by angular router) property

```<code>    { path: 'dashboard' , component: DashBoardComponent, canActivate: [CanActivateAuthGuard] }
</code>```

Body:
I have implemented Route Guards on my application. Before the user access the dashboard route, I have checked whether the user has logged in or not.

It get worked fine user access dashboard after logged in , but if the user try to access the route dashboard without logged in am getting blank page . The CanActivate Guard is executed and it return false.

However, I want to redirect the user to the logging page if the CanActivate is failed.

How can I redirect the user to another Route if the Route Guard failed?

This is i what i have followed

import { Routes, RouterModule } from '@angular/router';
import { AccountPage } from './account-page';
import { LoginRouteGuard } from './login-route-guard';
import { SaveFormsGuard } from './save-forms-guard';
const routes: Routes = [
{ path: 'home', component: HomePage },
{
path: 'accounts',
component: AccountPage,
canActivate: [LoginRouteGuard],
canDeactivate: [SaveFormsGuard]
}
];
export const appRoutingProviders: any[] = [];
export const routing = RouterModule.forRoot(routes);

import { CanActivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { LoginService } from './login-service';
@Injectable()
export class LoginRouteGuard implements CanActivate {
constructor(private loginService: LoginService) {}
canActivate() {
return this.loginService.isLoggedIn();
}
}

Body:
1. Create a class which implements CanActivate of router module

    import {Injectable} from '@angular/core';
    import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
    import { Observable } from 'rxjs/Observable';
    import { LoginService } from './login/login.service';
    // Here LoginService is a custom service to check the user authentication.
    @Injectable()
    export class CanActivateAuthGuard implements CanActivate  {
        constructor(private router: Router, private loginService: LoginService) { };
        canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
            if (this.loginService.GetAuthStatus()) {
                return true;
            } else {
            this.router.navigate(['/login']);
            return false;
            }
        };
    }

2. Add the class to provider array to NgModule in the  app.module.ts file

       import { CanActivateAuthGuard } from './auth.guard';

     @MgModule({
        providers: [
        ...
        CanActivateAuthGuard,
        ...
        ],
     })

3. In the router constant use the service in the canActivate (provided by angular router) property

    { path: 'dashboard' , component: DashBoardComponent, canActivate: [CanActivateAuthGuard] }


问:
Display data in html/js file using NodeJs from mysql database
My index.js file is

```<code>var express         = require('express');
var  app            = express();
var path            = require('path');
var router          = express.Router();
var data            = require('./data/jsonData');
var createDatabase  = require('./data/db');
var careateTable    = require('./data/createTable');
var insert          = require('./data/insert');
var bodyParser      = require('body-parser');
var select          = require('./data/select');

app.use(express.static(path.join(__dirname, 'www')));
app.use(express.static(path.join(__dirname, 'form')));
app.use(bodyParser());
app.get('/' , function (req , res) {
    res.sendFile(path.join(__dirname + '/www/index.html'));
});

app.get('/data' ,function (req , res) {
    res.json(data);
});
app.get('/form' ,function (req , res) {
    res.sendFile(path.join(__dirname + '/form/index.html'));
});
app.post('/form' ,function (req , res) {
    console.log(req.body.user);
    console.log(req.body.password);
    insert.insertModule(req.body.user , req.body.password);
    res.sendFile(path.join(__dirname + '/www/index.html'));
});
app.get('/show' , function (req , res) {
    var i ;
   select.select( function (err, results) {
       if (err == 'error') {
           console.log(err);
       } else {
           console.log(results);
           res.send(results.username);
       }
   });

});

app.listen(3000);
console.log("App is listning on port 3000");
</code>```

and select.js is

```<code>var mysql = require('mysql');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "NodeDataBase"
});
con.connect(function (err) {
    if (err) throw err;
    console.log("Connected!");
});

module.exports  = {
    select: function (callback) {
        var sql = "SELECT username , password FROM login ";
        con.query(sql, function (err, result , fields) {
            if (err) {
                callback("error", err)
            } else {
                callback("success", result)
            }
        });
    }
}
</code>```

I want to show the results object data to html file , So how can i do this please suggest me.

from a get request /show it will show all userdata fetched from the database

答:
May be you can use view engine such As EJS, Jade to render data from node to the front end.

If you want to render the data on the html page, i will do it like http://localhost:3000/show : with json -resonponse

```<code>var express = require('express');
var app = express();

require('json-response');

app.get('/', function(req, res){
  res.ok({foo: 'bar'}, 'hello world');
});
</code>```

i will return json from the link and in Index.html with the help of jquery/Ajax will hit the link , retrieve the  value and show it on HTML

Body:
My index.js file is

var express         = require('express');
var  app            = express();
var path            = require('path');
var router          = express.Router();
var data            = require('./data/jsonData');
var createDatabase  = require('./data/db');
var careateTable    = require('./data/createTable');
var insert          = require('./data/insert');
var bodyParser      = require('body-parser');
var select          = require('./data/select');

app.use(express.static(path.join(__dirname, 'www')));
app.use(express.static(path.join(__dirname, 'form')));
app.use(bodyParser());
app.get('/' , function (req , res) {
    res.sendFile(path.join(__dirname + '/www/index.html'));
});

app.get('/data' ,function (req , res) {
    res.json(data);
});
app.get('/form' ,function (req , res) {
    res.sendFile(path.join(__dirname + '/form/index.html'));
});
app.post('/form' ,function (req , res) {
    console.log(req.body.user);
    console.log(req.body.password);
    insert.insertModule(req.body.user , req.body.password);
    res.sendFile(path.join(__dirname + '/www/index.html'));
});
app.get('/show' , function (req , res) {
    var i ;
   select.select( function (err, results) {
       if (err == 'error') {
           console.log(err);
       } else {
           console.log(results);
           res.send(results.username);
       }
   });

});

app.listen(3000);
console.log("App is listning on port 3000");

and select.js is

var mysql = require('mysql');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "NodeDataBase"
});
con.connect(function (err) {
    if (err) throw err;
    console.log("Connected!");
});

module.exports  = {
    select: function (callback) {
        var sql = "SELECT username , password FROM login ";
        con.query(sql, function (err, result , fields) {
            if (err) {
                callback("error", err)
            } else {
                callback("success", result)
            }
        });
    }
}

I want to show the results object data to html file , So how can i do this please suggest me.

from a get request /show it will show all userdata fetched from the database

Body:
May be you can use view engine such As EJS, Jade to render data from node to the front end.

If you want to render the data on the html page, i will do it like http://localhost:3000/show : with json -resonponse

var express = require('express');
var app = express();

require('json-response');

app.get('/', function(req, res){
  res.ok({foo: 'bar'}, 'hello world');
});

i will return json from the link and in Index.html with the help of jquery/Ajax will hit the link , retrieve the  value and show it on HTML


问:
Redirecting standard output when generated
I am trying to redirect the output of a c program which generates output in the console. I can redirect the output once the process exits. But is there the way to redirect the output as and when there is some output in the shell window? I require this to make it understandable that the program is running and since different steps of the c code may take, say 10-15 minutes to run.

Thanks in advance for any help.

答: I'm guessing the code that you're using is using ReadToEnd on the StreamReader. If so, just use Read or ReadLine to get access to the stream as its written.


问:
Prevent cache in CloudFlare
I'm getting started with CloudFlare and I’m using it to build a new project.

I’m facing an issue when I make changes: I cannot see my changes in the browser, so I assume the problem here is the cache setting of CloudFlare.

I have read this link, about the CloudFlare cache, so I put the following meta-tag in my html:

```<code><meta http-equiv="Cache-control" content="private">
</code>```

But the problem still remain.

Should I put other meta-tags, or prevent -somehow- caching from the server-side? (I'm using PHP)

答:
This is very old question. To disable this we don't have to turn on development mode because cloudfare caches the CSS and JS. If you want to disable only the particular JS or CSS simply put following attribute to the link or script tag.</p>

```<code><script data-cfasync="false" src="/javascript.js"></script>
</code>```

Title: Prevent cache in CloudFlare

Body:
I'm getting started with CloudFlare and I’m using it to build a new project.

I’m facing an issue when I make changes: I cannot see my changes in the browser, so I assume the problem here is the cache setting of CloudFlare.

I have read this link, about the CloudFlare cache, so I put the following meta-tag in my html:

<meta http-equiv="Cache-control" content="private">

But the problem still remain.

Should I put other meta-tags, or prevent -somehow- caching from the server-side? (I'm using PHP)

Body:
This is very old question. To disable this we don't have to turn on development mode because cloudfare caches the CSS and JS. If you want to disable only the particular JS or CSS simply put following attribute to the link or script tag.

<script data-cfasync="false" src="/javascript.js"></script>


问:
PhpStorm not finding methods in objects created by late static binding by parent abstract class
In my PHP application I have a base class for all database objects, which is further extended by specific model classes. It goes on like this (simplified):

```<code>abstract class Model extends Collection {

    (...)

    function __construct(string $primary_key, string $value) {
        $data = MysqlDB::instance() -> select(static::TABLE, implode(',', static::COLUMNS), "$primary_key=\"$value\"");
        if (count($data) != 1)
            throw new ModelException('Select condition uncertain');
        parent::__construct($data[0]);
    }

    public static function getById(string $id) : ?Model {
        try {
            return new static('id', $id);
        } catch (ModelException $e) {
            return NULL;
        }
    }

    (...)

}
</code>```

The point is, I use the getById function on child classes to obtain the needed objects. However, since the return type of getById method is Model, PhpStorm can't figure out what methods the objects has and highlights the ones I use as an error. Consequently, no type-hinting available.

For instance, assuming that final class User extends Model and that class User has method sendNotification, this kind of code:

```<code>User::getById($id) -> sendNotification($param1, $param2, ...)
</code>```

has sendNotification yellowed out as though it did not exist.

I know this isn't that much of an issue, but it's really irritating in terms of that I get distracted by constant redundant warnings and that I can't use type-hinting in such a usage case.

答:
There are three ways to achieve this, none of them has anything to do with PHPStorm.

First overwrite the method in every child with the proper return type:

```<code>/**
 * @return User
 */
public static function getById(string $id) : ?Model { return parent::getById($id); }
</code>```

Second add all possible children to the return tag of the abstract class.

```<code>/**
 * @return Model|User|...
 */
public static function getById(string $id) : ?Model { /* ... */ }
</code>```

Third add a type hint just in place:

```<code>/** @var User $user */
$user = User::getById($id);
$user->sendNotification($param1, $param2, ...);
</code>```

These are not nice and hard to maintain. But there is no "setting" in PHPStorm for that.

Body:
In my PHP application I have a base class for all database objects, which is further extended by specific model classes. It goes on like this (simplified):

abstract class Model extends Collection {

    (...)

    function __construct(string $primary_key, string $value) {
        $data = MysqlDB::instance() -> select(static::TABLE, implode(',', static::COLUMNS), "$primary_key=\"$value\"");
        if (count($data) != 1)
            throw new ModelException('Select condition uncertain');
        parent::__construct($data[0]);
    }

    public static function getById(string $id) : ?Model {
        try {
            return new static('id', $id);
        } catch (ModelException $e) {
            return NULL;
        }
    }

    (...)

}

The point is, I use the getById function on child classes to obtain the needed objects. However, since the return type of getById method is Model, PhpStorm can't figure out what methods the objects has and highlights the ones I use as an error. Consequently, no type-hinting available.

For instance, assuming that final class User extends Model and that class User has method sendNotification, this kind of code:

User::getById($id) -> sendNotification($param1, $param2, ...)

has sendNotification yellowed out as though it did not exist.

I know this isn't that much of an issue, but it's really irritating in terms of that I get distracted by constant redundant warnings and that I can't use type-hinting in such a usage case.

Body:
There are three ways to achieve this, none of them has anything to do with PHPStorm.

First overwrite the method in every child with the proper return type:

/**
 * @return User
 */
public static function getById(string $id) : ?Model { return parent::getById($id); }

Second add all possible children to the return tag of the abstract class.

/**
 * @return Model|User|...
 */
public static function getById(string $id) : ?Model { /* ... */ }

Third add a type hint just in place:

/** @var User $user */
$user = User::getById($id);
$user->sendNotification($param1, $param2, ...);

These are not nice and hard to maintain. But there is no "setting" in PHPStorm for that.


问:
Is it bad practice to return from within a try catch finally block?
So I came across some code this morning that looked like this:

```<code>try
{
    x = SomeThingDangerous();
    return x;
}
catch (Exception ex)
{
    throw new DangerousException(ex);
}
finally
{
    CleanUpDangerousStuff();
}
</code>```

Now this code compiles fine and works as it should, but it just doesn't feel right to return from within a try block, especially if there's an associated finally.

My main issue is what happens if the finally throws an exception of it's own? You've got a returned variable but also an exception to deal with... so I'm interested to know what others think about returning from within a try block?

答: No, it's not a bad practice. Putting return where it makes sense improves readability and maintainability and makes your code simpler to understand. You shouldn't care as finally block will get executed if a return statement is encountered.

OwnerDisplayName: lomaxx

Body:
So I came across some code this morning that looked like this:

try
{
    x = SomeThingDangerous();
    return x;
}
catch (Exception ex)
{
    throw new DangerousException(ex);
}
finally
{
    CleanUpDangerousStuff();
}

Now this code compiles fine and works as it should, but it just doesn't feel right to return from within a try block, especially if there's an associated finally.

My main issue is what happens if the finally throws an exception of it's own? You've got a returned variable but also an exception to deal with... so I'm interested to know what others think about returning from within a try block?

OwnerDisplayName: Mehrdad Afshari


问:
iPhone app for testing Push Notifications from Firebase
I am developing NodeJS code to sendPush Notifications using Google's Firebase.
Currently it works for my Browser (I can get PN in my browser) and now would want to test the same on some iPhone app.

Is there a way to install some iPhone app to test Push Notifications?

Is there some Developer iPhone app that can serve for this purpose?

答:
You can but it would be a static code with javascript,

It's called cordova, I've seen someone created an example of it at Android. You can export it to iOS & Windows Phone too.


问:
extract an array from list in java
I have a list such:

```<code>List<string> list =Arrays.asList("2014-06-20 [txt1:executed]","2014-06-21 [txt2:in progressed]");
</code>```

I want to extract the contents to an array:

```<code>arr[0] =2014-06-20
arr[1] =executed
arr[2] =2014-06-21
arr[3] =in progressed
</code>```

答:
You might take a look at regular expressions. They are quite powerfull to split Strings according to your wishes.
Here is an example how you can split your String.

```<code>    String regex = "([0-9-]+)\\s+\\[\\w*:([\\w\\s]*)]";
    List<String> list = Arrays.asList("2014-06-20 [txt1:executed]","2014-06-21 [txt2:in progressed]");
    String date = list.get(0).replaceAll(regex, "$1");
    String status = list.get(0).replaceAll(regex, "$2");
</code>```

I hope that helps.

Title: extract an array from list in java

Body:
I have a list such:

List<string> list =Arrays.asList("2014-06-20 [txt1:executed]","2014-06-21 [txt2:in progressed]");

I want to extract the contents to an array:

arr[0] =2014-06-20
arr[1] =executed
arr[2] =2014-06-21
arr[3] =in progressed

Body:
You might take a look at regular expressions. They are quite powerfull to split Strings according to your wishes.
Here is an example how you can split your String.

    String regex = "([0-9-]+)\\s+\\[\\w*:([\\w\\s]*)]";
    List<String> list = Arrays.asList("2014-06-20 [txt1:executed]","2014-06-21 [txt2:in progressed]");
    String date = list.get(0).replaceAll(regex, "$1");
    String status = list.get(0).replaceAll(regex, "$2");

I hope that helps.