问:
Why are these responsive images not filling the wrapper?
I have a responsive image (srcset) that should be displayed at a max-width of 30rem, and fill the viewport otherwise. For that purpose I have the following html:

```<code><div class="Wrapper">
  <img
    src="//via.placeholder.com/250x150"
    srcset="
      //via.placeholder.com/100x150 100w,
      //via.placeholder.com/250x150 250w,
      //via.placeholder.com/500x150 500w,
      //via.placeholder.com/750x150 750w,
      //via.placeholder.com/1000x150 1000w,
      //via.placeholder.com/1250x150 1250w,
      //via.placeholder.com/1500x150 1500w"
    sizes="(min-width: 30em) 30rem, 100vw"
  >
</div>
</code>```

With this css (there is more, but this is the minimum to reproduce):

```<code>html {
  font-size: 24px;
}

img {
  max-width: 100%;
}

.Wrapper {
  margin: 0 auto;
  max-width: 30rem;
  background: red;
}
</code>```

On my monitor (macbook retina) the image is displayed like so:

So it isn't filling the viewport. Even though the measurements should be correct. I suspect that it has something to do with a difference in measurement between rem and em, but I'm not exactly sure what's going wrong. Why isn't the image filling the container?

Jsfiddle here: https://jsfiddle.net/Ly80zohd/2/

答:
May it help, Just remove below code from HTML and check it</p>

```<code>sizes="(min-width: 30em) 30rem, 100vw"
</code>```

Body:
I have a responsive image (srcset) that should be displayed at a max-width of 30rem, and fill the viewport otherwise. For that purpose I have the following html:

With this css (there is more, but this is the minimum to reproduce):

html {
  font-size: 24px;
}

img {
  max-width: 100%;
}

.Wrapper {
  margin: 0 auto;
  max-width: 30rem;
  background: red;
}

On my monitor (macbook retina) the image is displayed like so:

So it isn't filling the viewport. Even though the measurements should be correct. I suspect that it has something to do with a difference in measurement between rem and em, but I'm not exactly sure what's going wrong. Why isn't the image filling the container?

Jsfiddle here: https://jsfiddle.net/Ly80zohd/2/

Body:
May it help, Just remove below code from HTML and check it

sizes="(min-width: 30em) 30rem, 100vw"


来源: stackexchange

问:
How to run two methods in Gradle in parallel mode?
I got a Gradle task which calls two methods. The methods are independent of each other so I want to start them parallel. What is the best way to achieve this?

Example:

```<code>task cucumber(dependsOn: 'testClasses') {
    doLast {
        // ...
        // I want to call the next 2 methods in parallel
        runSequentialTests(testEnvironment, tags)
        runParallelTests(testEnvironment, tags)
    }
}

def runSequentialTests(testEnvironment, tags) {
    // execute cucumber tests via javaexec
}

def runParallelTests(testEnvironment, tags) {
    // execute cucumber tests via exec sh script for each feature file (parallelism is done via GParsPool.withPool(5) {...}
}
</code>```

答:
I used the asynchronous invocations of GPars: http://www.gpars.org/webapp/guide/#_asynchronous_invocations

I got it to work with this. Thanks

```<code>GParsPool.withPool {
    GParsPool.executeAsyncAndWait({runSequentialTests(testEnvironment, tags)}, {runParallelTests(testEnvironment, tags)})
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I got a Gradle task which calls two methods. The methods are independent of each other so I want to start them parallel. What is the best way to achieve this?

Example:

task cucumber(dependsOn: 'testClasses') {
    doLast {
        // ...
        // I want to call the next 2 methods in parallel
        runSequentialTests(testEnvironment, tags)
        runParallelTests(testEnvironment, tags)
    }
}

def runSequentialTests(testEnvironment, tags) {
    // execute cucumber tests via javaexec
}

def runParallelTests(testEnvironment, tags) {
    // execute cucumber tests via exec sh script for each feature file (parallelism is done via GParsPool.withPool(5) {...}
}

Body:
I used the asynchronous invocations of GPars: http://www.gpars.org/webapp/guide/#_asynchronous_invocations

I got it to work with this. Thanks

GParsPool.withPool {
    GParsPool.executeAsyncAndWait({runSequentialTests(testEnvironment, tags)}, {runParallelTests(testEnvironment, tags)})
}


问:
how to get data from mysql in php page in proper way?
My Mysql table contains one column Let's discuss together!! when when i get it into php page ? is displaying in place of ' means Let�s discuss together!!   . So how to to get data from mysql in php page in proper way </p>

答:
You required to use charset=UTF-8in your page. Add this line in you page,

```<code><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</code>```

Body:
You required to use charset=UTF-8in your page. Add this line in you page,

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />


问:
JavaScript/ES2015 - Keep all the properties of an object except one whit Rest/Spread operators
I have this object :

```<code>const value = {
  "template": "<span translate>myRecommendations</span>",
  "badge": "<span>{{ notifications }}</span>",
  "sref": "recommendation.list"
}
</code>```

I want to use the Rest / Spread operators to create another object with the same name (value) with all properties except the badge property

答:
So simply delete that property from the object if you want to keep the another shape in the current variable.

const value = {
  "template": "myRecommendations",
  "badge": "{{ notifications }}",
  "sref": "recommendation.list"
};

delete value.badge;

console.log(value);```
</div>
</div>
</p>

<p>If you need another object you can use object destructing with</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>const value = {
  "template": "<span translate>myRecommendations</span>",
  "badge": "<span>{{ notifications }}</span>",
  "sref": "recommendation.list"
};

const { badge, ...anotherValue } = value;

console.log(anotherValue);</code>```

Or iterate over the object keys and get the properties which you want

const value = {
   "template": "myRecommendations",
   "badge": "{{ notifications }}",
   "sref": "recommendation.list"
};

const anotherValue = Object.keys(value).reduce((obj, key) => {

  if(key !== 'badge') {
    obj[key] = value[key]    ;
  }

  return obj;
}, {});

console.log(anotherValue);```

Body:
I have this object :

const value = {
  "template": "myRecommendations",
  "badge": "{{ notifications }}",
  "sref": "recommendation.list"
}

I want to use the Rest / Spread operators to create another object with the same name (value) with all properties except the badge property

Body:
So simply delete that property from the object if you want to keep the another shape in the current variable.

const value = {
  "template": "<span translate>myRecommendations</span>",
  "badge": "<span>{{ notifications }}</span>",
  "sref": "recommendation.list"
};

delete value.badge;

console.log(value);

If you need another object you can use object destructing with

const value = {
  "template": "<span translate>myRecommendations</span>",
  "badge": "<span>{{ notifications }}</span>",
  "sref": "recommendation.list"
};

const { badge, ...anotherValue } = value;

console.log(anotherValue);

Or iterate over the object keys and get the properties which you want

const value = {
   "template": "<span translate>myRecommendations</span>",
   "badge": "<span>{{ notifications }}</span>",
   "sref": "recommendation.list"
};

const anotherValue = Object.keys(value).reduce((obj, key) => {

  if(key !== 'badge') {
    obj[key] = value[key]    ;
  }

  return obj;
}, {});

console.log(anotherValue);


问:
What is the difference between SocketAddress and InetAddress in Java
It's unclear what SocketAddres is designed for. As far as I see there is just one reasonable way to use it: through InetSocketAddress. It's confusing.</p>

答:
SocketAdress

This class represents a Socket Address with no protocol attachment. As an abstract class, it is meant to be subclassed with a specific, protocol dependent, implementation.

InetAdress

This class represents an Internet Protocol (IP) address.

Maybe you want to know about
InetSocketAddress

This class implements an IP Socket Address (IP address + port number) It can also be a pair (hostname + port number), in which case an attempt will be made to resolve the hostname. If resolution fails then the address is said to be unresolved but can still be used on some circumstances like connecting through a proxy.


问:
Creating artificially parsed arguments
My program "program.py" has the form:

```<code>if __name__=='__main__':
     args = parse_args()
     main_function(args)
</code>```

However, if I import program.py as a module and run program.main_function, how can I pass the parsed arguments structure as an argument to the main_function?

Here is the definition of the parse_args()

```<code> def parse_args():
     parser=argparse.ArgumentParser()
     parser.add_argument(...)
     args=parser.parse_args()
     return args
</code>```

答:
If we are talking about argparse.parse_args from the standard library, just pass the list of arguments explicitly.

For example, if you call your program from the command line with these arguments:

```<code>program --verbose --mode=3 file1 file2
</code>```

the shell splits the command line into five words, the program name and its four arguments. These are stored in sys.argv.

To achieve the same effect directly from Python:

```<code> args = parse_args(['--verbose', '--mode=3', 'file1' , 'file2'])
 main_function(args)
</code>```

UPDATE - parse_args modification:

```<code> def parse_args(arglist=None):
     parser=argparse.ArgumentParser()
     parser.add_argument(...)
     args=parser.parse_args(arglist)
     return args
</code>```

Title: Creating artificially parsed arguments

Body:
My program "program.py" has the form:

if __name__=='__main__':
     args = parse_args()
     main_function(args)

However, if I import program.py as a module and run program.main_function, how can I pass the parsed arguments structure as an argument to the main_function?

Here is the definition of the parse_args()

 def parse_args():
     parser=argparse.ArgumentParser()
     parser.add_argument(...)
     args=parser.parse_args()
     return args

Body:
If we are talking about argparse.parse_args from the standard library, just pass the list of arguments explicitly.

For example, if you call your program from the command line with these arguments:

program --verbose --mode=3 file1 file2

the shell splits the command line into five words, the program name and its four arguments. These are stored in sys.argv.

To achieve the same effect directly from Python:

 args = parse_args(['--verbose', '--mode=3', 'file1' , 'file2'])
 main_function(args)

UPDATE - parse_args modification:

 def parse_args(arglist=None):
     parser=argparse.ArgumentParser()
     parser.add_argument(...)
     args=parser.parse_args(arglist)
     return args


问:
UITextView text content doesn't start from the top
I have a long text coming from my JSON file but when I click the link from my UITableViewCell to go to my UIViewController page, the UITextView text loads the string content but it does not show the content from the beginning and I have to scroll up all the time.

What I need to do?

答:
Instead of setting content offset from viewDidLayoutSubviews you can write layoutIfNeeded from viewDidLoad to set the proper position of textview as below:

```<code>    self.textView.layoutIfNeeded()
    self.textView.setContentOffset(CGPoint.zero, animated: false)
</code>```

Cheers !!

Body:
Instead of setting content offset from viewDidLayoutSubviews you can write layoutIfNeeded from viewDidLoad to set the proper position of textview as below:

    self.textView.layoutIfNeeded()
    self.textView.setContentOffset(CGPoint.zero, animated: false)

Cheers !!


问:
Parsing JSON - Swift
I am using the following source code to retrieve some data from Google Maps:

```<code>import UIKit
import GoogleMaps
import GooglePlaces
import SwiftyJSON

class Place /*: NSObject*/ {
    let name: String

    init(diction:[String : Any])
    {
        let json = JSON(diction)
        name = json["name"].stringValue //as! String
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?&location=54.507514,-0.073603&radius=1000&name=Specsavers&name=Opticians&key=AIzaSyAcXLd8jotAyIOgKYqhYbL703BIibXkd-M"

       guard let url = URL(string: urlString) else {return}

        URLSession.shared.dataTask(with: url) {(data, response, error) in

            if let content = data {
                do {
                    let json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    if let results = json["results"] as? [[String : Any]] {
                        var places = [Place]()
                        for place in results {
                            print("HERE0: " place)
                            places.append(Place(diction: place))
                        }
                        print("HERE1:", places)
                    }
                    else {
                        print("return")
                    }

                }
                catch{

                }
            }
        }.resume()

    }
</code>```

But when I try to print places then I get the following response:

```<code>2017-11-13 11:16:56.887909+0000 Trial[3911:127944] [BoringSSL] Function boringssl_context_get_peer_sct_list: line 1757 received sct extension length is less than sct data length
</code>```

and I get this output from HERE1:

HERE1: [Trial.Place] (My xcode project is named Trial)

while from HERE0 I get properly the json file as it is.

Why I cannot retrieve properly the name of the store from Google Places?

答:
Your mistake is, places actually an Array of Place class. So when you print it out you should specify an index. Because of it is an array of class, after index you should type which property you want to see.

I refactored your code, you can use it.

Your class file

```<code>class Place /*: NSObject*/ {
let name: String

init(diction:[String : Any])
{
    self.name = diction["name"] as! String
}
}
</code>```

Your json parse

```<code> var places = [Place]() //do it outside of the viewDidload

 let urlString = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?&location=51.507514,-0.073603&radius=1000&name=Specsavers&name=Opticians&key=AIzaSyAcXLd8jotAyIOgKYqhYbL703BIibXkd-M")

    let session = URLSession.shared
    let task = session.dataTask(with: urlString!) { (data, response, err) in
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableLeaves) as! Dictionary<String,Any>
                if let results = json["results"] as? [[String:Any]] {
                    for place in results {
                        self.places.append(Place(diction: place))
                        print(self.places[0].name)
                    }
                    print(self.places[0].name)
                }
            }catch let err{
                print(err)
            }

        }
    }
    task.resume()
</code>```

Title: Parsing JSON - Swift

Body:
I am using the following source code to retrieve some data from Google Maps:

import UIKit
import GoogleMaps
import GooglePlaces
import SwiftyJSON

class Place /*: NSObject*/ {
    let name: String

    init(diction:[String : Any])
    {
        let json = JSON(diction)
        name = json["name"].stringValue //as! String
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?&location=54.507514,-0.073603&radius=1000&name=Specsavers&name=Opticians&key=AIzaSyAcXLd8jotAyIOgKYqhYbL703BIibXkd-M"

       guard let url = URL(string: urlString) else {return}

        URLSession.shared.dataTask(with: url) {(data, response, error) in

            if let content = data {
                do {
                    let json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    if let results = json["results"] as? [[String : Any]] {
                        var places = [Place]()
                        for place in results {
                            print("HERE0: " place)
                            places.append(Place(diction: place))
                        }
                        print("HERE1:", places)
                    }
                    else {
                        print("return")
                    }

                }
                catch{

                }
            }
        }.resume()

    }

But when I try to print places then I get the following response:

2017-11-13 11:16:56.887909+0000 Trial[3911:127944] [BoringSSL] Function boringssl_context_get_peer_sct_list: line 1757 received sct extension length is less than sct data length

and I get this output from HERE1:

HERE1: [Trial.Place] (My xcode project is named Trial)

while from HERE0 I get properly the json file as it is.

Why I cannot retrieve properly the name of the store from Google Places?

Body:
Your mistake is, places actually an Array of Place class. So when you print it out you should specify an index. Because of it is an array of class, after index you should type which property you want to see.

I refactored your code, you can use it.

Your class file

class Place /*: NSObject*/ {
let name: String

init(diction:[String : Any])
{
    self.name = diction["name"] as! String
}
}

Your json parse

 var places = [Place]() //do it outside of the viewDidload

 let urlString = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?&location=51.507514,-0.073603&radius=1000&name=Specsavers&name=Opticians&key=AIzaSyAcXLd8jotAyIOgKYqhYbL703BIibXkd-M")

    let session = URLSession.shared
    let task = session.dataTask(with: urlString!) { (data, response, err) in
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableLeaves) as! Dictionary<String,Any>
                if let results = json["results"] as? [[String:Any]] {
                    for place in results {
                        self.places.append(Place(diction: place))
                        print(self.places[0].name)
                    }
                    print(self.places[0].name)
                }
            }catch let err{
                print(err)
            }

        }
    }
    task.resume()


问:
Sql Joining 3 Tables Query for Loan Total Result
I have to get the total of Customer Loan from 3 tables the two tables are given loan to sum and the other subtract the paid amount and the tables have Customer ID in common. so far I can get the result only if the Customer ID exist in all tables but if it doesn't exist in one table I won't get Customer in my result. or I get NULL customer IDs when I anchor to the customer.

```<code>SELECT
  AS1.C_ID AS [Customer ID],
  ISNULL(AS1.OldCustomerLoan, 0) AS [Old Loan],
  ISNULL(AS2.NewGivenLoan, 0) AS [New Given Loan],
  ISNULL(AS3.LoanPaid, 0) AS [PaidLoanAmount],
  (ISNULL(AS1.OldCustomerLoan, 0) +
  ISNULL(AS2.NewGivenLoan, 0) -
  ISNULL(AS3.LoanPaid,0) ) AS Total
FROM
  Customer C
  LEFT OUTER JOIN
   (SELECT
       MOC.C_ID,
       SUM(MOC.Quantity) AS OldCustomerLoan
    FROM
       Money_On_Customer MOC (NOLOCK)
    GROUP BY
       MOC.C_ID) AS1
    ON c.C_Id = AS1.C_Id
   LEFT OUTER JOIN
(SELECT
       NGL.C_ID
       ,SUM(NGL.G_Take_Loan) AS NewGivenLoan
    FROM
       Given_Loan NGL
    GROUP BY
       NGL.C_ID) AS2
    ON c.C_Id = AS2.C_Id
LEFT OUTER JOIN
   (SELECT
       GLP.C_ID, SUM(GLP.G_P_Loan) AS LoanPaid
    FROM
       Given_Loan_Paid GLP
    GROUP BY
       GLP.C_ID ) AS3
ON c.C_Id = AS3.C_Id
</code>```

Here Is a picture of my two results:

When I get NULL Customer IDs

When I don't get All the Customers

答:
@Ab Bennett's answer is right,
because you should use your main(master) table's primary key column
if Customer ID is not available in as1 (Money_On_Customer) it will show null.
Hope you understand my explanation.

UPDATE:

and use following for getting customer id

```<code>COALESCE(c.C_Id, AS1.C_Id, AS2.C_Id)
</code>```

you will get first not null Customer ID

Body:
I have to get the total of Customer Loan from 3 tables the two tables are given loan to sum and the other subtract the paid amount and the tables have Customer ID in common. so far I can get the result only if the Customer ID exist in all tables but if it doesn't exist in one table I won't get Customer in my result. or I get NULL customer IDs when I anchor to the customer.

SELECT
  AS1.C_ID AS [Customer ID],
  ISNULL(AS1.OldCustomerLoan, 0) AS [Old Loan],
  ISNULL(AS2.NewGivenLoan, 0) AS [New Given Loan],
  ISNULL(AS3.LoanPaid, 0) AS [PaidLoanAmount],
  (ISNULL(AS1.OldCustomerLoan, 0) +
  ISNULL(AS2.NewGivenLoan, 0) -
  ISNULL(AS3.LoanPaid,0) ) AS Total
FROM
  Customer C
  LEFT OUTER JOIN
   (SELECT
       MOC.C_ID,
       SUM(MOC.Quantity) AS OldCustomerLoan
    FROM
       Money_On_Customer MOC (NOLOCK)
    GROUP BY
       MOC.C_ID) AS1
    ON c.C_Id = AS1.C_Id
   LEFT OUTER JOIN
(SELECT
       NGL.C_ID
       ,SUM(NGL.G_Take_Loan) AS NewGivenLoan
    FROM
       Given_Loan NGL
    GROUP BY
       NGL.C_ID) AS2
    ON c.C_Id = AS2.C_Id
LEFT OUTER JOIN
   (SELECT
       GLP.C_ID, SUM(GLP.G_P_Loan) AS LoanPaid
    FROM
       Given_Loan_Paid GLP
    GROUP BY
       GLP.C_ID ) AS3
ON c.C_Id = AS3.C_Id

Here Is a picture of my two results:

When I get NULL Customer IDs

When I don't get All the Customers

Body:
@Ab Bennett's answer is right,
because you should use your main(master) table's primary key column
if Customer ID is not available in as1 (Money_On_Customer) it will show null.
Hope you understand my explanation.

UPDATE:

and use following for getting customer id

COALESCE(c.C_Id, AS1.C_Id, AS2.C_Id)

you will get first not null Customer ID


问:
Get the duplicate entries from table mysql
I have the table structure as shown below. The database is MariaDB.

```<code>+-----------+----------+--------------+-----------------+
| id_object |   name   | value_double | value_timestamp |
+-----------+----------+--------------+-----------------+
|     1     | price    | 1589         |  null           |
|     1     | payment  | 1590         |  null           |
|     1     | date     | null         |  2012-04-17     |
|     2     | price    | 1589         |  null           |
|     2     | payment  | 1590         |  null           |
|     2     | date     | null         |  2012-04-17     |
|     3     | price    | 1589         |  null           |
|     3     | payment  | 1590         |  null           |
|     3     | date     | null         |  2012-09-25     |
|    ...    | ...      | ...          |  ..             |
+-----------+----------+--------------+-----------------+
</code>```

1) I need to get the duplicates by three entries: price & payment & date;

For example: the record with id_object=2 is duplicate because price, payment and date are the same as values of the record with id_object=1. Record with id_object = 3 is not the duplicate because the date is different (2012-09-25 != 2012-04-17)

2) I should remove the duplicates except one copy of them.

I thought to do three select operations and join each select on id_object. I can get the duplicates by one entry (price | payment | date). I faced the problem doing the joins

```<code>SELECT `id_object`,`name`,{P.`value_double` | P.`value_timestamp`}
FROM record P
INNER JOIN(
SELECT {value_double | value_timestamp}
FROM record
WHERE name = {required_entry}
GROUP BY {value_double | value_timestamp}
HAVING COUNT(id_object) > 1
)temp ON {P.value_double = temp.value_double | P.value_timestamp = temp.value_timestamp}
WHERE name = {required_entry}
</code>```

Can someone help and show the pure (better) solution?

答:
I would just group_concat() the values together and do the test that way:

```<code> select t.*
 from t join
      (select min(id_object) id_object
       from (select id_object,
                    group_concat(name, ':', coalesce(value_double, ''), ':', coalesce(value_timestamp, '') order by name) pairs
             from t
             where name in ('price', 'payment', 'date')
             group by id_object
            ) tt
        group by pairs
     ) tt
     on t.id_object = tt.id_object;
</code>```

To actually delete the ones that are not the minimum id for each group of related values:

```<code>delete t
    from t left join
         (select min(id) as id
          from (select id, group_concat(name, ':', coalesce(value_double, ''), ':', coalesce(value_timestamp, '' order by name) as pairs,
                from t
                where name in ('price', 'payment', 'date')
                group by id
               ) tt
          group by pairs
         ) tt
         on t.id = tt.id
    where tt.id is null;
</code>```

Body:
I have the table structure as shown below. The database is MariaDB.

+-----------+----------+--------------+-----------------+
| id_object |   name   | value_double | value_timestamp |
+-----------+----------+--------------+-----------------+
|     1     | price    | 1589         |  null           |
|     1     | payment  | 1590         |  null           |
|     1     | date     | null         |  2012-04-17     |
|     2     | price    | 1589         |  null           |
|     2     | payment  | 1590         |  null           |
|     2     | date     | null         |  2012-04-17     |
|     3     | price    | 1589         |  null           |
|     3     | payment  | 1590         |  null           |
|     3     | date     | null         |  2012-09-25     |
|    ...    | ...      | ...          |  ..             |
+-----------+----------+--------------+-----------------+

1) I need to get the duplicates by three entries: price & payment & date;

For example: the record with id_object=2 is duplicate because price, payment and date are the same as values of the record with id_object=1. Record with id_object = 3 is not the duplicate because the date is different (2012-09-25 != 2012-04-17)

2) I should remove the duplicates except one copy of them.

I thought to do three select operations and join each select on id_object. I can get the duplicates by one entry (price | payment | date). I faced the problem doing the joins

SELECT `id_object`,`name`,{P.`value_double` | P.`value_timestamp`}
FROM record P
INNER JOIN(
SELECT {value_double | value_timestamp}
FROM record
WHERE name = {required_entry}
GROUP BY {value_double | value_timestamp}
HAVING COUNT(id_object) > 1
)temp ON {P.value_double = temp.value_double | P.value_timestamp = temp.value_timestamp}
WHERE name = {required_entry}

Can someone help and show the pure (better) solution?

Body:
I would just group_concat() the values together and do the test that way:

 select t.*
 from t join
      (select min(id_object) id_object
       from (select id_object,
                    group_concat(name, ':', coalesce(value_double, ''), ':', coalesce(value_timestamp, '') order by name) pairs
             from t
             where name in ('price', 'payment', 'date')
             group by id_object
            ) tt
        group by pairs
     ) tt
     on t.id_object = tt.id_object;

To actually delete the ones that are not the minimum id for each group of related values:

delete t
    from t left join
         (select min(id) as id
          from (select id, group_concat(name, ':', coalesce(value_double, ''), ':', coalesce(value_timestamp, '' order by name) as pairs,
                from t
                where name in ('price', 'payment', 'date')
                group by id
               ) tt
          group by pairs
         ) tt
         on t.id = tt.id
    where tt.id is null;


问:
How to apply a custom MessageBodyWriter to lists of objects?
In a Dropwizard web service I want to return objects of class Test in a database using following custom MessageBodyWriter.

```<code> @Provider
 @Produces("application/Test")
 public class TestMarshaller implements MessageBodyWriter<Test>{
     public long getSize(Test obj, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
         return -1;
     }
     public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
         return type == Test.class;
     }
     public void writeTo(Test obj, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> httpHeaders, OutputStream outputStream) throws IOException, WebApplicationException {
        httpHeaders.add("Content-Type", "text/plain; charset=UTF-8");
        StringBuffer str = new StringBuffer();
        str.append(obj.getData());
        outputStream.write(str.toString().getBytes());
     }
}
</code>```

This works fine for single objects with the following method

```<code>@GET
@Produces("application/Test")
@Path("/{ID}")
public Test getTest(@PathParam(value = "ID") LongParam ID) {
    Test result = Test.findInDB(ID.get());
    return result;
}
</code>```

Now I want to use the same MessageBodyWriter for a list of elements.

```<code>@GET
@Produces("application/Test")
@Path("/{ID}")
public List<Test> getTest(@PathParam(value = "ID") String IDs) {
    List<Test> listTest = Test.findMultiInDB(IDs);
    return listTest;
}
</code>```

That resulted in the error

org.glassfish.jersey.message.internal.WriterInterceptorExecutor: MessageBodyWriter not found for media type=application/Test, type=class java.util.ArrayList, genericType=java.util.List.

A search suggested the usage of GenericEntity.

```<code>@GET
@Produces("application/Test")
@Path("/{ID}")
public Response getTest(@PathParam(value = "ID") String IDs) {
    List<Test> listTest = Test.findMultiInDB(IDs);
    GenericEntity<List<Test>> result = new GenericEntity<List<Test>>(listTest) {};
    return Response.ok(result).build();
}
</code>```

Unfortunately it resulted in the exact same error as above.

My question is what do I need to change to make it work or is another MessageBodyWriter necessary that deals with the lists?

答: The error message is clear, Jersey looks for a MessageBodyWriter with type java.util.List, but finds only MessageBodyWriter<Test>, so either create a new one for List MessageBodyWriter<java.util.List> or use Object and use if else on Object class.

Body:
In a Dropwizard web service I want to return objects of class Test in a database using following custom MessageBodyWriter.

 @Provider
 @Produces("application/Test")
 public class TestMarshaller implements MessageBodyWriter<Test>{
     public long getSize(Test obj, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
         return -1;
     }
     public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
         return type == Test.class;
     }
     public void writeTo(Test obj, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> httpHeaders, OutputStream outputStream) throws IOException, WebApplicationException {
        httpHeaders.add("Content-Type", "text/plain; charset=UTF-8");
        StringBuffer str = new StringBuffer();
        str.append(obj.getData());
        outputStream.write(str.toString().getBytes());
     }
}

This works fine for single objects with the following method

@GET
@Produces("application/Test")
@Path("/{ID}")
public Test getTest(@PathParam(value = "ID") LongParam ID) {
    Test result = Test.findInDB(ID.get());
    return result;
}

Now I want to use the same MessageBodyWriter for a list of elements.

@GET
@Produces("application/Test")
@Path("/{ID}")
public List<Test> getTest(@PathParam(value = "ID") String IDs) {
    List<Test> listTest = Test.findMultiInDB(IDs);
    return listTest;
}

That resulted in the error

org.glassfish.jersey.message.internal.WriterInterceptorExecutor: MessageBodyWriter not found for media type=application/Test, type=class java.util.ArrayList, genericType=java.util.List.

A search suggested the usage of GenericEntity.

@GET
@Produces("application/Test")
@Path("/{ID}")
public Response getTest(@PathParam(value = "ID") String IDs) {
    List<Test> listTest = Test.findMultiInDB(IDs);
    GenericEntity<List<Test>> result = new GenericEntity<List<Test>>(listTest) {};
    return Response.ok(result).build();
}

Unfortunately it resulted in the exact same error as above.

My question is what do I need to change to make it work or is another MessageBodyWriter necessary that deals with the lists?


问:
Missing locale data for the locale "ru" Angular 5
I updated Angular to version 5 and get this error

It seems to me the error with pipe in this line

{{ event.date | date:"yyyy.MM.dd"}}
.

Anybody knows how to fix this?

答:
It seems you don't update your pipe since breacking change of angular 5
see: https://github.com/angular/angular/blob/master/CHANGELOG.md

by default Angular now only contains locale data for the language
en-US, if you set the value of LOCALE_ID to another locale, you will
have to import new locale data for this language because we don't use
the intl API anymore.

all i18n pipes now have an additional last parameter locale which allows you to use a specific locale instead of the one defined in the token LOCALE_ID (whose default value is en-US).

the predefined formats (short, shortTime, shortDate, medium, ...) now use the patterns given by CLDR (like it was in AngularJS) instead of the ones from the intl API. You might notice some changes, e.g. shortDate will be 8/15/17 instead of 8/15/2017 for en-US.

the narrow version of eras is now GGGGG instead of G, the format G is now similar to GG and GGG.

the narrow version of months is now MMMMM instead of L, the format L is now the short standalone version of months.

the narrow version of the week day is now EEEEE instead of E, the format E is now similar to EE and EEE.

the timezone z will now fallback to O and output GMT+1 instead of the complete zone name (e.g. Pacific Standard Time), this is because the quantity of data required to have all the zone names in all of the existing locales is too big.

the timezone Z will now output the ISO8601 basic format, e.g. +0100, you should now use ZZZZ to get GMT+01:00.

You should change your date pipe

Also you need to provide your language in app.module like this:


问:
Change CONFIG [CLIENT SIDE] in Tampermonkey
CONFIG.PNG <--

How to change the Config in Tampermonkey if i change it there it works but i want to do it in Tampermonkey does that work and how?

答:
You probably have two independent problems: a) clicking the button and b) repeating the action. I am not very sure by reading your question, but you might find window.setInterval useful for the second.

https://www.w3schools.com/jsref/met_win_setinterval.asp

As for the onlick event issues, you have a ton of interesting answers already there in SO, e.g. How to Call a JS function using OnClick event

Hope that does help.


问:
Multi step transaction in hibernate
Am facing few issues with multi step transction in hibernate. This is what I am doing.

One of my DAO methods

Creates a new record in Table A and retrieves the Oracle generated Primary key.

Updates a row in Table B with the Primary key retrieved in step 1

The code looks something like this:

```<code>@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public Object myDAOMethos(...){
    ....
    getHibernateTemplate().execute(
new HibernateCallback<Long>() {
 public Long doInHibernate(Session session)
   throws HibernateException, SQLException {
  // Create a new record in table A
  session.save(objA);

  final long pKey = objA.getId();

  // Update the row in table B
  org.hibernate.Query query = session
      .getNamedQuery("updateBQuery").setLong("idB",pKey...
   query.executeUpdate();
   }
  }
  return true;
 }
});
}
</code>```

The method is bound under a transction.

My issue:
Everything works fine when I run this code on tomcat. But when i try to exeute a junit test case for this, the update on table B never takes place. Although I can see the update SQL on the console output (hibernate.show_sql=true). No exceptions either! just the insert takes place and thats it.

Not sure what is happening here! any ideas!?

regards,
-J

答:
A few things could be wrong

It is suspicious that you are updated a foreign key to your first entity manually; hibernate should do that for you if you set up your relationships correctly.

How is your test class set up?  Are you rolling the data back at some point so the tests are transparent?  What I am getting at is, if you see the the sql, but then in your test you don't see the data, you are trying to access your data at the wrong time to test -- either the data has not been committed, or the data has already been rolled back (if you are rolling back).  One thing you might want to try is turning the tx off, then running the test.  Note you will have to clean up the data manually, but it should indicate whether the tx configuration in the test is the problem.

Spring has some base test classes available that manage transactions and rolling data back for you....

ContentLicense: CC BY-SA 2.5

Title: Multi step transaction in hibernate

Body:
Am facing few issues with multi step transction in hibernate. This is what I am doing.

One of my DAO methods

Creates a new record in Table A and retrieves the Oracle generated Primary key.

Updates a row in Table B with the Primary key retrieved in step 1

The code looks something like this:

@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public Object myDAOMethos(...){
    ....
    getHibernateTemplate().execute(
new HibernateCallback<Long>() {
 public Long doInHibernate(Session session)
   throws HibernateException, SQLException {
  // Create a new record in table A
  session.save(objA);

  final long pKey = objA.getId();

  // Update the row in table B
  org.hibernate.Query query = session
      .getNamedQuery("updateBQuery").setLong("idB",pKey...
   query.executeUpdate();
   }
  }
  return true;
 }
});
}

The method is bound under a transction.

My issue:
Everything works fine when I run this code on tomcat. But when i try to exeute a junit test case for this, the update on table B never takes place. Although I can see the update SQL on the console output (hibernate.show_sql=true). No exceptions either! just the insert takes place and thats it.

Not sure what is happening here! any ideas!?

regards,
-J


问:
VBA run time error 438
I am trying to write a code to open a PPTX file from excel VBA and update links in ppt.

below is the code that i have got but while the code is trying to update links i am getting the

Run time error 438 Object does not support this property or method

```<code>Sub kunal()

Dim PPObj As Object

Set PPObj = CreateObject("PowerPoint.application")

With PPObj
    .Presentations.Add

    .Presentations.Open Filename:="Y:\Desktop\Month End\One_Shot\Template AVP Report Package\ABD-OME SDeeson.pptx"

    .Visible = True
    .UpdateLinks
    .Presentation.Save

    .Quit
    Set PPObj = Nothing
End With

End Sub
</code>```

答:
First, not sure why you need .Presentations.Add if at the following line you are opening an existing Presentation.

Second, the line of .UpdateLinks is a property of the Presentation, not the PowerPoint.Application.

Code

```<code>Option Explicit

Sub kunal()

Dim ppApp As Object
Dim ppPres As Object

Set ppApp = CreateObject("PowerPoint.application")

With ppApp
    .Visible = True

'    .Presentations.Add ' <-- not sure why you need to open a new Presentation ?
    Set ppPres = .Presentations.Open(Filename:="Y:\Desktop\Month End\One_Shot\Template AVP Report Package\ABD-OME SDeeson.pptx")

    ppPres.UpdateLinks
    ppPres.Save
    ppPres.Close

    .Quit
End With

Set ppPres = Nothing
Set ppApp = Nothing

End Sub
</code>```

Title: VBA run time error 438

Body:
I am trying to write a code to open a PPTX file from excel VBA and update links in ppt.

below is the code that i have got but while the code is trying to update links i am getting the

Run time error 438 Object does not support this property or method

Sub kunal()

Dim PPObj As Object

Set PPObj = CreateObject("PowerPoint.application")

With PPObj
    .Presentations.Add

    .Presentations.Open Filename:="Y:\Desktop\Month End\One_Shot\Template AVP Report Package\ABD-OME SDeeson.pptx"

    .Visible = True
    .UpdateLinks
    .Presentation.Save

    .Quit
    Set PPObj = Nothing
End With

End Sub

Body:
First, not sure why you need .Presentations.Add if at the following line you are opening an existing Presentation.

Second, the line of .UpdateLinks is a property of the Presentation, not the PowerPoint.Application.

Code

Option Explicit

Sub kunal()

Dim ppApp As Object
Dim ppPres As Object

Set ppApp = CreateObject("PowerPoint.application")

With ppApp
    .Visible = True

'    .Presentations.Add ' <-- not sure why you need to open a new Presentation ?
    Set ppPres = .Presentations.Open(Filename:="Y:\Desktop\Month End\One_Shot\Template AVP Report Package\ABD-OME SDeeson.pptx")

    ppPres.UpdateLinks
    ppPres.Save
    ppPres.Close

    .Quit
End With

Set ppPres = Nothing
Set ppApp = Nothing

End Sub


问:
How to disable a constraint in Oracle with select statement as constraint name
I try to disable a constraint attached to a column in a table

```<code>ALTER TABLE
   ADV_TEST_COURSE_CREDIT
DISABLE constraint

name = (SELECT
    constraint_name
from
    user_constraints natural join
    user_cons_columns
where
    table_name = 'ADV_TEST_COURSE_CREDIT' AND
    column_name = 'SEQUENCE_NUMBER' AND
    constraint_type = 'C');
</code>```

I try the statement above. It is not working. Any idea on how to make it work.

Table ADV_TEST_COURSE_CREDIT exists in dev, UAT, Production, so the constraint name is different, but it is all attached a column called SEQUENCE_NUMBER

答:
You need dynamic sql and some plsql:</p>

```<code>declare name varchar2(200);
begin
SELECT
    constraint_name
into name
from
    user_constraints natural join
    user_cons_columns
where
    table_name = 'ADV_TEST_COURSE_CREDIT' AND
    column_name = 'SEQUENCE_NUMBER' AND
    constraint_type = 'C');
execute immediate 'ALTER TABLE  ADV_TEST_COURSE_CREDIT DISABLE CONSTRAINT :1' using name;
end;
</code>```

Body:
I try to disable a constraint attached to a column in a table

ALTER TABLE
   ADV_TEST_COURSE_CREDIT
DISABLE constraint

name = (SELECT
    constraint_name
from
    user_constraints natural join
    user_cons_columns
where
    table_name = 'ADV_TEST_COURSE_CREDIT' AND
    column_name = 'SEQUENCE_NUMBER' AND
    constraint_type = 'C');

I try the statement above. It is not working. Any idea on how to make it work.

Table ADV_TEST_COURSE_CREDIT exists in dev, UAT, Production, so the constraint name is different, but it is all attached a column called SEQUENCE_NUMBER

Body:
You need dynamic sql and some plsql:

declare name varchar2(200);
begin
SELECT
    constraint_name
into name
from
    user_constraints natural join
    user_cons_columns
where
    table_name = 'ADV_TEST_COURSE_CREDIT' AND
    column_name = 'SEQUENCE_NUMBER' AND
    constraint_type = 'C');
execute immediate 'ALTER TABLE  ADV_TEST_COURSE_CREDIT DISABLE CONSTRAINT :1' using name;
end;


答:
You can't have two variables with the same name. However, if you don't want to mutate your original object and still use spread syntax, you might consider naming your new object differently, e.g. value2.

const value = {
  "template": "myRecommendations",
  "badge": "{{ notifications }}",
  "sref": "recommendation.list"
};

const { badge, ...value2 } = value;
    // ^^^^^^ prop you want NOT to include in your new object
console.log(value2);```

Title: JavaScript/ES2015 - Keep all the properties of an object except one whit Rest/Spread operators

Body:
I have this object :

const value = {
  "template": "myRecommendations",
  "badge": "{{ notifications }}",
  "sref": "recommendation.list"
}

I want to use the Rest / Spread operators to create another object with the same name (value) with all properties except the badge property

Body:
You can't have two variables with the same name. However, if you don't want to mutate your original object and still use spread syntax, you might consider naming your new object differently, e.g. value2.

const value = {
  "template": "<span translate>myRecommendations</span>",
  "badge": "<span>{{ notifications }}</span>",
  "sref": "recommendation.list"
};

const { badge, ...value2 } = value;
    // ^^^^^^ prop you want NOT to include in your new object
console.log(value2);


答:
Here you go:

const value = {
  "template": "myRecommendations",
  "badge": "{{ notifications }}",
  "sref": "recommendation.list"
}

const { badge, ...updatedValue } = value;
console.log(updatedValue)```

Body:
Here you go:

const value = {
  "template": "<span translate>myRecommendations</span>",
  "badge": "<span>{{ notifications }}</span>",
  "sref": "recommendation.list"
}

const { badge, ...updatedValue } = value;
console.log(updatedValue)


问:
I want to use jquery to make the option value element able to show some stuff and exclude other
I try to show some portfolio stuff by using the select attribute, but nothing happens. Basically, it is sorting and displaying.

Here is my code:

```<code>  <div id="selection">
        <span>Projets: </span>
        <select name="" id="options">
            <option class="option" value="1" data-filter="all">All</option>
            <option class="option" value="2" data-filter="blab">blab</option>
            <option class="option" value="3" data-filter="blob">blob</option>
            <option class="option" value="4" data-filter="blib">blib</option>
            <option class="option" value="5" data-filter="bleb">bleb</option>
            <option class="option" value="6" data-filter="bldb">bldb</option>
        </select>
    </div>

<div class="box filter website">Website</div>
<div class="box filter graphics">Graphics</div>
<div class="box filter psd">PSD</div>
<div class="box filter logo">Logo</div>
<div class="box filter application">Application</div>
<div class="box filter website">Website</div>
<div class="box filter graphics">Graphics</div>
<div class="box filter psd">PSD</div>
<div class="box filter logo">Logo</div>
<div class="box filter application">Application</div>
    <div class="box filter website">Website</div>
    <div class="box filter graphics">Graphics</div>
    <div class="box filter psd">PSD</div>
    <div class="box filter logo">Logo</div>
    <div class="box filter application">Application</div>
    <div class="box filter psd">PSD</div>
</code>```

The jQuery part:

```<code>$(document).ready(function(){
        $("selection").click(function(){
            var value = $(this).attr("data-filter");

            if(value == "all"){
                $(".option").show("1000");
            }
            else {
                $(".option").not("."+value).hide("1000");
                $(".option").filter("."+value).show("1000");
            }
        })
    });
</code>```

What have I done wrong?

Thanks,
C.

答:
selection  is div and click event will be fired when it is clicked, better option is to implement change event of

in your var value = $(this).attr("data-filter"); syntax this will be div element which has not attribute which you need

I am not sure what you are trying to do but you can get value of selected option like below

```<code>$(document).ready(function(){
        $("#options").change(function(){
            var value = $("#options").find(":selected");
            value = value.attr("data-filter");
            if(value == "all"){
                // Do Your Stuff
            }
            else {
                // Do Your Stuff
            }
        })
    });
</code>```

Body:
I try to show some portfolio stuff by using the select attribute, but nothing happens. Basically, it is sorting and displaying.

Here is my code:

        Projets:
        <select name="" id="options">
            <option class="option" value="1" data-filter="all">All</option>
            <option class="option" value="2" data-filter="blab">blab</option>
            <option class="option" value="3" data-filter="blob">blob</option>
            <option class="option" value="4" data-filter="blib">blib</option>
            <option class="option" value="5" data-filter="bleb">bleb</option>
            <option class="option" value="6" data-filter="bldb">bldb</option>
        </select>

Website

Graphics

PSD

Logo

Application

Website

Graphics

PSD

Logo

Application

Website

Graphics

PSD

Logo

Application

PSD

The jQuery part:

$(document).ready(function(){
        $("selection").click(function(){
            var value = $(this).attr("data-filter");

            if(value == "all"){
                $(".option").show("1000");
            }
            else {
                $(".option").not("."+value).hide("1000");
                $(".option").filter("."+value).show("1000");
            }
        })
    });

What have I done wrong?

Thanks,
C.

Body:
selection  is div and click event will be fired when it is clicked, better option is to implement change event of

in your var value = $(this).attr("data-filter"); syntax this will be div element which has not attribute which you need

I am not sure what you are trying to do but you can get value of selected option like below

$(document).ready(function(){
        $("#options").change(function(){
            var value = $("#options").find(":selected");
            value = value.attr("data-filter");
            if(value == "all"){
                // Do Your Stuff
            }
            else {
                // Do Your Stuff
            }
        })
    });


问:
How to get the sum for a float numbers within a text file?
I'm newbie to python, I'm doing this exercise I have to extract numbers from specific lines within a file.

The Task is to Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence:    0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below.
You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.

I have don't so far with the code and I need to get the total and the count to calculate the average :

http://i.gyazo.com/31373bdbc83c7f421236bc94d323d653.png

I should get this average result: 0.750718518519

```<code>#Use the file name mbox-short.txt as the file name
fname = raw_input("Enter file name: ")
if len(fname) == 0:
    fname = 'file.txt'
fh = open(fname)
count = 0
total = 0
for line in fh:
    line = line.rstrip()
    if not line.startswith("For example    0.6545") : continue
    x = line[20:28]
    xx = float(x)
    count = count + 1

    print xx

    #average = total/count

    #print average

print "Done"
</code>```

答:
You should try this:

```<code>fh = open("mbox-short.txt",'r')

count=0
total=0
result=0

for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") :continue
    count=count+1
    num=float(line[21:])
    total=num+total

result=total/count
print("Average spam confidence:",result)
</code>```

This is the logic. Understand the three variables, num, count, total and result. Its just a simple code!

Body:
I'm newbie to python, I'm doing this exercise I have to extract numbers from specific lines within a file.

The Task is to Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence:    0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below.
You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.

I have don't so far with the code and I need to get the total and the count to calculate the average :

http://i.gyazo.com/31373bdbc83c7f421236bc94d323d653.png

I should get this average result: 0.750718518519

#Use the file name mbox-short.txt as the file name
fname = raw_input("Enter file name: ")
if len(fname) == 0:
    fname = 'file.txt'
fh = open(fname)
count = 0
total = 0
for line in fh:
    line = line.rstrip()
    if not line.startswith("For example    0.6545") : continue
    x = line[20:28]
    xx = float(x)
    count = count + 1

    print xx

    #average = total/count

    #print average

print "Done"

Body:
You should try this:

fh = open("mbox-short.txt",'r')

count=0
total=0
result=0

for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") :continue
    count=count+1
    num=float(line[21:])
    total=num+total

result=total/count
print("Average spam confidence:",result)

This is the logic. Understand the three variables, num, count, total and result. Its just a simple code!


问:
Fetching data using Http in angular 2
I am trying to create a simple application in angular 2 to fetch data using Http.
I created two classes employee-list and employee-detail and a service with the name
employee.service.ts which makes an Http call and recieve the observable and map it.

I also create a folder in src with the name apidata in which i kept my data to be fetched
in the employeedata.json file.

And later subscribe to the observable and assign the data to local variable in the view.

My code is being compiled successfully .But iam unable to fetch data.

Below shown is my code snippets

index.html

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Employee</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

    <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>
<body>
  <app-root>Loading.....</app-root>
</body>
</html>
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Injectable } from '@angular/core';
import { HttpModule } from '@angular/http';
import { Http, Response} from '@angular/http';

import { AppComponent } from './app.component';
import { EmployeeListComponent } from './employee-list.component';
import { EmployeeDetailComponent } from './employee-detail.component';
import { EmployeeService } from './employee.service';

@NgModule({
  declarations: [
    AppComponent,
    EmployeeListComponent,
    EmployeeDetailComponent
  ],

  imports: [ BrowserModule, HttpModule ],

  providers: [EmployeeService],

  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';
import { EmployeeService } from './employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',

  providers: [EmployeeService]

})
export class AppComponent {
  title = 'app';
}
</code>```

app.component.html

```<code><!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:justify-all;">
  <h3>
    Welcome to {{title}}!
  </h3>
 <h4> Random Company</h4>
  <h4> ...........</h4>

  <employee-list></employee-list>
  <employee-detail></employee-detail>
</code>```

employee-list.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { EmployeeService } from './employee.service';

@Component({
    selector: 'employee-list',
    template: `<h4>Employee List</h4>'
                <ul *ngFor=" let employee of employees ">
                <li>{{employee.name}}</li>
                </ul>`
})

export class EmployeeListComponent implements OnInit{
employees = [];

constructor(private _employeeService:EmployeeService){}
ngOnInit(){
this._employeeService.getEmployees()
.subscribe(resEmployeeData => this.employees = resEmployeeData);
}
}
</code>```

employee-detail.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { EmployeeService } from './employee.service';

@Component({
    selector: 'employee-detail',
    template: `<h4>Employee Details</h4>'
                <ul *ngFor=" let employee of employees ">
                <li>{{employee.id}}.{{employee.name}}-{{employee.gender}}</li>
                </ul>`
})

export class EmployeeDetailComponent implements OnInit{
employees = [];

constructor(private _employeeService:EmployeeService){}
ngOnInit(){
this.employees = this._employeeService.getEmployees();
}
}
</code>```

employee.service.ts

```<code>import { Injectable } from '@angular/core';
import { Http, Response} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class EmployeeService {

private _url: string = "apidata/employeedata.json"

constructor(private _http: Http){}

    getEmployees(){
    return this._http.get(this._url)
    .map((response:Response) => response.json() );
}}
</code>```

Can anybody please let me know what is that i am missing in my application.
 Why my application isn't fetching data ?

答:
I think you must subscribe to observable which is return from your service.
You can do this in your component (observable.subscribe()) or in your template:

employee-detail.component.ts

```<code><ul *ngFor=" let employee of employees | async">
</code>```

Title: Fetching data using Http in angular 2

Body:
I am trying to create a simple application in angular 2 to fetch data using Http.
I created two classes employee-list and employee-detail and a service with the name
employee.service.ts which makes an Http call and recieve the observable and map it.

I also create a folder in src with the name apidata in which i kept my data to be fetched
in the employeedata.json file.

And later subscribe to the observable and assign the data to local variable in the view.

My code is being compiled successfully .But iam unable to fetch data.

Below shown is my code snippets

index.html

<!doctype html>

  <meta charset="utf-8">
  <title>Employee</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <app-root>Loading.....</app-root>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Injectable } from '@angular/core';
import { HttpModule } from '@angular/http';
import { Http, Response} from '@angular/http';

import { AppComponent } from './app.component';
import { EmployeeListComponent } from './employee-list.component';
import { EmployeeDetailComponent } from './employee-detail.component';
import { EmployeeService } from './employee.service';

@NgModule({
  declarations: [
    AppComponent,
    EmployeeListComponent,
    EmployeeDetailComponent
  ],

  imports: [ BrowserModule, HttpModule ],

  providers: [EmployeeService],

  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { EmployeeService } from './employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',

  providers: [EmployeeService]

})
export class AppComponent {
  title = 'app';
}

app.component.html

    Welcome to {{title}}!

 Random Company

 ...........

  <employee-list></employee-list>
  <employee-detail></employee-detail>

employee-list.component.ts

import { Component, OnInit } from '@angular/core';
import { EmployeeService } from './employee.service';

@Component({
    selector: 'employee-list',
    template: `
Employee List
'

{{employee.name}}

`
})

export class EmployeeListComponent implements OnInit{
employees = [];

constructor(private _employeeService:EmployeeService){}
ngOnInit(){
this._employeeService.getEmployees()
.subscribe(resEmployeeData => this.employees = resEmployeeData);
}
}

employee-detail.component.ts

import { Component, OnInit } from '@angular/core';
import { EmployeeService } from './employee.service';

@Component({
    selector: 'employee-detail',
    template: `
Employee Details
'

{{employee.id}}.{{employee.name}}-{{employee.gender}}

`
})

export class EmployeeDetailComponent implements OnInit{
employees = [];

constructor(private _employeeService:EmployeeService){}
ngOnInit(){
this.employees = this._employeeService.getEmployees();
}
}

employee.service.ts

import { Injectable } from '@angular/core';
import { Http, Response} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class EmployeeService {

private _url: string = "apidata/employeedata.json"

constructor(private _http: Http){}

    getEmployees(){
    return this._http.get(this._url)
    .map((response:Response) => response.json() );
}}

Can anybody please let me know what is that i am missing in my application.
 Why my application isn't fetching data ?

Body:
I think you must subscribe to observable which is return from your service.
You can do this in your component (observable.subscribe()) or in your template:

employee-detail.component.ts

<ul *ngFor=" let employee of employees | async">


问:
Eclipse > git - what is Assume Valid?
Looking through Eclipse's Label Decorations for Git, I see one with a tick that says assume-valid.txt.

What is Assume Valid?

答:
assume-valid - The resource has the "assume unchanged" flag. This means that Git stops checking the working tree files for possible modifications, so you need to manually unset the bit to tell Git when you change the working tree file. This setting can be switched on with the menu action Team->Assume unchanged (or on the command line with git update-index --assume-unchanged).

Check out more at https://wiki.eclipse.org/EGit/User_Guide/State

Title: Eclipse > git - what is Assume Valid?


问:
How to run Python test case with Appium?
I've created simple test case using Python (in PyCharm editor) which should click on Join/Login button on iOS app, but it doesn't work. Here is the code:

```<code>from appium import webdriver
import unittest
import os

class LoginTests(unittest.TestCase):
    def setUp(self):
        desired_caps = {}
        desired_caps['platformName'] = 'iOS'
        desired_caps['platformVersion'] = '11.0'
        desired_caps['deviceName'] = 'iPhone Simulator' # Run on simulator
        desired_caps['bundleId'] = 'com.matchbook.MatchbookApp'
        desired_caps['app'] = os.path.abspath('/Users/majdukovic/Library/Developer/Xcode/DerivedData/MatchBook-bgvchkbwrithuaegnjgpoffewdag/Build/Products/Debug-iphonesimulator/MatchBook.app') # Path to .app
        self.wd = webdriver.Remote('http://0.0.0.0:4723/wd/hub', desired_caps)
        self.wd.implicitly_wait(60)
        loginButton = self.wd.find_element_by_id("JOIN/LOGIN") # Button ID
        self.assertTrue(loginButton.is_displayed())
        loginButton.click()

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(LoginTests)
    unittest.TextTestRunner(verbosity=2).run(suite)
</code>```

If I run this test case it returns:
"Ran 0 tests in 0.000s

OK"

Appium server is already running and app is opened. In PyCharm Preferences I've selected py.test as default test runner.

Details of my setup:

macOS - HighSierra v10.13

Appium desktop app - v1.2.6

Python - v2.7.10

xCode - v9.0.1

Simulator - iPhone 8, iOS v11.0

答:
I'm still not sure what is the problem, I tried a lot of things, but it won't work from Pycharm , so I've written code in Atom editor and run it from Terminal with command:
    "python -m py.test name_of_test.py -s" and it works.</p>

Body:
I've created simple test case using Python (in PyCharm editor) which should click on Join/Login button on iOS app, but it doesn't work. Here is the code:

from appium import webdriver
import unittest
import os

class LoginTests(unittest.TestCase):
    def setUp(self):
        desired_caps = {}
        desired_caps['platformName'] = 'iOS'
        desired_caps['platformVersion'] = '11.0'
        desired_caps['deviceName'] = 'iPhone Simulator' # Run on simulator
        desired_caps['bundleId'] = 'com.matchbook.MatchbookApp'
        desired_caps['app'] = os.path.abspath('/Users/majdukovic/Library/Developer/Xcode/DerivedData/MatchBook-bgvchkbwrithuaegnjgpoffewdag/Build/Products/Debug-iphonesimulator/MatchBook.app') # Path to .app
        self.wd = webdriver.Remote('http://0.0.0.0:4723/wd/hub', desired_caps)
        self.wd.implicitly_wait(60)
        loginButton = self.wd.find_element_by_id("JOIN/LOGIN") # Button ID
        self.assertTrue(loginButton.is_displayed())
        loginButton.click()

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(LoginTests)
    unittest.TextTestRunner(verbosity=2).run(suite)

If I run this test case it returns:
"Ran 0 tests in 0.000s

OK"

Appium server is already running and app is opened. In PyCharm Preferences I've selected py.test as default test runner.

Details of my setup:

macOS - HighSierra v10.13

Appium desktop app - v1.2.6

Python - v2.7.10

xCode - v9.0.1

Simulator - iPhone 8, iOS v11.0


问:
Django self-recursive foreignkey filter query for all childs
I have this model with a self referencing Foreign Key relation:

```<code>class Person(TimeStampedModel):
    name = models.CharField(max_length=32)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
</code>```

Now I want to get all the multi level children for a person. How do I write a Django query for it? It needs to behave like recursive function.

答:
You can always add a recursive function to your model:

EDIT: Corrected according to SeomGi Han

```<code>def get_all_children(self, include_self=True):
    r = []
    if include_self:
        r.append(self)
    for c in Person.objects.filter(parent=self):
        _r = c.get_all_children(include_self=True)
        if 0 < len(_r):
            r.extend(_r)
    return r
</code>```

(Don't use this if you have a lot of recursion or data ...)

Still recommending mptt as suggested by errx.

EDIT: 2021 since this answer is still getting attention :/

Use django-tree-queries instead!

Body:
I have this model with a self referencing Foreign Key relation:

class Person(TimeStampedModel):
    name = models.CharField(max_length=32)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children')

Now I want to get all the multi level children for a person. How do I write a Django query for it? It needs to behave like recursive function.

Body:
You can always add a recursive function to your model:

EDIT: Corrected according to SeomGi Han

def get_all_children(self, include_self=True):
    r = []
    if include_self:
        r.append(self)
    for c in Person.objects.filter(parent=self):
        _r = c.get_all_children(include_self=True)
        if 0 < len(_r):
            r.extend(_r)
    return r

(Don't use this if you have a lot of recursion or data ...)

Still recommending mptt as suggested by errx.

EDIT: 2021 since this answer is still getting attention :/

Use django-tree-queries instead!

ContentLicense: CC BY-SA 4.0


问:
Disable remotely downloading webpages using curl/wget
I need to disable remotely downloading my web pages using curl/wget.

I want to disable curl -vv http://www.example.com
and I need to get a result like this

**

Rebuilt URL to: http://www.example.com/    Trying 12.34.56.78...
TCP_NODELAY set  Connected to www.example.com (12.34.56.78) port 80
(#0)  GET / HTTP/1.1  Host: www.example.com  User-Agent: curl/7.53.1
Accept: /    HTTP/1.1 301 Moved Permanently  Server: AkamaiGHost
Content-Length: 0  Location: http://www.example.com/  Date: Mon, 13
Nov 2017 05:52:50 GMT  Connection: keep-alive   Connection #0 to host
www.example.com left intact

**

I am using Apache, Using Cloudflare.
Please help me

答:
You can disable wget and curl with the rules below:

```<code>RewriteCond %{HTTP_USER_AGENT} ^pycurl [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Wget [NC,OR]
</code>```

Just add them to .htaccess.

Body:
You can disable wget and curl with the rules below:

RewriteCond %{HTTP_USER_AGENT} ^pycurl [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Wget [NC,OR]

Just add them to .htaccess.


问:
How to configure SSL certificates with Charles Web Proxy and the latest Android Emulator on Windows?
I would like to use Charles web proxy to work with the Android emulator in Windows.  I've successfully set up charles and have started the emulator with the command line:

```<code>emulator -http-proxy 127.0.0.1:8888 @NexusOne
</code>```

I can see traffic coming from the android emulator in Charles, but the problem is that I'm developing against a live API which uses SSL and I'm not sure how to configure Charles to let me play about the the data which is sent and received.  I'm aware of two areas where SSL is set up in Charles (Proxy -> Proxy Settings -> SSL and Proxy -> Client SSL Certificates) but I can't find any decent documentation which has let me do what I want to do.  Has anyone experience with Charles, or certificates in general, who can explain how to achieve this.  Maybe a primer on certificates would be good too, as I seem to be lacking knowledge as to why this is so difficult.

答:
These things helped me

Go to proxy -> SSL proxy settings -> Add

Add your site name here and give port number as 8888

Right click on your site name on the left panel and choose "Enable
SSL Proxying"

Hope this helps someone out there.

Body:
I would like to use Charles web proxy to work with the Android emulator in Windows.  I've successfully set up charles and have started the emulator with the command line:

emulator -http-proxy 127.0.0.1:8888 @NexusOne

I can see traffic coming from the android emulator in Charles, but the problem is that I'm developing against a live API which uses SSL and I'm not sure how to configure Charles to let me play about the the data which is sent and received.  I'm aware of two areas where SSL is set up in Charles (Proxy -> Proxy Settings -> SSL and Proxy -> Client SSL Certificates) but I can't find any decent documentation which has let me do what I want to do.  Has anyone experience with Charles, or certificates in general, who can explain how to achieve this.  Maybe a primer on certificates would be good too, as I seem to be lacking knowledge as to why this is so difficult.


问:
Calling C# static method from F#
I have this class in C#:

using System.Collections.Generic;

```<code>namespace StrassGlassLib
{
    public class Mesh
    {
        private List<Model.Node> _ns;
        private List<Model.Plate> _ps;

        public Mesh()
        {
            _ns = new List<Model.Node>();
            _ps = new List<Model.Plate>();
        }

        public List<Model.Node> Nodes => _ns;

        public List<Model.Plate> Plates => _ps;

        public void AddNode(Model.Node n)
        {
            _ns.Add(n);
        }

        public void AddPlate(Model.Plate p)
        {
            _ps.Add(p);
        }

        // CREATION METHOD
        public static Mesh CreatePlanarMesh()
        {
            // create new mesh
            Mesh m = new Mesh();
            // add node
            for (int y = 0; y < 2; y += 1)
            {
                for (int x = 0; x < 4; x += 1)
                {
                    m.AddNode(new Model.Node(0, x, y, 0.0));
                }
            }

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

I'm trying to call from F# to learn how to make test with this language, but:

```<code>namespace StraussGlassTest

open System

module MeshTesting =
    open StrassGlassLib

    let m = Mesh.CreatePlanarMesh()
</code>```

The problems are:

I've got error FS0039: The namespace or module 'Mesh' is not defined.

No error on the console, the code looks good

if I try to access to Nodes property I've got error FS0039: The field, constructor or member 'Nodes' is not defined

I imagine i miss more than something on how F# works, Do you have some hints?

答:
ok
the problem was the interactive part

```<code>#if INTERACTIVE
#r @"C:\Users\p.cappelletto\Documents\Visual Studio 2015\Projects\StraussGlass\StraussGlassLib\bin\Debug\StraussGlassLib.dll"
#r @"C:\Users\p.cappelletto\Documents\Visual Studio 2015\Projects\StraussGlass\StraussGlassLib\bin\Debug\StrausLib.dll"
#endif

namespace StraussGlassTest

open System

module MeshTesting =
    open StraussGlassLib
    open StrausLib

    let m = Mesh.CreatePlanarMesh()
    printfn "%A" m.Nodes.Count
</code>```

Now it works, see it also this

Title: Calling C# static method from F#

Body:
I have this class in C#:

using System.Collections.Generic;

namespace StrassGlassLib
{
    public class Mesh
    {
        private List<Model.Node> _ns;
        private List<Model.Plate> _ps;

        public Mesh()
        {
            _ns = new List<Model.Node>();
            _ps = new List<Model.Plate>();
        }

        public List<Model.Node> Nodes => _ns;

        public List<Model.Plate> Plates => _ps;

        public void AddNode(Model.Node n)
        {
            _ns.Add(n);
        }

        public void AddPlate(Model.Plate p)
        {
            _ps.Add(p);
        }

        // CREATION METHOD
        public static Mesh CreatePlanarMesh()
        {
            // create new mesh
            Mesh m = new Mesh();
            // add node
            for (int y = 0; y < 2; y += 1)
            {
                for (int x = 0; x < 4; x += 1)
                {
                    m.AddNode(new Model.Node(0, x, y, 0.0));
                }
            }

            return m;
        }
    }
}

I'm trying to call from F# to learn how to make test with this language, but:

namespace StraussGlassTest

open System

module MeshTesting =
    open StrassGlassLib

    let m = Mesh.CreatePlanarMesh()

The problems are:

I've got error FS0039: The namespace or module 'Mesh' is not defined.

No error on the console, the code looks good

if I try to access to Nodes property I've got error FS0039: The field, constructor or member 'Nodes' is not defined

I imagine i miss more than something on how F# works, Do you have some hints?

Body:
ok
the problem was the interactive part

#if INTERACTIVE
#r @"C:\Users\p.cappelletto\Documents\Visual Studio 2015\Projects\StraussGlass\StraussGlassLib\bin\Debug\StraussGlassLib.dll"
#r @"C:\Users\p.cappelletto\Documents\Visual Studio 2015\Projects\StraussGlass\StraussGlassLib\bin\Debug\StrausLib.dll"
#endif

namespace StraussGlassTest

open System

module MeshTesting =
    open StraussGlassLib
    open StrausLib

    let m = Mesh.CreatePlanarMesh()
    printfn "%A" m.Nodes.Count

Now it works, see it also this


问:
I can't include other html files and it does not show the header
```<code><html>
    <?require('header.html');?>
    <!-- page content -->
    <p>Welcome to the home of TLA Consulting.
        Please take some time to get to know us.</p>

    <p>We specialize in serving your business needs
        and hope to hear from you soon.</p>
    <?php
        require('footer.html');
    ?>
</html>
</code>```

This is my code and it can't show the header when i open it in browser.
i had found many ways online still cant solve the problem.

答:
youre missing <?php. it should be like this :

```<code><?php require('header.html');?>
</code>```

and make sure your page extention is .php

Body:
    <?require('header.html');?>

Welcome to the home of TLA Consulting.
        Please take some time to get to know us.

We specialize in serving your business needs
        and hope to hear from you soon.

    <?php
        require('footer.html');
    ?>

This is my code and it can't show the header when i open it in browser.
i had found many ways online still cant solve the problem.

Body:
youre missing <?php. it should be like this :

<?php require('header.html');?>

and make sure your page extention is .php


问:
Use JavaScript to prevent a later `<script>` tag from being evaluated?
This is a bit of an oddball use case, but I have my reasons:

I'd like to be able to write

```<code><script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
</code>```

in my markup and, using the code in first.js, prevent or delay the execution of second.js. Is this possible, in any browser? What if the contents of first.js are inlined? (If it helps, assume that the second script tag has an id attribute.)

Since I've gotten a couple of answers that missed what I'm getting at, I should clarify:

The solution must be entirely within first.js. Anything that require changes to the original HTML of the page, or to second.js, is not acceptable.

It is acceptable to load second.js via Ajax and execute it using eval. That's the easy part. The hard part is preventing the immediate execution of second.js.

Assume that you don't know what's in second.js. So, you can't just replace each global function called by second.js with a no-op function. (Plus, this would almost certainly lead to errors.)

If you know of a solution that works in some browsers but not in others, I'd love to hear it.

Example: To make this a little more concrete, let's say that the code

```<code><script type="text/javascript">
  function func() {
    window.meaningOfLife = 42;
    window.loadSecond();
  };
  setTimeout(func, 10);
</script>
</code>```

precedes the two script includes, and that second.js contains the line

```<code>if (window.meaningOfLife !== 42) {throw new Error();}
</code>```

first.js should be able to prevent this error by delaying second.js from executing until window.loadSecond is run. (Assume the implementation of window.loadSecond is also in first.js.) It is not allowed to touch window.meaningOfLife.

Update: Alohci's answer meets these requirements, but only on the condition that the second script tag comes immediately after the first, with nothing but whitespace in between. If someone could extend his hack to avoid that requirement, without introducing other unwanted consequences, that would be amazing...

答: you may use setTimeout() to delay the execution of some code</p>

Body:
This is a bit of an oddball use case, but I have my reasons:

I'd like to be able to write

in my markup and, using the code in first.js, prevent or delay the execution of second.js. Is this possible, in any browser? What if the contents of first.js are inlined? (If it helps, assume that the second script tag has an id attribute.)

Since I've gotten a couple of answers that missed what I'm getting at, I should clarify:

The solution must be entirely within first.js. Anything that require changes to the original HTML of the page, or to second.js, is not acceptable.

It is acceptable to load second.js via Ajax and execute it using eval. That's the easy part. The hard part is preventing the immediate execution of second.js.

Assume that you don't know what's in second.js. So, you can't just replace each global function called by second.js with a no-op function. (Plus, this would almost certainly lead to errors.)

If you know of a solution that works in some browsers but not in others, I'd love to hear it.

Example: To make this a little more concrete, let's say that the code

precedes the two script includes, and that second.js contains the line

if (window.meaningOfLife !== 42) {throw new Error();}

first.js should be able to prevent this error by delaying second.js from executing until window.loadSecond is run. (Assume the implementation of window.loadSecond is also in first.js.) It is not allowed to touch window.meaningOfLife.

Update: Alohci's answer meets these requirements, but only on the condition that the second script tag comes immediately after the first, with nothing but whitespace in between. If someone could extend his hack to avoid that requirement, without introducing other unwanted consequences, that would be amazing...


问:
What is the difference between SocketAddress and InetAddress in Java
It's unclear what SocketAddres is designed for. As far as I see there is just one reasonable way to use it: through InetSocketAddress. It's confusing.</p>

答:
InetAddress will give the IP address of specified web site
example :

```<code>InetAddress ip=InetAddress.getByName("www.google.com");

System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
</code>```

SocketAdress is used to create the Socket at end point with InetAddress and port number

```<code> InetAddress addr = InetAddress.getByName("www.google.com");
    int port = 80;
    SocketAddress sockaddr = new InetSocketAddress(addr, port);

    Socket sock = new Socket();

    sock.connect(sockaddr);
</code>```

Body:
InetAddress will give the IP address of specified web site
example :

InetAddress ip=InetAddress.getByName("www.google.com");

System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());

SocketAdress is used to create the Socket at end point with InetAddress and port number

 InetAddress addr = InetAddress.getByName("www.google.com");
    int port = 80;
    SocketAddress sockaddr = new InetSocketAddress(addr, port);

    Socket sock = new Socket();

    sock.connect(sockaddr);


答:
if your use heade.html and footer.html file include in .html file so its not work

because html page doesn't support php code so save your page in .html to .php and run again

and also change

<?require('header.html');?> to  <?php require('header.html'); ?>

Title: I can't include other html files and it does not show the header


问:
Ngx-pagination does not work for custom component
I am trying to build a custom ngx-pagination for the library and I am

referring the link https://github.com/michaelbromley/ngx-pagination But I do not

understand what I need to do to build the custom pagination.It does not respond to

a click event.

HTML

```<code><table class="table">
  <thead>
    <tr>
      <th>SL</th>
      <th>Ref</th>
      <th>Project Name</th>
      <th>Product Owner</th>
      <th>Project Type</th>
      <th>Remaining Days</th>
      <th>Status</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let project of projects  | paginate: { itemsPerPage: 7, currentPage: p } ;let ndx = index" >
      <td>{{ndx+1}}</td>
      <td>{{project.ref}}</td>
      <td>{{project.projectName}}</td>
      <td>{{project.productOwner}}</td>
      <td>{{project.projectType}}</td>
      <td>{{project.days}}</td>
      <td>{{project.status}}</td>
    </tr>
   </tbody>
</table>

  <pagination-template #p="paginationApi"
                 (pageChange)="pageChange.emit($event)">

    <div class="pagination-previous" [class.disabled]="p.isFirstPage()">
        <a *ngIf="!p.isFirstPage()" (click)="p.previous()"> < </a>
    </div>

    <div *ngFor="let page of p.pages" [class.current]="p.getCurrent() === page.value">
        <a (click)="p.setCurrent(page.value)" *ngIf="p.getCurrent() !== page.value">
            <span>{{ page.label }}</span>
        </a>
        <div *ngIf="p.getCurrent() === page.value">
            <span>{{ page.label }}</span>
        </div>
    </div>

    <div class="pagination-next" [class.disabled]="p.isLastPage()">
        <a *ngIf="!p.isLastPage()" (click)="p.next()"> > </a>
    </div>
</code>```

CUSTOM-COMPONENT.TS

```<code>@Input() id: string;
@Input() maxSize: number;
@Output() pageChange: EventEmitter<number> = new EventEmitter<number>();
page: number = 1;

 pageChanged(event){
    console.log("pageChanged");
  }
</code>```

What else changes are required to make it work?Am I missing something here I have installed the library using npm.Please suggest.

答:
Solved the issue.Seems to be naming conflict.

HTML

```<code> <pagination-template #pT="paginationApi"
                         (pageChange)="p = $event">

            <div class="pagination-previous" [class.disabled]="pT.isFirstPage()">
                <a *ngIf="!pT.isFirstPage()" (click)="pT.previous()"> < </a>
            </div>

            <div *ngFor="let page of pT.pages" [class.current]="pT.getCurrent() === page.value">
                <a (click)="pT.setCurrent(page.value)" *ngIf="pT.getCurrent() !== page.value">
                    <span>{{ page.label }}</span>
                </a>
                <div *ngIf="pT.getCurrent() === page.value">
                    <span>{{ page.label }}</span>
                </div>
            </div>

            <div class="pagination-next" [class.disabled]="pT.isLastPage()">
                <a *ngIf="!pT.isLastPage()" (click)="pT.next()"> > </a>
            </div>

    </pagination-template>
</code>```

Body:
I am trying to build a custom ngx-pagination for the library and I am

referring the link https://github.com/michaelbromley/ngx-pagination But I do not

understand what I need to do to build the custom pagination.It does not respond to

a click event.

HTML

      SL
      Ref
      Project Name
      Product Owner
      Project Type
      Remaining Days
      Status

      {{ndx+1}}
      {{project.ref}}
      {{project.projectName}}
      {{project.productOwner}}
      {{project.projectType}}
      {{project.days}}
      {{project.status}}

  <pagination-template #p="paginationApi"
                 (pageChange)="pageChange.emit($event)">

         <

            {{ page.label }}

            {{ page.label }}

         >

CUSTOM-COMPONENT.TS

@Input() id: string;
@Input() maxSize: number;
@Output() pageChange: EventEmitter<number> = new EventEmitter<number>();
page: number = 1;

 pageChanged(event){
    console.log("pageChanged");
  }

What else changes are required to make it work?Am I missing something here I have installed the library using npm.Please suggest.

Body:
Solved the issue.Seems to be naming conflict.

HTML

 <pagination-template #pT="paginationApi"
                         (pageChange)="p = $event">

            <div class="pagination-previous" [class.disabled]="pT.isFirstPage()">
                <a *ngIf="!pT.isFirstPage()" (click)="pT.previous()"> < </a>
            </div>

            <div *ngFor="let page of pT.pages" [class.current]="pT.getCurrent() === page.value">
                <a (click)="pT.setCurrent(page.value)" *ngIf="pT.getCurrent() !== page.value">
                    <span>{{ page.label }}</span>
                </a>
                <div *ngIf="pT.getCurrent() === page.value">
                    <span>{{ page.label }}</span>
                </div>
            </div>

            <div class="pagination-next" [class.disabled]="pT.isLastPage()">
                <a *ngIf="!pT.isLastPage()" (click)="pT.next()"> > </a>
            </div>

    </pagination-template>


问:
can someone explain what this code is doing
I am having two problems here:

The following block of codes has got me confused. Primarily, I do not know what exactly the code is doing from the basics; I just copied it from a tutorial, and it seems to do what i want it to do. If anyone can explain in bits what it does, it will be really helpful.

The second problem is that I do not know why it throws an ArrayIndexOutOfBounds error, maybe because I do not understand it or otherwise. I really need clarification.

```<code>   try {
        Document searchLink = Jsoup.connect("https://www.google.com.ng/search?dcr=0&source=hp&ei=5-cIWuZ30cCwB7aUhrAN&q=" + URLEncoder.encode(searchValue, encoding))
                .userAgent("Mozilla/5.0").get();
        String websiteLink = searchLink.getElementsByTag("cite").get(0).text();

        //we are setting the value for the action "titles" in the wikipedia API with our own article title
        //we use the string method replaceAll() to remove the title of the article from the wikipedia URL that we generated from google
        //
        String wikiAPItoSearch = "https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles="
                                + URLEncoder.encode(websiteLink.replaceAll("https://en.wikipedia.org/wiki/", ""),encoding);
        System.out.println(wikiAPItoSearch);

        //extraction of textfiles
        //from this point till down i cant really grab what is happening
        HttpURLConnection httpconn = (HttpURLConnection) new URL(wikiAPItoSearch).openConnection();
        httpconn.addRequestProperty("userAgent", "Mozilla/5.0");

        BufferedReader bf = new BufferedReader(new InputStreamReader(httpconn.getInputStream()));

        //read line by line
        String response = bf.lines().collect(Collectors.joining());
        bf.close();
        ///it returns ArrayIndexOutOfBounds here
        String result = response.split("\"extract\":\"")[1];
        System.out.println(result);
    } catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }
</code>```

答:
I don't think anyone will take the time to explain the code for you. A good opportunity for you to do some debugging.

ArrayIndexOutOfBounds comes from response.split("\"extract\":\"")[1]. There is no guarantee that the String response can be split into at least 2 parts.

Add a check to avoid the error. Instead of...

```<code>    String result = response.split("\"extract\":\"")[1];
</code>```

use...

```<code>    String[] parts = response.split("\"extract\":\"");
    String result;
    if (parts.length >= 2) {
        result = parts[1];
    } else {
        result = "Error..." + response; // a simple fallback
    }
</code>```

This is how split works:

```<code>String input = "one,two,three";
String[] parts = input.split(",");
System.out.println(parts[0]); // prints 'one'
System.out.println(parst[2]); // prints 'three'
</code>```

So in your case, [1] means the second item in the parts array. "\"extract\":\"" has to appear at least once in the response, otherwise there will be only one item in the parts array, and you will get an error when you try to reach the second item (since it doesn't exist). It all gets extra tricky since .split accepts a regexp string and "\"extract\":\"" contains regexp reserved characters.

Body:
I am having two problems here:

The following block of codes has got me confused. Primarily, I do not know what exactly the code is doing from the basics; I just copied it from a tutorial, and it seems to do what i want it to do. If anyone can explain in bits what it does, it will be really helpful.

The second problem is that I do not know why it throws an ArrayIndexOutOfBounds error, maybe because I do not understand it or otherwise. I really need clarification.

   try {
        Document searchLink = Jsoup.connect("https://www.google.com.ng/search?dcr=0&source=hp&ei=5-cIWuZ30cCwB7aUhrAN&q=" + URLEncoder.encode(searchValue, encoding))
                .userAgent("Mozilla/5.0").get();
        String websiteLink = searchLink.getElementsByTag("cite").get(0).text();

        //we are setting the value for the action "titles" in the wikipedia API with our own article title
        //we use the string method replaceAll() to remove the title of the article from the wikipedia URL that we generated from google
        //
        String wikiAPItoSearch = "https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles="
                                + URLEncoder.encode(websiteLink.replaceAll("https://en.wikipedia.org/wiki/", ""),encoding);
        System.out.println(wikiAPItoSearch);

        //extraction of textfiles
        //from this point till down i cant really grab what is happening
        HttpURLConnection httpconn = (HttpURLConnection) new URL(wikiAPItoSearch).openConnection();
        httpconn.addRequestProperty("userAgent", "Mozilla/5.0");

        BufferedReader bf = new BufferedReader(new InputStreamReader(httpconn.getInputStream()));

        //read line by line
        String response = bf.lines().collect(Collectors.joining());
        bf.close();
        ///it returns ArrayIndexOutOfBounds here
        String result = response.split("\"extract\":\"")[1];
        System.out.println(result);
    } catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }

Body:
I don't think anyone will take the time to explain the code for you. A good opportunity for you to do some debugging.

ArrayIndexOutOfBounds comes from response.split("\"extract\":\"")[1]. There is no guarantee that the String response can be split into at least 2 parts.

Add a check to avoid the error. Instead of...

    String result = response.split("\"extract\":\"")[1];

use...

    String[] parts = response.split("\"extract\":\"");
    String result;
    if (parts.length >= 2) {
        result = parts[1];
    } else {
        result = "Error..." + response; // a simple fallback
    }

This is how split works:

String input = "one,two,three";
String[] parts = input.split(",");
System.out.println(parts[0]); // prints 'one'
System.out.println(parst[2]); // prints 'three'

So in your case, [1] means the second item in the parts array. "\"extract\":\"" has to appear at least once in the response, otherwise there will be only one item in the parts array, and you will get an error when you try to reach the second item (since it doesn't exist). It all gets extra tricky since .split accepts a regexp string and "\"extract\":\"" contains regexp reserved characters.


问:
Which Version of Python to Use for Maximum Compatibility
If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system?

I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current version seems to be working fine. What version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements?

答:
You can use different versions of python on each machine.

Coding something new, I would not use anything less than python2.5. You can do apt-get install python2.5 on stock debian stable.

For windows, don't really worry about it. It's very easy to install the python2.5 msi.

If the users can't be bothered to do that, you can deploy an executable with py2exe (so simple) and build an installer with inno setup (again simple) then it will behave like a standard windows application and will use its own python dlls, so no need to have python installed.

Like Peter said: keep in mind the transition to 3.0 but don't build on it yet.

OwnerDisplayName: Cristian

OwnerDisplayName: Christopher Mahan


问:
jQuery Maximum Amount Of DatePickers
I have a rather frustrating problem where the maximum number of available DatePicker's on one page seems to be twenty.  I can't find any documentation referring to this.

If I had a page with 100 text boxes, and did the following:

```<code>$(document).ready(function() {
    $(".datepicker").datepicker({ duration: '', dateFormat: 'dd/mm/yy' });
});
</code>```

Then the first 20 text boxes have the DatePicker, however, when you select an input box after that the DatePicker pops up against the twentieth input box for a date.

This is being done under IE7.  Any ideas?

答:
The code is subject to NDA (not as in secret service NDA, as in, it's work-related NDA ;) ) so I can't show the ACTUAL code, however I can say that it's part of an XSLT page which auto-generates the fields.

I have an input like so

```<code><input class="datepicker" name="{UNIQUE}-date" type="text" />
<a href="javascript:MyFunctionCall('linktype', '{UNIQUE}')">go</a>
</code>```

This way, on a form submit I know the unique field once I post-fix it with the "-date" identifier and can get the data back from the HTML input field.  The MyFunctionCall just submits two form values, that way in my code I can check for a form value of "linktype", that way I know what to do with that form submit.  It's a little hack to differentiate between different types of form submit within the same form.

As shown before:

```<code>$(document).ready(function() {
  $(".datepicker").datepicker({ duration: '', dateFormat: 'dd/mm/yy' });
});
</code>```

This way it gets all of the inputs which have that class type.

EDIT As I say, this is against many fields, about 100 altogether.

OwnerDisplayName: Kezzer

Title: jQuery Maximum Amount Of DatePickers

Body:
I have a rather frustrating problem where the maximum number of available DatePicker's on one page seems to be twenty.  I can't find any documentation referring to this.

If I had a page with 100 text boxes, and did the following:

$(document).ready(function() {
    $(".datepicker").datepicker({ duration: '', dateFormat: 'dd/mm/yy' });
});

Then the first 20 text boxes have the DatePicker, however, when you select an input box after that the DatePicker pops up against the twentieth input box for a date.

This is being done under IE7.  Any ideas?

Body:
The code is subject to NDA (not as in secret service NDA, as in, it's work-related NDA ;) ) so I can't show the ACTUAL code, however I can say that it's part of an XSLT page which auto-generates the fields.

I have an input like so

<input class="datepicker" name="{UNIQUE}-date" type="text" />
<a href="javascript:MyFunctionCall('linktype', '{UNIQUE}')">go</a>

This way, on a form submit I know the unique field once I post-fix it with the "-date" identifier and can get the data back from the HTML input field.  The MyFunctionCall just submits two form values, that way in my code I can check for a form value of "linktype", that way I know what to do with that form submit.  It's a little hack to differentiate between different types of form submit within the same form.

As shown before:

$(document).ready(function() {
  $(".datepicker").datepicker({ duration: '', dateFormat: 'dd/mm/yy' });
});

This way it gets all of the inputs which have that class type.

EDIT As I say, this is against many fields, about 100 altogether.