问:
deploy build to artifactory via cli or jenkins plugin
```<code>./jfrog rt upload --url http://192.168.1.10:8081/artifactory/ --user=admin --password=password --build-name=ttt --build-number=70 1.txt ttt/my/txttest/1.0.1/txttest-1.0.1.txt
./jfrog rt bce ttt 70
./jfrog rt build-publish ttt 70
</code>```

Look at artifactory and see grey link (unworking) to published artifacts in build tab.
result

Artifacts are normally uploaded and accessible.
Same will happen then use "Generic-Artifactory Integration" from Jenkins

Artifactory OSS 5.5.2 rev 50502900

./jfrog version 1.12.1

答: According to the docs managing artifacts for builds isn't available in OSS editions. See https://www.jfrog.com/confluence/display/RTF/Artifactory+Comparison+Matrix</p>

Body:
./jfrog rt upload --url http://192.168.1.10:8081/artifactory/ --user=admin --password=password --build-name=ttt --build-number=70 1.txt ttt/my/txttest/1.0.1/txttest-1.0.1.txt
./jfrog rt bce ttt 70
./jfrog rt build-publish ttt 70

Look at artifactory and see grey link (unworking) to published artifacts in build tab.
result

Artifacts are normally uploaded and accessible.
Same will happen then use "Generic-Artifactory Integration" from Jenkins

Artifactory OSS 5.5.2 rev 50502900

./jfrog version 1.12.1


来源: stackexchange

问:
How do I read this text file and Insert into MySQL?
sample

```<code>user id  User Name
   U456      Mathew
   U457      Leon
   U458      Cris
   U459      Yancy
   U460      Jane
</code>```

and so on up to 500k.

I need to read this text file and insert to MySQL  in two columns say User ID and User Name. How do I do this in PHP?

答:
Using PHP, Possibly Something similar to this:

```<code>$file = "/path/to/text/file.txt";
$fp = fopen($file, "r");
$data = fread($fp, filesize($file));
fclose($fp);
</code>```

The above reads the text file into a variable

```<code>$output = explode("\n", $output);
foreach($output as $var) {
$tmp = explode("|", $var);
$userId = $tmp[0];
$userName = $tmp[1];
</code>```

Tell it to explode at each Endline and then store the data in temp variables

```<code>$sql = "INSERT INTO table SET userId='$userId', userName='$userName'";
mysql_query($sql);
</code>```

Execute the query for each line

ContentLicense: CC BY-SA 2.5

Body:
sample

user id  User Name
   U456      Mathew
   U457      Leon
   U458      Cris
   U459      Yancy
   U460      Jane

and so on up to 500k.

I need to read this text file and insert to MySQL  in two columns say User ID and User Name. How do I do this in PHP?

Body:
Using PHP, Possibly Something similar to this:

$file = "/path/to/text/file.txt";
$fp = fopen($file, "r");
$data = fread($fp, filesize($file));
fclose($fp);

The above reads the text file into a variable

$output = explode("\n", $output);
foreach($output as $var) {
$tmp = explode("|", $var);
$userId = $tmp[0];
$userName = $tmp[1];

Tell it to explode at each Endline and then store the data in temp variables

$sql = "INSERT INTO table SET userId='$userId', userName='$userName'";
mysql_query($sql);

Execute the query for each line


问:
How can I declare a function or variable in a file and use it always in Swift
Currently I am working on a project and I have to use an alert message almost in every view controller. Particularly this one:

```<code>func showMessage(myMessage: String) {
    let myAlert = UIAlertController(title: "ALERT", message: myMessage, preferredStyle: UIAlertControllerStyle.alert)
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
    myAlert.addAction(okAction)
    self.present(myAlert, animated: true, completion: nil)
}
</code>```

Using the same code over an over again makes my code verbose. This scenario goes with some other functions and some variables also. How can I declare this function somewhere in a different file and use it whenever necessary? Shall I use a singleton pattern like:

```<code>static let sharedInstance = viewController()
</code>```

If so, please show me an example.

答:
Your function showMessage(myMessage:) is common to all your ViewControllers. So you can either :

Use a super class ViewController and implement your function in there :

```<code>class BaseViewController {
    func showMessage(myMessage: String) { ... }
}
</code>```

Use swift protocols :

```<code>protocol MessageHelper {}

extension MessageHelper where Self: UIViewController {
    func showMessage(myMessage: String) { ... }
}

extension MyViewController: MessageHelper {}
</code>```

Using a shared instance that handles all your message could be another way to go.

```<code>class MessageController {
    static let shared = MessageController()
    private init() {}

    func showMessage(myMessage: String, viewController: UIViewController) { ... }

}
</code>```

And just call MessageController.shared.showMessage(myMessage:viewController:) when you need to display a message.

Using a message controller will give you more possibilities, you can either count the number of messages displayed or filter messages to display in the same and one place.

ContentLicense: CC BY-SA 3.0

Body:
Currently I am working on a project and I have to use an alert message almost in every view controller. Particularly this one:

func showMessage(myMessage: String) {
    let myAlert = UIAlertController(title: "ALERT", message: myMessage, preferredStyle: UIAlertControllerStyle.alert)
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
    myAlert.addAction(okAction)
    self.present(myAlert, animated: true, completion: nil)
}

Using the same code over an over again makes my code verbose. This scenario goes with some other functions and some variables also. How can I declare this function somewhere in a different file and use it whenever necessary? Shall I use a singleton pattern like:

static let sharedInstance = viewController()

If so, please show me an example.

Body:
Your function showMessage(myMessage:) is common to all your ViewControllers. So you can either :

Use a super class ViewController and implement your function in there :

class BaseViewController {
    func showMessage(myMessage: String) { ... }
}

Use swift protocols :

protocol MessageHelper {}

extension MessageHelper where Self: UIViewController {
    func showMessage(myMessage: String) { ... }
}

extension MyViewController: MessageHelper {}

Using a shared instance that handles all your message could be another way to go.

class MessageController {
    static let shared = MessageController()
    private init() {}

    func showMessage(myMessage: String, viewController: UIViewController) { ... }

}

And just call MessageController.shared.showMessage(myMessage:viewController:) when you need to display a message.

Using a message controller will give you more possibilities, you can either count the number of messages displayed or filter messages to display in the same and one place.


问:
OpenCV squared norm for cv::Point2d
I try to use squared euclidean norm cv::NORM_L2SQR without taking root, as shown here

Does OpenCV offer a squared norm function for cv::Point?

to save computational resources. So while the following code works:

```<code>// works fine
cv::Point2d a(1.5, 3);
cv::Point2d b(5.1, 6);
//Euclidean distance
//http://answers.opencv.org/question/14188
double res = cv::norm(a-b);
</code>```

The following doesn't:

```<code>double res = cv::norm(a-b,cv::NORM_L2SQR);
</code>```

(error: no matching function for call to norm(cv::Point_<double>, cv::NormTypes))

What can I do in OpenCV 3.1 to use optimized solution?

EDIT: I'm using custom function at the moment and hope that compiler optimizes it somehow:

```<code>double euclideanDist(cv::Point2d& p, cv::Point2d& q) {
    cv::Point2d diff = p - q;
    return (diff.x*diff.x + diff.y*diff.y);
}
</code>```

答:
Have to explicitly construct an InputArray container (e.g. matrix) in order to compile properly for non-default parameters:

double res = cv::norm( cv::Mat( a0 - b0 ), cv::NORM_L2SQR );

Though cost of creating a container object might be slower than just calculating the norm.

cv::norm( std::vector< cv::Point2d >( 1, a0 - b0 ), cv::NORM_L2SQR );

Perhaps converting Point2d to std::complex and using the std::norm() is more thoughtful.

```<code>cv::Point2d diff = a0 - b0;
std::norm( std::complex< double >( diff.x, diff.y ) );
</code>```

Title: OpenCV squared norm for cv::Point2d

Body:
I try to use squared euclidean norm cv::NORM_L2SQR without taking root, as shown here

Does OpenCV offer a squared norm function for cv::Point?

to save computational resources. So while the following code works:

// works fine
cv::Point2d a(1.5, 3);
cv::Point2d b(5.1, 6);
//Euclidean distance
//http://answers.opencv.org/question/14188
double res = cv::norm(a-b);

The following doesn't:

double res = cv::norm(a-b,cv::NORM_L2SQR);

(error: no matching function for call to norm(cv::Point_<double>, cv::NormTypes))

What can I do in OpenCV 3.1 to use optimized solution?

EDIT: I'm using custom function at the moment and hope that compiler optimizes it somehow:

double euclideanDist(cv::Point2d& p, cv::Point2d& q) {
    cv::Point2d diff = p - q;
    return (diff.x*diff.x + diff.y*diff.y);
}

Body:
Have to explicitly construct an InputArray container (e.g. matrix) in order to compile properly for non-default parameters:

double res = cv::norm( cv::Mat( a0 - b0 ), cv::NORM_L2SQR );

Though cost of creating a container object might be slower than just calculating the norm.

cv::norm( std::vector< cv::Point2d >( 1, a0 - b0 ), cv::NORM_L2SQR );

Perhaps converting Point2d to std::complex and using the std::norm() is more thoughtful.

cv::Point2d diff = a0 - b0;
std::norm( std::complex< double >( diff.x, diff.y ) );


问:
Could not cast value of type 'UITableViewCell' to 'ProjectName.UserCell'
Hey guys befor you mark this as a duplicate just please hear me out. I have tried everything related to this topic including adding

self.tableView.registerClass(UserCell.self, forCellReuseIdentifier: "cell")

I have also changed my placeholder cell to match the UserCell class

Im Not sure what it could be! I get the error :

Could not cast value of type 'UITableViewCell' (0x1134700e0) to 'Lightning_Chat.UserCell'

with type SIGBRT not sure what could be going on and ive tried everything please help!

here is table view code :

```<code>  public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    // not casting for some reason
    let cell : UserCell =  UITableViewCell(style: .subtitle , reuseIdentifier: "cellId") as! UserCell

    cell.textLabel?.text = contacts[indexPath.row].userName
    cell.detailTextLabel?.text = contacts[indexPath.row].score

    if let profileImageUrl = contacts[indexPath.row].picURL {
        let url = URL(string: profileImageUrl)
        URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

            //download hit an error
            if error != nil {
                print(error!)
                return
            }
            DispatchQueue.main.async {
                cell.profileImageView.image = UIImage(data: data!)

            }

        }).resume()
    }

    return cell;
}
</code>```

here is my view did load :

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.register(UserCell.self, forCellReuseIdentifier: "cellId")

    //irrelevant
    fetchUsers()
}
</code>```

答:
Instead of:

```<code>let cell : UserCell =  UITableViewCell(style: .subtitle , reuseIdentifier: "cellId") as! UserCell
</code>```

Try this:

```<code>let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! UserCell
</code>```

Body:
Hey guys befor you mark this as a duplicate just please hear me out. I have tried everything related to this topic including adding

self.tableView.registerClass(UserCell.self, forCellReuseIdentifier: "cell")

I have also changed my placeholder cell to match the UserCell class

Im Not sure what it could be! I get the error :

Could not cast value of type 'UITableViewCell' (0x1134700e0) to 'Lightning_Chat.UserCell'

with type SIGBRT not sure what could be going on and ive tried everything please help!

here is table view code :

  public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    // not casting for some reason
    let cell : UserCell =  UITableViewCell(style: .subtitle , reuseIdentifier: "cellId") as! UserCell

    cell.textLabel?.text = contacts[indexPath.row].userName
    cell.detailTextLabel?.text = contacts[indexPath.row].score

    if let profileImageUrl = contacts[indexPath.row].picURL {
        let url = URL(string: profileImageUrl)
        URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

            //download hit an error
            if error != nil {
                print(error!)
                return
            }
            DispatchQueue.main.async {
                cell.profileImageView.image = UIImage(data: data!)

            }

        }).resume()
    }

    return cell;
}

here is my view did load :

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.register(UserCell.self, forCellReuseIdentifier: "cellId")

    //irrelevant
    fetchUsers()
}

Body:
Instead of:

let cell : UserCell =  UITableViewCell(style: .subtitle , reuseIdentifier: "cellId") as! UserCell

Try this:

let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! UserCell


问:
jQuery: How to enable `timeout` for `$.ajax({dataType:'jsonp'...`? Is there any solution?
jQuery: How to enable timeout for $.ajax({dataType:'jsonp'...? Is there any solution? http://jsfiddle.net/laukstein/2wcpU/4

```<code>$.ajax({
    type:"GET",
    url:'http://lab.laukstein.com/ajax-seo/.json',
    dataType:'jsonp',
    timeout:200, // Not working with dataType:'jsonp'
    success:function(data){$('#content').html(data.content);},
    error:function(request,status,error){$('#content').html('request failed');}
});
</code>```

I do not like to use some plugins for that, like http://code.google.com/p/jquery-jsonp.

答:
Here is my solution with setTimeout and clearTimeout http://jsfiddle.net/laukstein/2wcpU/7/

```<code>$('#content').ajaxStart(function(){
    $(this).html('Loading...');
});
var timer=window.setTimeout(function(){
    $('#content').html('Loading seems to be taking a while. Try again.');
},2000);
$.ajax({
    type:"GET",
    url:'http://lab.laukstein.com/ajax-seo/.json',
    dataType:'jsonp',
    success:function(data){
        window.clearTimeout(timer);
        $('#content').html(data.content);
    },
    error:function(){
        window.clearTimeout(timer);
        $('#content').html('The request failed. Try to refresh page.');
    }
});
</code>```

Body:
jQuery: How to enable timeout for $.ajax({dataType:'jsonp'...? Is there any solution? http://jsfiddle.net/laukstein/2wcpU/4

$.ajax({
    type:"GET",
    url:'http://lab.laukstein.com/ajax-seo/.json',
    dataType:'jsonp',
    timeout:200, // Not working with dataType:'jsonp'
    success:function(data){$('#content').html(data.content);},
    error:function(request,status,error){$('#content').html('request failed');}
});

I do not like to use some plugins for that, like http://code.google.com/p/jquery-jsonp.

Body:
Here is my solution with setTimeout and clearTimeout http://jsfiddle.net/laukstein/2wcpU/7/

$('#content').ajaxStart(function(){
    $(this).html('Loading...');
});
var timer=window.setTimeout(function(){
    $('#content').html('Loading seems to be taking a while. Try again.');
},2000);
$.ajax({
    type:"GET",
    url:'http://lab.laukstein.com/ajax-seo/.json',
    dataType:'jsonp',
    success:function(data){
        window.clearTimeout(timer);
        $('#content').html(data.content);
    },
    error:function(){
        window.clearTimeout(timer);
        $('#content').html('The request failed. Try to refresh page.');
    }
});


问:
In a socket.recv(1024), how can I search for a specific word inside of it?
I have a simple banner grabber. If I grab a banner from Google, I receive something back.

I want to find a specific word inside the socket data? How can I do that?

My Banner grabber:

```<code>import socket
import ipaddress

import socket
host = "www.google.nl"
port = 80
addr = (host, port)
s = socket.socket()
s.connect (addr)
s.send(b'GET / HTTP/1.1\n\n\n')
print(s.recv(1024))
</code>```

Banner I receive from Google.nl (s.recv(1024)):

b'HTTP/1.1 302 Found\r\nCache-Control: private\r\nContent-Type: text/html; charset=UTF-8\r\nReferrer-Policy: no-referrer\r\nLocation: http://www.google.nl/?gfe_rd=cr&dcr=0&ei=XrAKWpHeJ9GC3gOB_ZWoBg\r\nContent-Length: 268\r\nDate: Tue, 14 Nov 2017 08:59:10 GMT\r\n\r\n<meta http-equiv="content-type" content="text/html;charset=utf-8">\n<TITLE>302 Moved</TITLE>\n
302 Moved
\nThe document has moved\nhere.\r\n\r\n'

What I want:

```<code>If "Document" is in s.recv(1024):
print ("Document is found in the banner!")

Else:
print ("No keyword found")
</code>```

答:
Better to use the right tool for the job instead of low-level sockets.  requests is a popular 3rd party library for making HTTP requests.

```<code>>>> import requests
>>> r = requests.get('http://www.google.nl')
>>> r.headers
{'Date': 'Tue, 14 Nov 2017 17:13:33 GMT', 'Expires': '-1', 'Cache-Control': 'private, max-age=0', 'Content-Type': 'text/html; char
set=ISO-8859-1', 'P3P': 'CP="This is not a P3P policy! See g.co/p3phelp for more info."', 'Server': 'gws', 'Content-Length': '5129
', 'X-XSS-Protection': '1; mode=block', 'X-Frame-Options': 'SAMEORIGIN', 'Via': '1.1 jfdmzpr06', 'Connection': 'Keep-Alive', 'Cont
ent-Encoding': 'gzip', 'Set-Cookie': '1P_JAR=2017-11-14-17; expires=Thu, 14-Dec-2017 17:13:33 GMT; path=/; domain=.google.nl, NID=
117=Sa3F7Bq4oXkQdcBu5OXCM3AdfyGZbxABbYqFMenMm-Ru4nITdC8tQujRxLJPl3aUG8ksQM-uDF56jlDrk0Hm9KMVkbOcb51K0oyys0PFU3ZEaSS5TnzBGk_dOYmK4X
vS; expires=Wed, 16-May-2018 17:13:33 GMT; path=/; domain=.google.nl; HttpOnly'}
>>> r.status_code
200
>>> r.text[:1000]
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world\'s informa
tion, including webpages, images, videos and more. Google has many special features to help you find exactly what you\'re looking
for." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><m
eta content="/logos/doodles/2017/131st-anniversary-of-the-hole-puncher-5763551741345792.3-law.gif" itemprop="image"><meta content=
"131st Anniversary of the Hole Puncher" property="twitter:title"><meta content="131st Anniversary of the Hole Puncher #GoogleDoodl
e" property="twitter:description"><meta content="131st Anniversary of the Hole Puncher #GoogleDoodle" property="og:description"><m
eta content="summary_large_image" property="twitter:card"><meta content="@GoogleDoodles" property="twitter:site"><meta content="ht
tps://www.google.com/logos/doodles/2017/131st-anniversary-of-the-hole-puncher-576355174134579'
>>> 'History' in r.text
True
</code>```

Body:
I have a simple banner grabber. If I grab a banner from Google, I receive something back.

I want to find a specific word inside the socket data? How can I do that?

My Banner grabber:

import socket
import ipaddress

import socket
host = "www.google.nl"
port = 80
addr = (host, port)
s = socket.socket()
s.connect (addr)
s.send(b'GET / HTTP/1.1\n\n\n')
print(s.recv(1024))

Banner I receive from Google.nl (s.recv(1024)):

b'HTTP/1.1 302 Found\r\nCache-Control: private\r\nContent-Type: text/html; charset=UTF-8\r\nReferrer-Policy: no-referrer\r\nLocation: http://www.google.nl/?gfe_rd=cr&dcr=0&ei=XrAKWpHeJ9GC3gOB_ZWoBg\r\nContent-Length: 268\r\nDate: Tue, 14 Nov 2017 08:59:10 GMT\r\n\r\n<meta http-equiv="content-type" content="text/html;charset=utf-8">\n<TITLE>302 Moved</TITLE>\n
302 Moved
\nThe document has moved\nhere.\r\n\r\n'

What I want:

If "Document" is in s.recv(1024):
print ("Document is found in the banner!")

Else:
print ("No keyword found")

Body:
Better to use the right tool for the job instead of low-level sockets.  requests is a popular 3rd party library for making HTTP requests.

>>> import requests
>>> r = requests.get('http://www.google.nl')
>>> r.headers
{'Date': 'Tue, 14 Nov 2017 17:13:33 GMT', 'Expires': '-1', 'Cache-Control': 'private, max-age=0', 'Content-Type': 'text/html; char
set=ISO-8859-1', 'P3P': 'CP="This is not a P3P policy! See g.co/p3phelp for more info."', 'Server': 'gws', 'Content-Length': '5129
', 'X-XSS-Protection': '1; mode=block', 'X-Frame-Options': 'SAMEORIGIN', 'Via': '1.1 jfdmzpr06', 'Connection': 'Keep-Alive', 'Cont
ent-Encoding': 'gzip', 'Set-Cookie': '1P_JAR=2017-11-14-17; expires=Thu, 14-Dec-2017 17:13:33 GMT; path=/; domain=.google.nl, NID=
117=Sa3F7Bq4oXkQdcBu5OXCM3AdfyGZbxABbYqFMenMm-Ru4nITdC8tQujRxLJPl3aUG8ksQM-uDF56jlDrk0Hm9KMVkbOcb51K0oyys0PFU3ZEaSS5TnzBGk_dOYmK4X
vS; expires=Wed, 16-May-2018 17:13:33 GMT; path=/; domain=.google.nl; HttpOnly'}
>>> r.status_code
200
>>> r.text[:1000]
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world\'s informa
tion, including webpages, images, videos and more. Google has many special features to help you find exactly what you\'re looking
for." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><m
eta content="/logos/doodles/2017/131st-anniversary-of-the-hole-puncher-5763551741345792.3-law.gif" itemprop="image"><meta content=
"131st Anniversary of the Hole Puncher" property="twitter:title"><meta content="131st Anniversary of the Hole Puncher #GoogleDoodl
e" property="twitter:description"><meta content="131st Anniversary of the Hole Puncher #GoogleDoodle" property="og:description"><m
eta content="summary_large_image" property="twitter:card"><meta content="@GoogleDoodles" property="twitter:site"><meta content="ht
tps://www.google.com/logos/doodles/2017/131st-anniversary-of-the-hole-puncher-576355174134579'
>>> 'History' in r.text
True


问:
SQL Divide Multiply Execution Order
```<code>select 3900.0 * 30097 / 30097 as result1
select 3900.0 / 30097 * 30097 as result2
</code>```

Looking at these 2 queries would lead most people (or perhaps just me) to determine that the result would be the same (3900) however it would seem like SQL Server disagrees - waddup?

Spent an afternoon looking for a bug only to find that my issue can be resolved if I change the order of a multiply and divide - aren't we always told order doesn't matter?  Clearly SQL is rounding the result of the first operation in query 2 i.e. 3900.0 / 30097 but why?

答:
Try adding brackets around operators,so order won't be of any issue</p>

```<code>select (3900.0 * 30097) / 30097 as result1
select 3900.0 / (30097 * 30097)as result2
</code>```

Title: SQL Divide Multiply Execution Order

Body:
select 3900.0 * 30097 / 30097 as result1
select 3900.0 / 30097 * 30097 as result2

Looking at these 2 queries would lead most people (or perhaps just me) to determine that the result would be the same (3900) however it would seem like SQL Server disagrees - waddup?

Spent an afternoon looking for a bug only to find that my issue can be resolved if I change the order of a multiply and divide - aren't we always told order doesn't matter?  Clearly SQL is rounding the result of the first operation in query 2 i.e. 3900.0 / 30097 but why?

Body:
Try adding brackets around operators,so order won't be of any issue

select (3900.0 * 30097) / 30097 as result1
select 3900.0 / (30097 * 30097)as result2


答:
You are not creating the cell correctly.

Change:

```<code>let cell : UserCell =  UITableViewCell(style: .subtitle , reuseIdentifier: "cellId") as! UserCell
</code>```

to:

```<code>let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! UserCell
</code>```

Note that your code is directly creating a UITableViewCell which is why you can't cast it. You are bypassing the standard cell reuse as well.

Title: Could not cast value of type 'UITableViewCell' to 'ProjectName.UserCell'

Body:
You are not creating the cell correctly.

Change:

let cell : UserCell =  UITableViewCell(style: .subtitle , reuseIdentifier: "cellId") as! UserCell

to:

let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! UserCell

Note that your code is directly creating a UITableViewCell which is why you can't cast it. You are bypassing the standard cell reuse as well.


问:
For targeted standard and dotnetcore library which dll will be selected in core application?
I have a library, that target NETSTANDARD2_0 that used by full NET461 and NETCOREAPP2_0 clients.

I want to add to the library some Core2.0 specific code.
I am going to add APPNETCORE2_0 target and wrap the section with

```<code>#if NETCOREAPP2_0
#endif
</code>```

It will create 2 separate target DLLs.
When I will refer my library from client Core2.0 application , will it refer NETCOREAPP2_0 DLL and ignore NETSTANDARD2_0 dll?

Is the order of selecting the version predefined and documented?
I will appreciate a link to the documentation.

答:
Here is the official doc on creating these multi-targetted dlls. That explains how a different dll is generated for each target (such as net461 and netcoreapp1.0).

The official doc on how nuget resolves these to find the matching library covers how the right dll is selected:

When NuGet installs a package that has multiple assembly versions, it tries to match the framework name of the assembly with the target framework of the project.

If a match is not found, NuGet copies the assembly for the highest version that is less than or equal to the project's target framework, if available. If no compatible assembly is found, NuGet returns an appropriate error message.

Side note: you want NETCOREAPP2_0, not APPNETCORE2_0.

Body:
I have a library, that target NETSTANDARD2_0 that used by full NET461 and NETCOREAPP2_0 clients.

I want to add to the library some Core2.0 specific code.
I am going to add APPNETCORE2_0 target and wrap the section with

#if NETCOREAPP2_0
#endif

It will create 2 separate target DLLs.
When I will refer my library from client Core2.0 application , will it refer NETCOREAPP2_0 DLL and ignore NETSTANDARD2_0 dll?

Is the order of selecting the version predefined and documented?
I will appreciate a link to the documentation.


问:
What unit test to write for a class using generics in Java?
Taking the very specific example of the JpaDao class defined in this article:

```<code>public abstract class JpaDao<K, E> implements Dao<K, E> {
    protected Class<E> entityClass;

    @PersistenceContext
    protected EntityManager entityManager;

    public JpaDao() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
    }

    public void persist(E entity) { entityManager.persist(entity); }

    public void remove(E entity) { entityManager.remove(entity); }

    public E findById(K id) { return entityManager.find(entityClass, id); }
}
</code>```

would it be best to write unit tests for all the existing entities in the application (Order, Customer, Book, etc.), or would it be acceptable to write unit tests for just one entity, as hinted by this other question?  Are there any best practice regarding unit testing java classes using generics?

答:
If using a different entity type causes different code to execute, then you need a separate test case.

I'd test as much as I could in a common set of tests that only use one entity type.  If most of your code treats all entities the same, then there's no need to test it more than once.  I'd set up separate test cases for any special behavior that's required where specific entity DAOs have different behavior.

Body:
Taking the very specific example of the JpaDao class defined in this article:

public abstract class JpaDao<K, E> implements Dao<K, E> {
    protected Class<E> entityClass;

    @PersistenceContext
    protected EntityManager entityManager;

    public JpaDao() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
    }

    public void persist(E entity) { entityManager.persist(entity); }

    public void remove(E entity) { entityManager.remove(entity); }

    public E findById(K id) { return entityManager.find(entityClass, id); }
}

would it be best to write unit tests for all the existing entities in the application (Order, Customer, Book, etc.), or would it be acceptable to write unit tests for just one entity, as hinted by this other question?  Are there any best practice regarding unit testing java classes using generics?


问:
Switching between GCC and Clang/LLVM using CMake
I have a number of projects built using CMake and I'd like to be able to easily switch between using GCC or Clang/LLVM to compile them. I believe (please correct me if I'm mistaken!) that to use Clang I need to set the following:

```<code>    SET (CMAKE_C_COMPILER             "/usr/bin/clang")
    SET (CMAKE_C_FLAGS                "-Wall -std=c99")
    SET (CMAKE_C_FLAGS_DEBUG          "-g")
    SET (CMAKE_C_FLAGS_MINSIZEREL     "-Os -DNDEBUG")
    SET (CMAKE_C_FLAGS_RELEASE        "-O4 -DNDEBUG")
    SET (CMAKE_C_FLAGS_RELWITHDEBINFO "-O2 -g")

    SET (CMAKE_CXX_COMPILER             "/usr/bin/clang++")
    SET (CMAKE_CXX_FLAGS                "-Wall")
    SET (CMAKE_CXX_FLAGS_DEBUG          "-g")
    SET (CMAKE_CXX_FLAGS_MINSIZEREL     "-Os -DNDEBUG")
    SET (CMAKE_CXX_FLAGS_RELEASE        "-O4 -DNDEBUG")
    SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g")

    SET (CMAKE_AR      "/usr/bin/llvm-ar")
    SET (CMAKE_LINKER  "/usr/bin/llvm-ld")
    SET (CMAKE_NM      "/usr/bin/llvm-nm")
    SET (CMAKE_OBJDUMP "/usr/bin/llvm-objdump")
    SET (CMAKE_RANLIB  "/usr/bin/llvm-ranlib")
</code>```

Is there an easy way of switching between these and the default GCC variables, preferably as a system-wide change rather than project specific (i.e. not just adding them into a project's CMakeLists.txt)?

Also, is it necessary to use the llvm-* programs rather than the system defaults when compiling using clang instead of gcc? What's the difference?

答:
If the default compiler chosen by cmake is gcc and you have installed clang, you can use the easy way to compile your project with clang:

```<code>$ mkdir build && cd build
$ CXX=clang++ CC=clang cmake ..
$ make -j2
</code>```

or specify the compiler for cmake:

```<code>$ cmake -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_C_COMPILER=clang ..
</code>```

Body:
I have a number of projects built using CMake and I'd like to be able to easily switch between using GCC or Clang/LLVM to compile them. I believe (please correct me if I'm mistaken!) that to use Clang I need to set the following:

    SET (CMAKE_C_COMPILER             "/usr/bin/clang")
    SET (CMAKE_C_FLAGS                "-Wall -std=c99")
    SET (CMAKE_C_FLAGS_DEBUG          "-g")
    SET (CMAKE_C_FLAGS_MINSIZEREL     "-Os -DNDEBUG")
    SET (CMAKE_C_FLAGS_RELEASE        "-O4 -DNDEBUG")
    SET (CMAKE_C_FLAGS_RELWITHDEBINFO "-O2 -g")

    SET (CMAKE_CXX_COMPILER             "/usr/bin/clang++")
    SET (CMAKE_CXX_FLAGS                "-Wall")
    SET (CMAKE_CXX_FLAGS_DEBUG          "-g")
    SET (CMAKE_CXX_FLAGS_MINSIZEREL     "-Os -DNDEBUG")
    SET (CMAKE_CXX_FLAGS_RELEASE        "-O4 -DNDEBUG")
    SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g")

    SET (CMAKE_AR      "/usr/bin/llvm-ar")
    SET (CMAKE_LINKER  "/usr/bin/llvm-ld")
    SET (CMAKE_NM      "/usr/bin/llvm-nm")
    SET (CMAKE_OBJDUMP "/usr/bin/llvm-objdump")
    SET (CMAKE_RANLIB  "/usr/bin/llvm-ranlib")

Is there an easy way of switching between these and the default GCC variables, preferably as a system-wide change rather than project specific (i.e. not just adding them into a project's CMakeLists.txt)?

Also, is it necessary to use the llvm-* programs rather than the system defaults when compiling using clang instead of gcc? What's the difference?

Body:
If the default compiler chosen by cmake is gcc and you have installed clang, you can use the easy way to compile your project with clang:

$ mkdir build && cd build
$ CXX=clang++ CC=clang cmake ..
$ make -j2

or specify the compiler for cmake:

$ cmake -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_C_COMPILER=clang ..

ContentLicense: CC BY-SA 4.0


问:
Topics, partitions and keys
I am looking for some clarification on the subject.
In Kafka documentations I found the following:

Kafka only provides a total order over messages within a partition,
not between different partitions in a topic. Per-partition ordering
combined with the ability to partition data by key is sufficient for
most applications. However, if you require a total order over messages
this can be achieved with a topic that has only one partition, though
this will mean only one consumer process per consumer group.

So here are my questions:

Does it mean if i want to have more than 1 consumer (from the same group) reading from one topic I need to have more than 1 partition?

Does it mean I need same amount of partitions as amount of consumers for the same group?

How many consumers can read from one partition?

Also have some questions regarding relationship between keys and partitions with regard to API. I only looked at .net APIs (especially one from MS)  but looks like the mimic Java API.
I see when using a producer to send a message to a topic there is a key parameter. But when consumer reads from a topic there is a partition number.

How are partitions numbered? Starting from 0 or 1?

What exactly relationship between a key and partition?
As I understand some function on key will determine a partition. is that correct?

If I have 2 partitions in a topic and want some particular messages go to one partition and other messages go to another I should use a specific key for one specific partition, and the rest for another?

What if I have 3 partitions and one type of messages to one particular partition and the rest to other 2?

How in general I send messages to a particular partition in order to know  for a consumer from where to read?
Or I better off with multiple topics?

Thanks in advance.

答:
Does it mean if i want to have more than 1 consumer (from the same
  group) reading from one topic I need to have more than 1 partition?

Let's see the following properties of kafka:

each partition is consumed by exactly one consumer in the group

one consumer in the group can consume more than one partition

the number of consumer processes in a group must be <= number
of partitions

With these properties, kafka is smartly able to provide both ordering guarantees and load balancing over a pool of consumer processes.

To answer your question, yes, in the context of the same group, if you want to have N consumers, you have to have at least N partitions.

Does it mean I need same amount of partitions as amount of consumers
  for the same group?

I think this has been explained in the first answer.

How many consumers can read from one partition?

The number of consumers that can read from one partition is always equal to the number of consumer groups subscribing to that topic.

Relationship between keys and partitions with regard to API

First, we must understand that the producer is responsible for choosing which record to assign to which partition within the topic.

Now, lets see how producer does so. First, lets see the class definition of ProducerRecord.java :

```<code>public class ProducerRecord<K, V> {

    private final String topic;
    private final Integer partition;
    private final Headers headers;
    private final K key;
    private final V value;
    private final Long timestamp;

}
</code>```

Here, the field that we have to understand from the class is partition.

From the ProducerRecord docs,

If a valid partition number is specified, that partition will be used when sending the record.

If no partition is specified but a key is present a partition will be chosen using a hash of the key.

If neither key nor partition is present a partition will be assigned in a round-robin fashion.

Title: Topics, partitions and keys

Body:
Does it mean if i want to have more than 1 consumer (from the same
  group) reading from one topic I need to have more than 1 partition?

Let's see the following properties of kafka:

each partition is consumed by exactly one consumer in the group

one consumer in the group can consume more than one partition

the number of consumer processes in a group must be <= number
of partitions

With these properties, kafka is smartly able to provide both ordering guarantees and load balancing over a pool of consumer processes.

To answer your question, yes, in the context of the same group, if you want to have N consumers, you have to have at least N partitions.

Does it mean I need same amount of partitions as amount of consumers
  for the same group?

I think this has been explained in the first answer.

How many consumers can read from one partition?

The number of consumers that can read from one partition is always equal to the number of consumer groups subscribing to that topic.

Relationship between keys and partitions with regard to API

First, we must understand that the producer is responsible for choosing which record to assign to which partition within the topic.

Now, lets see how producer does so. First, lets see the class definition of ProducerRecord.java :

public class ProducerRecord<K, V> {

    private final String topic;
    private final Integer partition;
    private final Headers headers;
    private final K key;
    private final V value;
    private final Long timestamp;

}

Here, the field that we have to understand from the class is partition.

From the ProducerRecord docs,

If a valid partition number is specified, that partition will be used when sending the record.

If no partition is specified but a key is present a partition will be chosen using a hash of the key.

If neither key nor partition is present a partition will be assigned in a round-robin fashion.


问:
react-router-dom Element Type Invalid
I'm new to React and ES6, and am a bit stuck with react-router-dom. I'm currently either getting error messages or none of the information seems to be loading in. I'm using React 15.6.

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import App from './components/App';
import Vote from './components/Vote';
import Results from './components/Results';

ReactDOM.render(
  <Router>
    <App>
      <Route path="/" component={Vote} />
      <Route path="/results" component={Results} />
    </App>
  </Router>,
  document.getElementById('root')
);
</code>```

If I have the two Route declarations in index.js, I am getting an error

```<code>Element type is invalid: expected a string (for built-in components) or a
class/function (for composite components) but got: undefined.
You likely forgot to export your component from the file it's defined in.
</code>```

I think this means that this.props.children doesn't have a value, so it can't clone the route with the pair list correctly?

If I remove the one of the Route declarations, the page does successfully compile, but it's just empty. I added a line of text to the return() in Vote.jsx and it does output that, so the route is working correctly, just nothing is being outputted for the this.getPair() function.

It looks like App.jsx also loads correctly, as it I change the return in this file to output text, it does so.

As mentioned, I'm entirely green to this, so I'm hoping its something fairly simple, or just a misunderstanding of how everything stitches together.

App.jsx

```<code>import React from 'react';
import {List, Map} from 'immutable';

const pair = List.of('Item One', 'Item Two');
const tally = Map({'Item One': 5, 'Item Two': 4});

export class App extends React.PureComponent {
  render() {
    return (
      React.cloneElement(this.props.children, {pair: pair})
    )
  }
};

export default App;
</code>```

Vote.jsx

```<code>import React from 'react';

export class Vote extends React.PureComponent {

  getPair() {
    return this.props.pair || [];
  }

  isDisabled() {
    return !!this.props.hasVoted;
  }

  hasVotedFor(entry) {
    return this.props.hasVoted === entry;
  }

  render() {
    return (
      <div className="voting">
        {this.getPair().map(entry =>
          <button key={entry} onClick={() => this.props.vote(entry)} disabled={this.isDisabled()}>
            <h1>{entry}</h1>
            {this.hasVotedFor(entry) ? <div className="label">Voted</div> : null}
          </button>
        )}
      </div>
    )
  }
};

export default Vote;
</code>```

Results.jsx

```<code>import React from 'react';

export class Results extends React.PureComponent {

  getPair() {
    return this.props.pair || [];

  }

  getVotes(entry) {
    if (this.props.tally && this.props.tally.has(entry)) {
      return this.props.tally.get(entry);
    }

    return 0;
  }

  render() {
   return (
      <div className="results">
        {this.getPair().map(entry =>
          <div key={entry} className="entry">
            <h1>{entry}</h1>
            <div className="voteCount">
              {this.getVotes(entry)}
            </div>
          </div>
        )}
      </div>
    )
  }
};

export default Results;
</code>```

答:
Arman Charan's comment about using a <Switch /> statement was the way that I got the routes to work and to stop receiving the mentioned error.

```<code>ReactDOM.render(
    <Router>
      <App>
        <Switch>
          <Route path="/" component={Vote} />
          <Route path="/results" component={Results} />
        </Switch>
    </Router>,
  document.getElementById('root')
);
</code>```

Title: react-router-dom Element Type Invalid

Body:
I'm new to React and ES6, and am a bit stuck with react-router-dom. I'm currently either getting error messages or none of the information seems to be loading in. I'm using React 15.6.

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import App from './components/App';
import Vote from './components/Vote';
import Results from './components/Results';

ReactDOM.render(
  <Router>
    <App>
      <Route path="/" component={Vote} />
      <Route path="/results" component={Results} />
    </App>
  </Router>,
  document.getElementById('root')
);

If I have the two Route declarations in index.js, I am getting an error

Element type is invalid: expected a string (for built-in components) or a
class/function (for composite components) but got: undefined.
You likely forgot to export your component from the file it's defined in.

I think this means that this.props.children doesn't have a value, so it can't clone the route with the pair list correctly?

If I remove the one of the Route declarations, the page does successfully compile, but it's just empty. I added a line of text to the return() in Vote.jsx and it does output that, so the route is working correctly, just nothing is being outputted for the this.getPair() function.

It looks like App.jsx also loads correctly, as it I change the return in this file to output text, it does so.

As mentioned, I'm entirely green to this, so I'm hoping its something fairly simple, or just a misunderstanding of how everything stitches together.

App.jsx

import React from 'react';
import {List, Map} from 'immutable';

const pair = List.of('Item One', 'Item Two');
const tally = Map({'Item One': 5, 'Item Two': 4});

export class App extends React.PureComponent {
  render() {
    return (
      React.cloneElement(this.props.children, {pair: pair})
    )
  }
};

export default App;

Vote.jsx

import React from 'react';

export class Vote extends React.PureComponent {

  getPair() {
    return this.props.pair || [];
  }

  isDisabled() {
    return !!this.props.hasVoted;
  }

  hasVotedFor(entry) {
    return this.props.hasVoted === entry;
  }

  render() {
    return (

        {this.getPair().map(entry =>
          <button key={entry} onClick={() => this.props.vote(entry)} disabled={this.isDisabled()}>

{entry}

            {this.hasVotedFor(entry) ?
Voted
 : null}
          </button>
        )}

    )
  }
};

export default Vote;

Results.jsx

import React from 'react';

export class Results extends React.PureComponent {

  getPair() {
    return this.props.pair || [];

  }

  getVotes(entry) {
    if (this.props.tally && this.props.tally.has(entry)) {
      return this.props.tally.get(entry);
    }

    return 0;
  }

  render() {
   return (

        {this.getPair().map(entry =>

{entry}

              {this.getVotes(entry)}

        )}

    )
  }
};

export default Results;

Body:
Arman Charan's comment about using a <Switch /> statement was the way that I got the routes to work and to stop receiving the mentioned error.

ReactDOM.render(
    <Router>
      <App>
        <Switch>
          <Route path="/" component={Vote} />
          <Route path="/results" component={Results} />
        </Switch>
    </Router>,
  document.getElementById('root')
);


问:
Spring LDAP authentication bad credentials password in Salted SHA type
I have a project for LDAP authentication with REST service. My LDAP configuration have Salted SHA (SSHA) password hash method. In Spring's LDAP authentication best practice guide supporting SHA method when I used that I got bad credentials while crendentials are ok.

My configuration class reference:

```<code>@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .ldapAuthentication()
                .userSearchFilter("uid={0}")
                .contextSource(contextSource())
                .passwordCompare()
                    .passwordEncoder(new LdapShaPasswordEncoder())
                    .passwordAttribute("userPassword");
    }

    @Bean
    public DefaultSpringSecurityContextSource contextSource() {
        return new DefaultSpringSecurityContextSource(Arrays.asList("ldap://localhost:8389/"), "dc=springframework,dc=org");
    }
}
</code>```

My ldif configuration;

```<code>dn: uid=ben,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Ben Alex
sn: Alex
uid: ben
userPassword: {SSHA}pcFdFhO/NS98EhTRup60PMkHMWFRDkJ3jUu1Zg==
</code>```

My original password is Test1234. My pom.xml file ;

```<code>   <dependency>
       <groupId>org.springframework.ldap</groupId>
       <artifactId>spring-ldap-core</artifactId>
   </dependency>
   <dependency>
       <groupId>org.springframework.security</groupId>
       <artifactId>spring-security-ldap</artifactId>
   </dependency>
   <dependency>
       <groupId>com.unboundid</groupId>
       <artifactId>unboundid-ldapsdk</artifactId>
   </dependency>
</code>```

How can I authenticate with my username/password to ldap server with SSHA password encryption?

答:
Try this approach

```<code>auth
        .ldapAuthentication()
            .userSearchFilter("uid={0}")
            .contextSource(contextSource())
            .passwordCompare().passwordAttribute("userPassword")
            .and()
            .passwordEncoder(passwordEncoder());
</code>```

And create a custom password encoder

```<code>private PasswordEncoder passwordEncoder() {
    final LdapShaPasswordEncoder sha = new LdapShaPasswordEncoder();
    return new PasswordEncoder() {
        @Override
        public String encode(CharSequence rawPassword) {
            return sha.encodePassword(rawPassword.toString(), null);
        }
        @Override
        public boolean matches(CharSequence rawPassword, String encodedPassword) {
            return sha.isPasswordValid(encodedPassword, rawPassword.toString(), null);
        }
    };
}
</code>```

I had same problem and it worked for me.

Hope it helps you!

Body:
I have a project for LDAP authentication with REST service. My LDAP configuration have Salted SHA (SSHA) password hash method. In Spring's LDAP authentication best practice guide supporting SHA method when I used that I got bad credentials while crendentials are ok.

My configuration class reference:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .ldapAuthentication()
                .userSearchFilter("uid={0}")
                .contextSource(contextSource())
                .passwordCompare()
                    .passwordEncoder(new LdapShaPasswordEncoder())
                    .passwordAttribute("userPassword");
    }

    @Bean
    public DefaultSpringSecurityContextSource contextSource() {
        return new DefaultSpringSecurityContextSource(Arrays.asList("ldap://localhost:8389/"), "dc=springframework,dc=org");
    }
}

My ldif configuration;

dn: uid=ben,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Ben Alex
sn: Alex
uid: ben
userPassword: {SSHA}pcFdFhO/NS98EhTRup60PMkHMWFRDkJ3jUu1Zg==

My original password is Test1234. My pom.xml file ;

   <dependency>
       <groupId>org.springframework.ldap</groupId>
       <artifactId>spring-ldap-core</artifactId>
   </dependency>
   <dependency>
       <groupId>org.springframework.security</groupId>
       <artifactId>spring-security-ldap</artifactId>
   </dependency>
   <dependency>
       <groupId>com.unboundid</groupId>
       <artifactId>unboundid-ldapsdk</artifactId>
   </dependency>

How can I authenticate with my username/password to ldap server with SSHA password encryption?

Body:
Try this approach

auth
        .ldapAuthentication()
            .userSearchFilter("uid={0}")
            .contextSource(contextSource())
            .passwordCompare().passwordAttribute("userPassword")
            .and()
            .passwordEncoder(passwordEncoder());

And create a custom password encoder

private PasswordEncoder passwordEncoder() {
    final LdapShaPasswordEncoder sha = new LdapShaPasswordEncoder();
    return new PasswordEncoder() {
        @Override
        public String encode(CharSequence rawPassword) {
            return sha.encodePassword(rawPassword.toString(), null);
        }
        @Override
        public boolean matches(CharSequence rawPassword, String encodedPassword) {
            return sha.isPasswordValid(encodedPassword, rawPassword.toString(), null);
        }
    };
}

I had same problem and it worked for me.

Hope it helps you!


问:
React - importing images
I want to have a global variable or something else so that i can easily change path if i need to. I would also like to have a different path when when i build it.

Is there a better way to import without using require?

```<code>  const URL="./../../img";

 //withURL doesn't work
    export const logo1 = require(URL+ "/Global/logo1.png");

//this works but too long
    export const logo2 = require("./../../img/Editorial/logo2.jpg");
</code>```

Any idea? Is there a way in webpack that i can set this up?

Here is my webpack:

```<code>var webpack = require("webpack");
var path = require("path");

var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require("html-webpack-plugin");

var extractPlugin = new ExtractTextPlugin({
    filename: "App.css"
});

module.exports = {
    entry: './src/js/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'app.bundle.js',

    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ['react', 'es2015']
                        }
                    }
                ]
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    use: ['css-loader']
                })
            },
            {
                test: /\.html$/,
                use: ['html-loader']
            },
            {
                test: /\.(png|jpg|svg)$/,
                use: [
                        {
                            loader: 'file-loader',
                            options: {
                                name:'[name].[ext]',
                                outputPath: 'img/'
                            }
                        }
                    ]
            }
        ],
    },
    plugins: [
        extractPlugin,
        new HtmlWebpackPlugin({
            template: 'src/index.html'
        })
    ]
};
</code>```

答:
This is something done through webpack with the url-loader plugin.

This plugin allows you to require a resource, like an image, and it returns a url for it.

```<code>import imageUrl from './url/image.png';

console.log(imageUrl) // "/public/path/0dcbbaa7013869e351f.png"
</code>```

The url is the content hash of the resource, so that it can be long-term cached.

However, you also want that the path to the resource is generated on runtime. If you are using ES6 modules, you can't do that (well, you can using this syntax https://webpack.js.org/api/module-methods/#import-), but from your example, it seems you aren't since you use require. In that case, if you have correctly configured the url-loader, it seems your issue is with

```<code>const URL="./../../img";
export const logo1 = require(URL+ "/Global/logo1");
</code>```

the path does not end on .png or some extension that has been defined in your webpack config. Did you try adding .jpg?

Title: React - importing images

Body:
I want to have a global variable or something else so that i can easily change path if i need to. I would also like to have a different path when when i build it.

Is there a better way to import without using require?

  const URL="./../../img";

 //withURL doesn't work
    export const logo1 = require(URL+ "/Global/logo1.png");

//this works but too long
    export const logo2 = require("./../../img/Editorial/logo2.jpg");

Any idea? Is there a way in webpack that i can set this up?

Here is my webpack:

var webpack = require("webpack");
var path = require("path");

var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require("html-webpack-plugin");

var extractPlugin = new ExtractTextPlugin({
    filename: "App.css"
});

module.exports = {
    entry: './src/js/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'app.bundle.js',

    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ['react', 'es2015']
                        }
                    }
                ]
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    use: ['css-loader']
                })
            },
            {
                test: /\.html$/,
                use: ['html-loader']
            },
            {
                test: /\.(png|jpg|svg)$/,
                use: [
                        {
                            loader: 'file-loader',
                            options: {
                                name:'[name].[ext]',
                                outputPath: 'img/'
                            }
                        }
                    ]
            }
        ],
    },
    plugins: [
        extractPlugin,
        new HtmlWebpackPlugin({
            template: 'src/index.html'
        })
    ]
};

Body:
This is something done through webpack with the url-loader plugin.

This plugin allows you to require a resource, like an image, and it returns a url for it.

import imageUrl from './url/image.png';

console.log(imageUrl) // "/public/path/0dcbbaa7013869e351f.png"

The url is the content hash of the resource, so that it can be long-term cached.

However, you also want that the path to the resource is generated on runtime. If you are using ES6 modules, you can't do that (well, you can using this syntax https://webpack.js.org/api/module-methods/#import-), but from your example, it seems you aren't since you use require. In that case, if you have correctly configured the url-loader, it seems your issue is with

const URL="./../../img";
export const logo1 = require(URL+ "/Global/logo1");

the path does not end on .png or some extension that has been defined in your webpack config. Did you try adding .jpg?


问:
struct.unpack not returning strings
Here is my code (py3.1):

```<code>def get_string(self,chars):
    return struct.unpack("{}s".format(chars),self.get_bin(chars))
</code>```

b'MESH' is going in, (b'MESH',) is coming out. Why am I not getting a string?

答:
It helps when asking questions if you make sure that the code is actually what you did run. What you show would have given an error. Also ensure that the code snippet includes all information so that people don't need to guess.

```<code>>>> chars = "MESH" # guess
>>> binchars = b"MESH" # guess
>>> struct_fmt = "{}s".format(chars) # what you showed
>>> struct_fmt
'MESHs' ############### won't work
>>> import struct
>>> struct.unpack(struct_fmt, binchars)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
struct.error: bad char in struct format ############ didn't work
>>> struct_fmt2 = "{}s".format(len(chars)) # what you probably did use
>>> struct_fmt2
'4s' #### looks much better
>>> struct.unpack(struct_fmt2, binchars)
(b'MESH',) ### did work
>>>
</code>```

As the manual says, "For unpacking, the resulting bytes object ..."

Title: struct.unpack not returning strings

Body:
Here is my code (py3.1):

def get_string(self,chars):
    return struct.unpack("{}s".format(chars),self.get_bin(chars))

b'MESH' is going in, (b'MESH',) is coming out. Why am I not getting a string?

Body:
It helps when asking questions if you make sure that the code is actually what you did run. What you show would have given an error. Also ensure that the code snippet includes all information so that people don't need to guess.

>>> chars = "MESH" # guess
>>> binchars = b"MESH" # guess
>>> struct_fmt = "{}s".format(chars) # what you showed
>>> struct_fmt
'MESHs' ############### won't work
>>> import struct
>>> struct.unpack(struct_fmt, binchars)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
struct.error: bad char in struct format ############ didn't work
>>> struct_fmt2 = "{}s".format(len(chars)) # what you probably did use
>>> struct_fmt2
'4s' #### looks much better
>>> struct.unpack(struct_fmt2, binchars)
(b'MESH',) ### did work
>>>

As the manual says, "For unpacking, the resulting bytes object ..."


问:
How do I assert nil presence of flash variables with Cucumber-Capybara?
I'm running a Rails 3.0.7 project with Cucumber and Capybara and I have a step definition that checks if a flash[:error] exists:

```<code>Then /^I should be able to see the main page properly$/ do
    current_path.should == "/"
    flash[:error].should == nil
end
</code>```

When I run my cucumber test, I get an error

```<code>And I should be able to see the main page properly # features/step_definitions/user_auth_steps.rb:17
  undefined method `flash' for nil:NilClass (NoMethodError)
  ./features/step_definitions/user_auth_steps.rb:19:in `/^I should be able to see the main page properly$/'
  features/user_auth.feature:10:in `And I should be able to see the main page properly'
</code>```

Is this the correct way of handling variable assertions? I've noticed that if I were to use sessions[:something], the same type of error happens.

答:
To assert that there is no flash message set (of any type), you can do:

```<code>assert_predicate flash, :empty?
</code>```

To assert that there is no flash message of a particular type set (:error in this example), you can do:

```<code>assert_predicate flash[:error], :nil?
</code>```

Body:
I'm running a Rails 3.0.7 project with Cucumber and Capybara and I have a step definition that checks if a flash[:error] exists:

Then /^I should be able to see the main page properly$/ do
    current_path.should == "/"
    flash[:error].should == nil
end

When I run my cucumber test, I get an error

And I should be able to see the main page properly # features/step_definitions/user_auth_steps.rb:17
  undefined method `flash' for nil:NilClass (NoMethodError)
  ./features/step_definitions/user_auth_steps.rb:19:in `/^I should be able to see the main page properly$/'
  features/user_auth.feature:10:in `And I should be able to see the main page properly'

Is this the correct way of handling variable assertions? I've noticed that if I were to use sessions[:something], the same type of error happens.

Body:
To assert that there is no flash message set (of any type), you can do:

assert_predicate flash, :empty?

To assert that there is no flash message of a particular type set (:error in this example), you can do:

assert_predicate flash[:error], :nil?


问:
If functions are objects in JavaScript, then why can't they have name-value pair syntax for their properties?
If functions are objects in javascript, then why can't they have name-value pair syntax for their properties? For example, why is the following not possible/allowed?

```<code>function xx() {
    name: 'jhg'
}
alert(xx.name);
</code>```

and vice versa:

```<code>var person = {
    this.age = 32;
};
alert(person.age);
</code>```

答:
Because function declarations aren't object initializers. They're just different syntaxes, for different purposes, with different use cases and design criteria. Arrays are also objects, but we use a different initializer notation for them, too. Same with regular expressions.

(Note that your first example is perfectly valid and will run; name is a label, not a property name, and labels an ExpressionStatement that isn't used for anything.)

(Also note that functions do, as of ES2015, have a built-in name property. That's just not how you initialize it. [That function's name will be "xx" in your example.])

Body:
If functions are objects in javascript, then why can't they have name-value pair syntax for their properties? For example, why is the following not possible/allowed?

function xx() {
    name: 'jhg'
}
alert(xx.name);

and vice versa:

var person = {
    this.age = 32;
};
alert(person.age);


问:
Behavior of const auto pointers in C++
This answer claims that a const auto pointer behaves the same as a const 'regular' (i.e., non-auto) pointer, which is what I would expect.

However, the following code compiles and outputs 100:

```<code>int n{ 99 };
const auto nPtr = &n;
++(*nPtr);
std::cout << n << '\n';
</code>```

To dig a little deeper, I checked the types of all 4 kinds of pointers and this is the result I got:

Code

```<code>int n{ 99 };

int* intPtr = &n;
const int* intConstPtr = &n;

auto autoPtr = &n;
const auto autoConstPtr = &n;

std::cout << "intPtr: " << typeid(intPtr).name() << '\n';
std::cout << "intConstPtr: " << typeid(intConstPtr).name() << '\n';

std::cout << "autoPtr: " << typeid(autoPtr).name() << '\n';
std::cout << "autoConstPtr: " << typeid(autoConstPtr).name() << '\n';
</code>```

Output

intPtr: int * __ptr64

intConstPtr: int const * __ptr64

autoPtr: int * __ptr64

autoConstPtr: int * __ptr64

So the compiler seems to be completely ignoring the const keyword with the auto pointer. Does anyone know why this is?

答:
Here, const auto is being converted to int *const, not const int*. The difference is that it’s a constant pointer to a (variable) int, not a (variable) pointer to a constant int. In this case, that means you can do ++(*nPtr);, as you do, but you cannot change nPtr to point to a different int.

To see this, try adding the lines

```<code>int i{ 17 };
nPtr = &i
</code>```

The four variants of int pointers with different const qualification, specified without auto, are:

int*: A modifiable pointer to a modifiable int. You can change which int it points to, and you can use it to change the value of that int. This is what you get with just auto nPtr = &n.

int *const: A fixed pointer to a modifiable int. It will always point to the same int, but you can use it to change the value of that int. This is what you get with const auto nPtr = &n or auto const nPtr = &n.

int const * or const int*: A modifiable pointer to a constant int. You can change which int it points to, but you cannot use it to change the value of that int.

int const *const or const int *const: A constant pointer to a constant int. You cannot change which int it points to, and you cannot use it to change the value of that int.

Title: Behavior of const auto pointers in C++

Body:
This answer claims that a const auto pointer behaves the same as a const 'regular' (i.e., non-auto) pointer, which is what I would expect.

However, the following code compiles and outputs 100:

int n{ 99 };
const auto nPtr = &n;
++(*nPtr);
std::cout << n << '\n';

To dig a little deeper, I checked the types of all 4 kinds of pointers and this is the result I got:

Code

int n{ 99 };

int* intPtr = &n;
const int* intConstPtr = &n;

auto autoPtr = &n;
const auto autoConstPtr = &n;

std::cout << "intPtr: " << typeid(intPtr).name() << '\n';
std::cout << "intConstPtr: " << typeid(intConstPtr).name() << '\n';

std::cout << "autoPtr: " << typeid(autoPtr).name() << '\n';
std::cout << "autoConstPtr: " << typeid(autoConstPtr).name() << '\n';

Output

intPtr: int * __ptr64

intConstPtr: int const * __ptr64

autoPtr: int * __ptr64

autoConstPtr: int * __ptr64

So the compiler seems to be completely ignoring the const keyword with the auto pointer. Does anyone know why this is?

Body:
Here, const auto is being converted to int *const, not const int*. The difference is that it’s a constant pointer to a (variable) int, not a (variable) pointer to a constant int. In this case, that means you can do ++(*nPtr);, as you do, but you cannot change nPtr to point to a different int.

To see this, try adding the lines

int i{ 17 };
nPtr = &i

The four variants of int pointers with different const qualification, specified without auto, are:

int*: A modifiable pointer to a modifiable int. You can change which int it points to, and you can use it to change the value of that int. This is what you get with just auto nPtr = &n.

int *const: A fixed pointer to a modifiable int. It will always point to the same int, but you can use it to change the value of that int. This is what you get with const auto nPtr = &n or auto const nPtr = &n.

int const * or const int*: A modifiable pointer to a constant int. You can change which int it points to, but you cannot use it to change the value of that int.

int const *const or const int *const: A constant pointer to a constant int. You cannot change which int it points to, and you cannot use it to change the value of that int.


问:
Extract information from all matching nodes without looping xpath
```<code><ul class="products-grid">
    <li class="item">
        <div class="product-block">
            <div class="product-block-inner">
                <a href="#" title="Product A" class="product-image"><img src="#/producta.jpg"></a>
                <h2 class="product-name"><a href="#">Product A</a></h2>
                <div class="price-box">
                    <span class="regular-price" id="#">
                        <span class="price">Rs 1,849</span>
                    </span>
                </div>
            </div>
        </div>
    </li>
    <li class="item">
        <div class="product-block">
            <div class="product-block-inner">
                <a href="#" title="Product B" class="product-image"><img src="#/productb.jpg"></a>
                <h2 class="product-name"><a href="#">Product B</a></h2>
                <div class="price-box">
                    <span class="regular-price" id="#">
                        <span class="price">Rs 1,849</span>
                    </span>
                </div>
            </div>
        </div>
    </li>
</ul>
</code>```

I am at this moment scraping the item in a loop.

```<code>products = response.xpath('//ul[@class="products-grid"]//li//div[@class="product-block"]//div[@class="product-block-inner"]').extract()
</code>```

After getting the product-block-inner node, I save it into products and then I will have to loop like

```<code>for product in products:
   // parse the div.product-block-inner further deep down
   // to get name, price, image etc
   // and save it to a dict and yeild
   pass
</code>```

Is this possible that i get text, href for all div.product-block-inner in the final list without looping

答:
Yes, but it's very confusing, for example you could try this:

```<code>products = response.xpath(
    '//ul[@class="products-grid"]//li//div[@class="product-block"]//div[@class="product-block-inner"]'
).css(
    '.product-name a::attr(href), .product-name a::text, .price::text'
).extract()
</code>```

but I would suggest to always loop (btw, why do you call extract() when you assign it to products?)

```<code>products = response.xpath(
    '//ul[@class="products-grid"]//li//div[@class="product-block"]//div[@class="product-block-inner"]'
)
for product in products:
    yield {'name': product.css('.product-name a::text').extract_first()
           'url': product.css('.product-name a::attr(href)').extract_first()
           'price': product.css('.price::text').extract_first()}
</code>```

(I've used css selectors in this case because the equivalent xpaths are longer, but the same can also be achieved using xpath)

Body:
Product A

                        Rs 1,849

Product B

                        Rs 1,849

I am at this moment scraping the item in a loop.

products = response.xpath('//ul[@class="products-grid"]//li//div[@class="product-block"]//div[@class="product-block-inner"]').extract()

After getting the product-block-inner node, I save it into products and then I will have to loop like

for product in products:
   // parse the div.product-block-inner further deep down
   // to get name, price, image etc
   // and save it to a dict and yeild
   pass

Is this possible that i get text, href for all div.product-block-inner in the final list without looping

Body:
Yes, but it's very confusing, for example you could try this:

products = response.xpath(
    '//ul[@class="products-grid"]//li//div[@class="product-block"]//div[@class="product-block-inner"]'
).css(
    '.product-name a::attr(href), .product-name a::text, .price::text'
).extract()

but I would suggest to always loop (btw, why do you call extract() when you assign it to products?)

products = response.xpath(
    '//ul[@class="products-grid"]//li//div[@class="product-block"]//div[@class="product-block-inner"]'
)
for product in products:
    yield {'name': product.css('.product-name a::text').extract_first()
           'url': product.css('.product-name a::attr(href)').extract_first()
           'price': product.css('.price::text').extract_first()}

(I've used css selectors in this case because the equivalent xpaths are longer, but the same can also be achieved using xpath)


问:
Socket connection fails to send data
I have a long running TCP connection. A machine (IoT device) establishes a connection with the server, connection is setup (encryption and stuff) and data stored, connection is kept open a while.

Everything kind of works but sometimes the server 'drops' the connection with an error:
An established connection was aborted by the software in your host machine (code: 10053 - ConnectionAborted). But the connection isn't dropped, cause server can read data from the device after the error and could start sending again. If the connection drops in real, both the server and client need to reinitialize connection (security and stuff).

There is nothing really that indicates why network stream cannot be written to.
And polling the socket says, that it's writetable, and in next point it throws an exception. Seems to happen randomly.

```<code>public class ClientIdentifier
{
    ...
    public TcpClient Connection { get; set; }
    public BlockDecoder ConnectionDecoder { get; set; }
}

private void ReplyToClient(ClientIdentifier client, byte[] data)
{
    byte[] encrypted = client.ConnectionDecoder.Encrypt(data);
    var stream = client.Connection.GetStream();

    int dataIndex = 0;

    while (dataIndex != encrypted.Length)
    {
        if (CanWriteClient(client))
        {
            byte[] block = encrypted.GetChunk(dataIndex, Frame.BLOCK_LENGTH);

            stream.Write(block, 0, Frame.BLOCK_LENGTH);

            dataIndex += Frame.BLOCK_LENGTH;
        }
    }
}

private bool CanWriteClient(ClientIdentifier client)
{
    try
    {
        return client.Connection.Client.Poll(1000, SelectMode.SelectWrite);
    }
    catch (Exception ex)
    {
        Logger.Warn(ex, $"[{client.HexIdentifier}]: Polling client write failed");
        return false;
    }
}
</code>```

EDIT (12.11.2017)

Server: 192.168.1.150
Device: 192.168.1.201

I can see that the device sends RST when the server resets Seq and Ack in some weird way.

答:
Managed to find the mistake. Timeout was set to way too low.</p>

```<code>...
TcpClient client = server.EndAcceptTcpClient(ar);

int timeout = (int)TimeSpan.FromSeconds(3).TotalMilliseconds;

client.ReceiveTimeout = timeout;
client.SendTimeout = timeout;
...
</code>```

Title: Socket connection fails to send data

Body:
I have a long running TCP connection. A machine (IoT device) establishes a connection with the server, connection is setup (encryption and stuff) and data stored, connection is kept open a while.

Everything kind of works but sometimes the server 'drops' the connection with an error:
An established connection was aborted by the software in your host machine (code: 10053 - ConnectionAborted). But the connection isn't dropped, cause server can read data from the device after the error and could start sending again. If the connection drops in real, both the server and client need to reinitialize connection (security and stuff).

There is nothing really that indicates why network stream cannot be written to.
And polling the socket says, that it's writetable, and in next point it throws an exception. Seems to happen randomly.

public class ClientIdentifier
{
    ...
    public TcpClient Connection { get; set; }
    public BlockDecoder ConnectionDecoder { get; set; }
}

private void ReplyToClient(ClientIdentifier client, byte[] data)
{
    byte[] encrypted = client.ConnectionDecoder.Encrypt(data);
    var stream = client.Connection.GetStream();

    int dataIndex = 0;

    while (dataIndex != encrypted.Length)
    {
        if (CanWriteClient(client))
        {
            byte[] block = encrypted.GetChunk(dataIndex, Frame.BLOCK_LENGTH);

            stream.Write(block, 0, Frame.BLOCK_LENGTH);

            dataIndex += Frame.BLOCK_LENGTH;
        }
    }
}

private bool CanWriteClient(ClientIdentifier client)
{
    try
    {
        return client.Connection.Client.Poll(1000, SelectMode.SelectWrite);
    }
    catch (Exception ex)
    {
        Logger.Warn(ex, $"[{client.HexIdentifier}]: Polling client write failed");
        return false;
    }
}

EDIT (12.11.2017)

Server: 192.168.1.150
Device: 192.168.1.201

I can see that the device sends RST when the server resets Seq and Ack in some weird way.

Body:
Managed to find the mistake. Timeout was set to way too low.

...
TcpClient client = server.EndAcceptTcpClient(ar);

int timeout = (int)TimeSpan.FromSeconds(3).TotalMilliseconds;

client.ReceiveTimeout = timeout;
client.SendTimeout = timeout;
...


问:
Android Studio 3.1 Canary 3 - Gradle sync failed
For a unknown reason Android Studio 3.1 Canary 3 is bugged and stopped to work, I updated gradle to 3.1-alpha03 and it stopped working, no matter if I download the project again, already downloaded Android Studio again too.

I've already checkout old versions of the project, but this message still show:

```<code>Gradle sync failed: com.android.tools.idea.gradle.project.model.AndroidModuleModel.getSelectedVariant()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeVariant; (8s 806ms)
</code>```

I've removed .idea folder, .gradle folder, did invalidate and restart

I don't know nothing more to do, cant run or use the IDE.

Edit:

Edit2:

New Projects doesnt work too

答: roll back  to the  previous  gradle version i have  faced  such issues  myself and  stay  away from RC gradle version unless  really  needed.</p>

Body:
For a unknown reason Android Studio 3.1 Canary 3 is bugged and stopped to work, I updated gradle to 3.1-alpha03 and it stopped working, no matter if I download the project again, already downloaded Android Studio again too.

I've already checkout old versions of the project, but this message still show:

Gradle sync failed: com.android.tools.idea.gradle.project.model.AndroidModuleModel.getSelectedVariant()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeVariant; (8s 806ms)

I've removed .idea folder, .gradle folder, did invalidate and restart

I don't know nothing more to do, cant run or use the IDE.

Edit:

Edit2:

New Projects doesnt work too


问:
how to get message authentication code for BouncyCastle AES-CCM encrypted message
I have encrypted some text as follows:

```<code>Cipher in = Cipher.getInstance("AES/CCM/NoPadding", "BC");
in.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(_nonce));
encoded = in.doFinal(payload);
</code>```

Works great. I want to get the MAC, so I try this:

```<code>byte[] K = Hex.decode(bek.getBytes());
Key key = new SecretKeySpec(K, "AES");
Mac mac = Mac.getInstance("AES/CCM/NoPadding", "BC");
</code>```

but get a "no such algorithm: AES/CCM/NoPadding for provider BC".

So, what algorithm is used to extract the MAC from an AES/CCM encrypted message? Thanks!

答: The CCM mode implies the use of the CBC block cipher MAC for AES, so that's the algorithm you should be using, but I haven't written code which uses this myself.  I know that BouncyCastle implements this with the CBCBlockCipherMac class, but I'm not 100% sure of the correct algorithm name, but looking in the sourcecode it appears to be "AESMac" (which uses CBC mode and zero-padding by default).</p>

Body:
I have encrypted some text as follows:

Cipher in = Cipher.getInstance("AES/CCM/NoPadding", "BC");
in.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(_nonce));
encoded = in.doFinal(payload);

Works great. I want to get the MAC, so I try this:

byte[] K = Hex.decode(bek.getBytes());
Key key = new SecretKeySpec(K, "AES");
Mac mac = Mac.getInstance("AES/CCM/NoPadding", "BC");

but get a "no such algorithm: AES/CCM/NoPadding for provider BC".

So, what algorithm is used to extract the MAC from an AES/CCM encrypted message? Thanks!


问:
Format String to add \n before showing it in alert?
I have the following String which is coming from the backend and I need to format the string before showing it in the alert message.

How we can do that using Apex code or using JavaScript code? How we can put \n for each ., • and o?

Try adding the above to your web page, then load the page and see if it works. If it doesn't, you probably have a bug. Specifically, please:  • Be sure you typed everything exactly as it appears,:    o Third Party Details   • Upload the following documents in the Requestor Required Documentation section:    o Proposal    o Relevant Documentation

I am using Visualforce pages and Controller.

```<code>    <!DOCTYPE html>
    <html>
    <body>

    <h2>JavaScript Alert</h2>

    <button onclick="myFunction()">Try it</button>

    <script>
    function myFunction() {
        alert("Try adding the above to your web page, then load the page and see if it works.
If it doesn't, you probably have a bug.\n Specifically, please:\n
• Be sure you typed everything exactly as it appears,:\n
o Third Party Details   \n• Upload the following documents in the Requestor
Required Documentation section:      \no Proposal     \no Relevant Documentation");
    }
    </script>

</body>
</html>
</code>```

I have already formatted code using object.field.stripHtmlTags();

Shown alert should be like below. But how to split String for ., • and o and add \n using apex?

答:
You can try by using javascript replace function

for example :

    var str = "Try adding the above to your web page, then load the page and see if it works. If it doesn't works";
    var newStr = str.replace(".", '.\n');
    alert(newStr);```

Body:
I have the following String which is coming from the backend and I need to format the string before showing it in the alert message.

How we can do that using Apex code or using JavaScript code? How we can put \n for each ., • and o?

Try adding the above to your web page, then load the page and see if it works. If it doesn't, you probably have a bug. Specifically, please:  • Be sure you typed everything exactly as it appears,:    o Third Party Details   • Upload the following documents in the Requestor Required Documentation section:    o Proposal    o Relevant Documentation

I am using Visualforce pages and Controller.

    <!DOCTYPE html>

JavaScript Alert

    <button onclick="myFunction()">Try it</button>

I have already formatted code using object.field.stripHtmlTags();

Shown alert should be like below. But how to split String for ., • and o and add \n using apex?


答:
They are objects, but they are not object literals.

A function can be used to create an instance of an object. For example:

```<code>function Person(name, age) {
    this.name = name;
    this.age = age;
    this.sayHello = function() {
        console.log('Hi, my name is ' + this.name);
    };
}

var bob = new Person('Bob', 24);
</code>```

The bob variable is an instance of the Person function.
You can access the properties from bob like this:

```<code>console.log( bob.name ) // "Bob"
</code>```

You could also define it literally, like this:

```<code>var bob = {
    name: 'Bob',
    age: 24
};
</code>```

The function syntax is used to create functions. They are templates that can be used over and over again. The object literal syntax is used when you only want one instance, or also for data, without any behavior attached to it.

Title: If functions are objects in JavaScript, then why can't they have name-value pair syntax for their properties?

Body:
They are objects, but they are not object literals.

A function can be used to create an instance of an object. For example:

function Person(name, age) {
    this.name = name;
    this.age = age;
    this.sayHello = function() {
        console.log('Hi, my name is ' + this.name);
    };
}

var bob = new Person('Bob', 24);

The bob variable is an instance of the Person function.
You can access the properties from bob like this:

console.log( bob.name ) // "Bob"

You could also define it literally, like this:

var bob = {
    name: 'Bob',
    age: 24
};

The function syntax is used to create functions. They are templates that can be used over and over again. The object literal syntax is used when you only want one instance, or also for data, without any behavior attached to it.


问:
How can I implement prepend and append with regular JavaScript?
How can I implement prepend and append with regular JavaScript without using jQuery?</p>

答:
In 2017 I know for Edge 15 and IE 12, the prepend method isn't included as a property for Div elements, but if anyone needs a quick reference to polyfill a function I made this:

```<code> HTMLDivElement.prototype.prepend = (node, ele)=>{
               try { node.insertBefore(ele ,node.children[0]);}
                     catch (e){ throw new Error(e.toString()) } }
</code>```

Simple arrow function that's compatible with most modern browsers.

Body:
In 2017 I know for Edge 15 and IE 12, the prepend method isn't included as a property for Div elements, but if anyone needs a quick reference to polyfill a function I made this:

 HTMLDivElement.prototype.prepend = (node, ele)=>{
               try { node.insertBefore(ele ,node.children[0]);}
                     catch (e){ throw new Error(e.toString()) } }

Simple arrow function that's compatible with most modern browsers.


问:
Can request YARN containers of different resource capabilities in a tight loop?
I am writing a native YARN application following the model of the distributed shell application. In my application master I am requesting two containers using the usual looping as follows:

```<code>for (int i = 0; i < appContainerList.size(); ++i)
{
  ContainerRequest containerAsk = setupContainerAskForRM(i);
  amRMClient.addContainerRequest(containerAsk);
  appContainerList.setStatus(i, "requested");
}
</code>```

As long as the two containers request the same amount of memory, say either 512 or 1000, then shortly after this loop runs I get a callback to the onContainersAllocated method of my AMRMClientAsync.CallbackHandler with a list of two allocated containers that were allocated. This also happens if I ask for more than two containers with the same resource allocation, but I am keeping it to two here so that the demonstration of the issue is simplified.

However, if I make the requests for different capabilities, say one for 512 and the other for 1000, then I also get a callback but only one container is allocated, and I never get a call back for the second container request.

I know that the communication between the AMRMClientAsync and the RM rides on top of heartbeats that are sent every second, so I tried inserting a sleep between the two container requests and now I get two callbacks, each with one allocated container.

Here is my code with a sleep.

```<code>for (int i = 0; i < appContainerList.size(); ++i)
{
  ContainerRequest containerAsk = setupContainerAskForRM(i);
  amRMClient.addContainerRequest(containerAsk);
  appContainerList.setStatus(i, "requested");
  try
  {
    Thread.sleep(5000);
  }
  catch (InterruptedException ex)
  {
    LOG.info("sleep interrupted " + ex);
  }
}
</code>```

It this correct, is it impossible to request containers with different resource capabilities in a tight loop? Do requests for containers with different resource capabilities require a sleep in between so they don’t end up riding the same heartbeat same communication to the RM?

If so, this seems to mean that if I have many different container types, with different resource capabilities, I have to group them and make sure that requests for different types have at least one heartbeat between them. This is much more complicated than simply requesting the containers in a tight loop without regard to the resource capabilities each one is requesting.

I found a related post here: post by yihee and a JIRA here: YARN-314.

The answer to my question appears to be, as it says in YARN-314:
"Currently, resource requests for the same container and locality are expected to all be the same size." Therefore to request containers of different resource requirements in a tight loop they must have different priorities if the resources requested are different.

答: Answering my own question. Based on the other references I mentioned, especially YARN-314, I changed the priorities of the containers I requested and now I can request the containers in a tight loop and I get both containers allocated in the same call to my onContainersAllocated callback handler.</p>

Body:
I am writing a native YARN application following the model of the distributed shell application. In my application master I am requesting two containers using the usual looping as follows:

for (int i = 0; i < appContainerList.size(); ++i)
{
  ContainerRequest containerAsk = setupContainerAskForRM(i);
  amRMClient.addContainerRequest(containerAsk);
  appContainerList.setStatus(i, "requested");
}

As long as the two containers request the same amount of memory, say either 512 or 1000, then shortly after this loop runs I get a callback to the onContainersAllocated method of my AMRMClientAsync.CallbackHandler with a list of two allocated containers that were allocated. This also happens if I ask for more than two containers with the same resource allocation, but I am keeping it to two here so that the demonstration of the issue is simplified.

However, if I make the requests for different capabilities, say one for 512 and the other for 1000, then I also get a callback but only one container is allocated, and I never get a call back for the second container request.

I know that the communication between the AMRMClientAsync and the RM rides on top of heartbeats that are sent every second, so I tried inserting a sleep between the two container requests and now I get two callbacks, each with one allocated container.

Here is my code with a sleep.

for (int i = 0; i < appContainerList.size(); ++i)
{
  ContainerRequest containerAsk = setupContainerAskForRM(i);
  amRMClient.addContainerRequest(containerAsk);
  appContainerList.setStatus(i, "requested");
  try
  {
    Thread.sleep(5000);
  }
  catch (InterruptedException ex)
  {
    LOG.info("sleep interrupted " + ex);
  }
}

It this correct, is it impossible to request containers with different resource capabilities in a tight loop? Do requests for containers with different resource capabilities require a sleep in between so they don’t end up riding the same heartbeat same communication to the RM?

If so, this seems to mean that if I have many different container types, with different resource capabilities, I have to group them and make sure that requests for different types have at least one heartbeat between them. This is much more complicated than simply requesting the containers in a tight loop without regard to the resource capabilities each one is requesting.

I found a related post here: post by yihee and a JIRA here: YARN-314.

The answer to my question appears to be, as it says in YARN-314:
"Currently, resource requests for the same container and locality are expected to all be the same size." Therefore to request containers of different resource requirements in a tight loop they must have different priorities if the resources requested are different.