问:
jQuery child and ancestor selector not working in IE 8
In jQuery, child selectors supposedly work in IE 7+, but a particular selector path is not working for me in IE 8.  Given the following code:

```<code><html>
  <head>
    <script type="text/javascript" src="jquery-min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $('.a > div a').text("Found!");
      });
    </script>
  </head>
  <body>
    <div class="a">
      <div>
        <div>
          <a href="#">Not Found</a>
        </div>
      </div>
    </div>
  </body>
</html>
</code>```

"Not Found" remains in the  element.  If I remove one of the divs, the selector does work.  Is my selector incorrect, or is this a known or discovered jQuery bug?  We're using version 1.4.1, but I just verified the same behavior occurs in jQuery 1.4.4.

答:
Unfortunatly, I don't have a windows machine right now. But if it really is not working in IE8 you probably should fill a bug.

Anyway, to avoid the selector you can always use

```<code>$('.a > div').find('a').text('Found!');
</code>```

Body:
In jQuery, child selectors supposedly work in IE 7+, but a particular selector path is not working for me in IE 8.  Given the following code:

          Not Found

"Not Found" remains in the  element.  If I remove one of the divs, the selector does work.  Is my selector incorrect, or is this a known or discovered jQuery bug?  We're using version 1.4.1, but I just verified the same behavior occurs in jQuery 1.4.4.

Body:
Unfortunatly, I don't have a windows machine right now. But if it really is not working in IE8 you probably should fill a bug.

Anyway, to avoid the selector you can always use

$('.a > div').find('a').text('Found!');


来源: stackexchange

问:
Coupons doesn't work in opencart
i am doing an updation in an opencart project.we create coupons that will apply a rebate.  it is included in checkout page.  we are adding this coupon details like coupon code,discount,exp date etc  from admin side.but nothing happens on user side.  while entering coupon code nothing happens.  no reduction in price and also we didn't get any error message.</p>

答:
Following on from John's answer... In catalog/model/total/coupon.php I swapped out

```<code>// If discount greater than total
if ($discount_total > $total) {
    $discount_total = $total;
}
</code>```

For:

```<code>// If discount greater than total
if ($coupon_info['type'] == 'F' && $discount_total > $subtotal) {
    $discount_total = $subtotal;
}
</code>```

Hope no one else ever has to debug this one!!!

ContentLicense: CC BY-SA 3.0

Title: Coupons doesn't work in opencart

Body:
Following on from John's answer... In catalog/model/total/coupon.php I swapped out

// If discount greater than total
if ($discount_total > $total) {
    $discount_total = $total;
}

For:

// If discount greater than total
if ($coupon_info['type'] == 'F' && $discount_total > $subtotal) {
    $discount_total = $subtotal;
}

Hope no one else ever has to debug this one!!!


问:
Sending a single-packet HTTP response in Node.js
To show my students a simple HTTP request and response that they could capture using Wireshark, I whipped up a simple Node.js HTTP server:

```<code>var fs = require('fs');
var http = require('http');

var port = 80;
var file = process.argv[2]; //This file contains a 42 byte HTML page

http.createServer(function (req, res) {
  res.writeHead(200, { 'content-type' : 'text/html' }); // Sends first packet
  fs.createReadStream(file).pipe(res); // Sends second packet
}).listen(port);
</code>```

Unfortunately, the two lines transmitting the HTTP header and the HTML are sent as two separate TCP packets (even though they are both quite small). It would be simpler for my students if the HTTP header and HTML were just one packet. How could I change my code to do this?

答:
```<code>var http = require('http');
var fs = require('fs');
var file = process.argv[2];

http.createServer(function(request, response) {
    response.writeHeader(200, {"Content-Type": "text/html;"});
    fs.readFile(file, function (err, html) {
        if (err) {
            throw err;
        }
        response.write(html);
        response.end();
    });
}).listen(8000);
</code>```

the reason it won't work is that Node.js runs everything asynchronously. When you are loading your html file, the server creation starts the same time. By the time you are about to write your html to your tcp socket, the file most likely won't be ready.

I see what you were trying to do before... I misread your code because of the indentation. Let me know if this snippet works.

Body:
To show my students a simple HTTP request and response that they could capture using Wireshark, I whipped up a simple Node.js HTTP server:

var fs = require('fs');
var http = require('http');

var port = 80;
var file = process.argv[2]; //This file contains a 42 byte HTML page

http.createServer(function (req, res) {
  res.writeHead(200, { 'content-type' : 'text/html' }); // Sends first packet
  fs.createReadStream(file).pipe(res); // Sends second packet
}).listen(port);

Unfortunately, the two lines transmitting the HTTP header and the HTML are sent as two separate TCP packets (even though they are both quite small). It would be simpler for my students if the HTTP header and HTML were just one packet. How could I change my code to do this?

Body:
var http = require('http');
var fs = require('fs');
var file = process.argv[2];

http.createServer(function(request, response) {
    response.writeHeader(200, {"Content-Type": "text/html;"});
    fs.readFile(file, function (err, html) {
        if (err) {
            throw err;
        }
        response.write(html);
        response.end();
    });
}).listen(8000);

the reason it won't work is that Node.js runs everything asynchronously. When you are loading your html file, the server creation starts the same time. By the time you are about to write your html to your tcp socket, the file most likely won't be ready.

I see what you were trying to do before... I misread your code because of the indentation. Let me know if this snippet works.


问:
Sending mail with Laravel on shared hosting
I'm trying to send mail from my website.

I'm using laravel 5.5 and the shared hosting of hostnet.nl.

I'm very sure i have all my configuration correct..

My .env :

```<code>MAIL_DRIVER=mail
MAIL_HOST=smtp02.hostnet.nl
MAIL_PORT=587
MAIL_USERNAME=username
MAIL_PASSWORD=password
MAIL_ENCRYPTION=TLS
</code>```

But when i try to send mail this allways returns

Whoops there was an error:

proc_open() has been disabled for security reasons

I already chat with the hosting company and they said this is not a php setting that is allowed to be changed. So i cannot enable this.

When i try to set MAIL_DRIVER=smtp it says connection refused.

I have another laravel installation/website at this shared hosting, which has the same MAIL_DRIVER=mail and this works perfectly.

This installation is on laravel 5.2.*

Is this something that has changed inside swiftmailer from laravel 5.2 to 5.5?

I don't know how to fix this issue.

Any help is appreciated.

答:
You should try changing this :

```<code>MAIL_DRIVER=mail
</code>```

There is no "mail" driver for laravel's mailing service (Laravel 5.5), you could have problems with the "smtp" because of wrong credentials. I think Laravel 5.2 might be using php's built-in "mail()" function when the "mail" driver is set, which could work on some shared hosting and fail on other.

Most shared hosting providers allow sending via the default server "sendmail" so you could also try this :

```<code>MAIL_DRIVER=sendmail
</code>```

If you can't get "sendmail" or "smtp" to work, you could try the "mailgun" or any other external mail service provider. Mailgun for example gives you 10 000 free mails per month so you will not need any paid subscriptions and the set-up tutorials are very easy, plus you have great tools for monitoring the sent mails.

Body:
I'm trying to send mail from my website.

I'm using laravel 5.5 and the shared hosting of hostnet.nl.

I'm very sure i have all my configuration correct..

My .env :

MAIL_DRIVER=mail
MAIL_HOST=smtp02.hostnet.nl
MAIL_PORT=587
MAIL_USERNAME=username
MAIL_PASSWORD=password
MAIL_ENCRYPTION=TLS

But when i try to send mail this allways returns

Whoops there was an error:

proc_open() has been disabled for security reasons

I already chat with the hosting company and they said this is not a php setting that is allowed to be changed. So i cannot enable this.

When i try to set MAIL_DRIVER=smtp it says connection refused.

I have another laravel installation/website at this shared hosting, which has the same MAIL_DRIVER=mail and this works perfectly.

This installation is on laravel 5.2.*

Is this something that has changed inside swiftmailer from laravel 5.2 to 5.5?

I don't know how to fix this issue.

Any help is appreciated.

Body:
You should try changing this :

MAIL_DRIVER=mail

There is no "mail" driver for laravel's mailing service (Laravel 5.5), you could have problems with the "smtp" because of wrong credentials. I think Laravel 5.2 might be using php's built-in "mail()" function when the "mail" driver is set, which could work on some shared hosting and fail on other.

Most shared hosting providers allow sending via the default server "sendmail" so you could also try this :

MAIL_DRIVER=sendmail

If you can't get "sendmail" or "smtp" to work, you could try the "mailgun" or any other external mail service provider. Mailgun for example gives you 10 000 free mails per month so you will not need any paid subscriptions and the set-up tutorials are very easy, plus you have great tools for monitoring the sent mails.


问:
A VirtualBox machine with the name 'homestead' already exists
Since homestead 2.0 homestead laravel has not been working

I don't know why 'homestead init' creates a Homestead.yaml file in mydirectory/.homestead
and not in the project directory. Homestead up OR Vagrant up create the following message

A VirtualBox machine with the name 'homestead' already exists.

```<code>Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'laravel/homestead'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'laravel/homestead' is up to date...
A VirtualBox machine with the name 'homestead' already exists.
Please use another name or delete the machine with the existing
name, and try again.
</code>```

答:
Commands to execute:

```<code>vagrant box list
vagrant box remove laravel/homestead
vagrant global-status
vagrant destroy nameOfYourBox
</code>```

Open your VirtualBox and delete all itens of your homestead

```<code>vagrant up
</code>```

Body:
Since homestead 2.0 homestead laravel has not been working

I don't know why 'homestead init' creates a Homestead.yaml file in mydirectory/.homestead
and not in the project directory. Homestead up OR Vagrant up create the following message

A VirtualBox machine with the name 'homestead' already exists.

Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'laravel/homestead'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'laravel/homestead' is up to date...
A VirtualBox machine with the name 'homestead' already exists.
Please use another name or delete the machine with the existing
name, and try again.

Body:
Commands to execute:

vagrant box list
vagrant box remove laravel/homestead
vagrant global-status
vagrant destroy nameOfYourBox

Open your VirtualBox and delete all itens of your homestead

vagrant up

ContentLicense: CC BY-SA 4.0


问:
Correct syntax for javascript redirect with parameters
I need to modify the below code that, run from Submit in a Caspio form as a popup, to redirect the parent page (instead of refreshing it) and close the popup.

The current code is:

```
</div>
</div>
</p>

<p>I think something like the below is what I need but I can't get the syntax right:</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-html lang-html prettyprint-override"><code>setTimeout(function() {
        window.parent.location.href='../my-webpage?PID=[@field:PID]&PTID=[@field:PTID]'();
        window.parent.jQuery.fancybox.close();},
    2000);</code>```

Any help on this would be greatly appreciated.

答:
```<code>setTimeout(function(){
window.parent.location.href=window.location.hostname; window.parent.jQuery.fancybox.close();
}, 2000);
</code>```

Its will redirect to current domain

Then for parent by "/"

```<code>var currentURL = window.parent.location.href;
var lastDir = currentURL.substr(currentURL.lastIndexOf('/') + 1)
var parentURL = currentURL.replace(lastDir,"");

   setTimeout(function(){
    window.parent.location.href=parentURL; window.parent.jQuery.fancybox.close();
    }, 2000);
</code>```

Its will redirect to parent of domain by "/" as separator.

example my current https://stackoverflow.com/posts/parent/child

so will redirent to

https://stackoverflow.com/posts/parent

Body:
I need to modify the below code that, run from Submit in a Caspio form as a popup, to redirect the parent page (instead of refreshing it) and close the popup.

The current code is:

I think something like the below is what I need but I can't get the syntax right:

setTimeout(function() {
        window.parent.location.href='../my-webpage?PID=[@field:PID]&PTID=[@field:PTID]'();
        window.parent.jQuery.fancybox.close();},
    2000);

Any help on this would be greatly appreciated.

Body:
setTimeout(function(){
window.parent.location.href=window.location.hostname; window.parent.jQuery.fancybox.close();
}, 2000);

Its will redirect to current domain

Then for parent by "/"

var currentURL = window.parent.location.href;
var lastDir = currentURL.substr(currentURL.lastIndexOf('/') + 1)
var parentURL = currentURL.replace(lastDir,"");

   setTimeout(function(){
    window.parent.location.href=parentURL; window.parent.jQuery.fancybox.close();
    }, 2000);

Its will redirect to parent of domain by "/" as separator.

example my current https://stackoverflow.com/posts/parent/child

so will redirent to

https://stackoverflow.com/posts/parent


问:
can node HTTPS server be created without public and private keys?
I am using expressjs to create an http/https server.

There was a case wherein the server was not able to fetch the public and private certificate files from a directory.

In which case I create the server using http and send a raw HTML file to the client indicating that there was an issue, but here lies the problem,
the user does not know that they need to move to http url rather than https to see the HTML file.

So is there a way I can redirect my users to a https url when they try to access the http URL

```<code>init.js
    try {
      // options = get public and private certificate file
    } catch(e) {
      // accessError
    }

    if(accessError) {
     server = http.createServer();
    } else {
      server = https.createServer(options, (req, res) => {
         res.writeHead(200);
         res.end('hello world\n');
      });
     );
    }

server.listen(8080);

app.js

let app = require('express');

app.use((req, res, next) => {
   if(accessError) {
     res.sendFile(index.html);
   } else {
     next();
   }
});

index.html
<h1> there was an error <h1>
</code>```

答:
You can try a 301 Redirect like in the answer to this question.

Whenever somebody tries to access the http variant of a resource, they'll be redirected to the https one.

As a design decision I'd treat the inability to retrieve certificates as a fatal error. I imagine you're reading them at start time. If you can't read them for some reason, you should just terminate the application, and log an exception. You do need to have some monitoring in place to notice that the thing hasn't started and act accordingly when you can't find it. But displaying an error page seems like more trouble than it's worth. You're going to have the application in an up state, but not really. Cause it won't be able to do anything, and you'll need to rely on clients telling you that it doesn't work and there's a https related message etc. Better to fail hard.

Body:
I am using expressjs to create an http/https server.

There was a case wherein the server was not able to fetch the public and private certificate files from a directory.

In which case I create the server using http and send a raw HTML file to the client indicating that there was an issue, but here lies the problem,
the user does not know that they need to move to http url rather than https to see the HTML file.

So is there a way I can redirect my users to a https url when they try to access the http URL

init.js
    try {
      // options = get public and private certificate file
    } catch(e) {
      // accessError
    }

    if(accessError) {
     server = http.createServer();
    } else {
      server = https.createServer(options, (req, res) => {
         res.writeHead(200);
         res.end('hello world\n');
      });
     );
    }

server.listen(8080);

app.js

let app = require('express');

app.use((req, res, next) => {
   if(accessError) {
     res.sendFile(index.html);
   } else {
     next();
   }
});

index.html

 there was an error


问:
Maximum value of timestamp
I am using Python 3.6.0 on Windows 10 x64.

I just found that in time.ctime(seconds), seconds parameter has an implicit maximum value, which is 32536799999, almost equals to 2^34.92135.

Is that the maximum value?

The error message just says it's an invalid number.

>>> import time
>>> time.ctime(32536799999)
>>> 'Mon Jan 19 15:59:59 3001'
>>> time.ctime(32536799999+1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument
```

I googled and looked on Python documentation, but I didn't find anything about it. And I'm going to check this problem on Ubuntu in my lab.

答:
I'm using
3.6.1 |Continuum Analytics, Inc.| (default, May 11 2017, 13:09:58) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
in a Ubuntu 16.04 VM running on a Windows 10 machine.

I broke apart your ctime call to its components, to investigate but I don't run into the same maximum.

```<code>>>> time.asctime(time.localtime(32536799999-1))
'Mon Jan 19 02:59:58 3001'
>>> time.asctime(time.localtime(32536799999+1))
'Mon Jan 19 03:00:00 3001'
>>> time.asctime(time.localtime(32536799999+10))
'Mon Jan 19 03:00:09 3001'
>>> time.asctime(time.localtime(32536799999+10000))
'Mon Jan 19 05:46:39 3001'
>>> time.asctime(time.localtime(32536799999+1000000))
'Fri Jan 30 16:46:39 3001'
>>> time.asctime(time.localtime(32536799999+1000000000))
'Thu Sep 27 05:46:39 3032'
>>> time.ctime(32536799999+1000000000)
'Thu Sep 27 05:46:39 3032'
>>> time.asctime(time.gmtime(32536799999-1))
'Mon Jan 19 07:59:58 3001'
>>> time.asctime(time.gmtime(32536799999+1))
'Mon Jan 19 08:00:00 3001'
>>> time.asctime(time.gmtime(32536799999+1000000000))
'Thu Sep 27 09:46:39 3032'
</code>```

Either something was fixed from 3.6.0 to 3.6.1, or you have some interesting issue specific to your machine.

I do see the following time related change in 3.6.1:
https://www.python.org/dev/peps/pep-0495/
I wonder if the time you happened to be using happened to fall into a fold or a gap?  Could you try adding a little over 1 hour on your system and see if it becomes valid again?

Title: Maximum value of timestamp

Body:
I am using Python 3.6.0 on Windows 10 x64.

I just found that in time.ctime(seconds), seconds parameter has an implicit maximum value, which is 32536799999, almost equals to 2^34.92135.

Is that the maximum value?

The error message just says it's an invalid number.

>>> import time
>>> time.ctime(32536799999)
>>> 'Mon Jan 19 15:59:59 3001'
>>> time.ctime(32536799999+1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

I googled and looked on Python documentation, but I didn't find anything about it. And I'm going to check this problem on Ubuntu in my lab.

Body:
I'm using
3.6.1 |Continuum Analytics, Inc.| (default, May 11 2017, 13:09:58) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
in a Ubuntu 16.04 VM running on a Windows 10 machine.

I broke apart your ctime call to its components, to investigate but I don't run into the same maximum.

>>> time.asctime(time.localtime(32536799999-1))
'Mon Jan 19 02:59:58 3001'
>>> time.asctime(time.localtime(32536799999+1))
'Mon Jan 19 03:00:00 3001'
>>> time.asctime(time.localtime(32536799999+10))
'Mon Jan 19 03:00:09 3001'
>>> time.asctime(time.localtime(32536799999+10000))
'Mon Jan 19 05:46:39 3001'
>>> time.asctime(time.localtime(32536799999+1000000))
'Fri Jan 30 16:46:39 3001'
>>> time.asctime(time.localtime(32536799999+1000000000))
'Thu Sep 27 05:46:39 3032'
>>> time.ctime(32536799999+1000000000)
'Thu Sep 27 05:46:39 3032'
>>> time.asctime(time.gmtime(32536799999-1))
'Mon Jan 19 07:59:58 3001'
>>> time.asctime(time.gmtime(32536799999+1))
'Mon Jan 19 08:00:00 3001'
>>> time.asctime(time.gmtime(32536799999+1000000000))
'Thu Sep 27 09:46:39 3032'

Either something was fixed from 3.6.0 to 3.6.1, or you have some interesting issue specific to your machine.

I do see the following time related change in 3.6.1:
https://www.python.org/dev/peps/pep-0495/
I wonder if the time you happened to be using happened to fall into a fold or a gap?  Could you try adding a little over 1 hour on your system and see if it becomes valid again?


问:
'advanced(by:)' is unavailable convert from swift 3 to swift 4
```<code> internal func rangeFromNSRange(_ nsRange: NSRange) -> Range<String.Index>? {
    let from16 = utf16.startIndex.advanced(by: nsRange.location)
    let to16 = from16.advanced(by: nsRange.length) //advanced(by:) is unavailable
    if let from = String.Index(from16, within: self),
        let to = String.Index(to16, within: self) {
        return from ..< to
    }
    return nil
}
</code>```

I have this file in swift 3 and I'm trying to convert it to swift 4 but I get this error and also this error

```<code>  public func height(_ width: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGFloat {
        var attrib: [String: AnyObject] = [NSAttributedStringKey.font.rawValue: font]
        if lineBreakMode != nil {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineBreakMode = lineBreakMode!
            attrib.updateValue(paragraphStyle, forKey: NSAttributedStringKey.paragraphStyle.rawValue)
        }
        let size = CGSize(width: width, height: CGFloat(Double.greatestFiniteMagnitude))
        return ceil((self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attrib, context: nil).height)
    }
</code>```

// Cannot convert value of type '[String : AnyObject]' to expected argument type '[NSAttributedStringKey : Any]?'

答:
In Swift 4 there is an API to make Range<String.Index> from NSRange and vice versa. The String extension can be reduced to

```<code>internal func range(from nsRange: NSRange) -> Range<String.Index>? {
   return Range(nsRange, in: self)
}
</code>```

In Swift 4 the type of string attributes has been changed from String to NSAttributedStringKey. For example NSForegroundColorAttributeName is replaced with NSAttributedStringKey.foregroundColor. You need to change the declaration of attrib to

```<code>var attrib: [NSAttributedStringKey: Any] = [.font: font]
</code>```

and to change the line to add an attribute accordingly.

Body:
 internal func rangeFromNSRange(_ nsRange: NSRange) -> Range<String.Index>? {
    let from16 = utf16.startIndex.advanced(by: nsRange.location)
    let to16 = from16.advanced(by: nsRange.length) //advanced(by:) is unavailable
    if let from = String.Index(from16, within: self),
        let to = String.Index(to16, within: self) {
        return from ..< to
    }
    return nil
}

I have this file in swift 3 and I'm trying to convert it to swift 4 but I get this error and also this error

  public func height(_ width: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGFloat {
        var attrib: [String: AnyObject] = [NSAttributedStringKey.font.rawValue: font]
        if lineBreakMode != nil {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineBreakMode = lineBreakMode!
            attrib.updateValue(paragraphStyle, forKey: NSAttributedStringKey.paragraphStyle.rawValue)
        }
        let size = CGSize(width: width, height: CGFloat(Double.greatestFiniteMagnitude))
        return ceil((self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attrib, context: nil).height)
    }

// Cannot convert value of type '[String : AnyObject]' to expected argument type '[NSAttributedStringKey : Any]?'

Body:
In Swift 4 there is an API to make Range<String.Index> from NSRange and vice versa. The String extension can be reduced to

internal func range(from nsRange: NSRange) -> Range<String.Index>? {
   return Range(nsRange, in: self)
}

In Swift 4 the type of string attributes has been changed from String to NSAttributedStringKey. For example NSForegroundColorAttributeName is replaced with NSAttributedStringKey.foregroundColor. You need to change the declaration of attrib to

var attrib: [NSAttributedStringKey: Any] = [.font: font]

and to change the line to add an attribute accordingly.


问:
Java regex for a specific phone number format
I am looking for a regex java pattern to match the following string:

```<code> [Phone Number]= 1234567890
</code>```

Here:
 The regex should look for hardcoded string of "[Phone Number]=" followed by space or not, and followed by
 any numbers of digits.

That means it should match:

```<code>[Phone Number]= 123456 and
[Phone Number]=1234567890
</code>```

Any help is appreciated.

答:
What are your rules for a phone number?
Simply a list of digits is rarely a valid phone number format.

A simple search can find you the regexps for specific countries (I'll provide a specific one if you can tell us which one you need).

ContentLicense: CC BY-SA 2.5

Body:
I am looking for a regex java pattern to match the following string:

 [Phone Number]= 1234567890

Here:
 The regex should look for hardcoded string of "[Phone Number]=" followed by space or not, and followed by
 any numbers of digits.

That means it should match:

[Phone Number]= 123456 and
[Phone Number]=1234567890

Any help is appreciated.


问:
How does Twitter extract meaningful subject colors from image pixel data?
Let me first clarify the problem statement. Check out this tweet:

https://twitter.com/jungledragon/status/926894337761345538

Next, click the image itself within the tweet. In the light box that appears, the menu bar below it takes on a meaningful color that is based on the actual pixels in the image itself. Even in this stress test, this is a difficult image given all the light pixels, does it do a fine job in picking an overall color that 1) represents the content of the image 2) is dark/contrasty enough to place white text on it:

I was simultaneously implementing a similar system before I even knew Twitter had this. Check out a preview below:

The examples in the screenshot are optimistic, as there are plenty of situations where the background is too light. Even in seemingly positive examples as seen in my screenshot, most of the time it does not pass the AA or AAA contrast check.

My current approach:

One-time per image, a JS runs that calculates the average color of
all pixels in the image. Note that the average color is not
necessarily a meaningful color, such as in the edge case of the
spider where the average would be close to white.

I store the RGB value in the database

Upon rendering the page (server-side) I dynamically set the
background color of the image's caption using a formula

My formula is to convert the RGB to HSL, and then to manipulate in particular the S and L values. Given them a notch, using min/max values to set a treshold. I've tried countless combinations.

Yet it seems like a never-ending struggle because color darkness and contrast are subject to human perception.

Hence my curiosity on how Twitter seems to have nailed this, in particular two aspects:

Finding a meaningful subject color (not the same as average or dominant color)

Toning that meaningful color in a way that it remains recognizable (hue) yet is contrasty enough to place light text on it, whilst passing at least the AA contrast check.

I've searched around, but cannot find any information on their implementation. Anybody aware of they do it? Or other proven methods to solve this puzzle end-to-end?

答:
Something like the example below might be found helpful for what you want to accomplish.

function getAverageColourAsRGB(img) {
  var canvas = document.createElement('canvas'),
    context = canvas.getContext && canvas.getContext('2d'),
    rgb = {
      r: 102,
      g: 102,
      b: 102
    },
    pixelInterval = 5,
    count = 0,
    i = -4,
    data, length;
  if (!context) {
    return rgb;
  }
  var height = canvas.height = img.naturalHeight || img.offsetHeight || img.height,
    width = canvas.width = img.naturalWidth || img.offsetWidth || img.width;
  context.drawImage(img, 0, 0);
  try {
    data = context.getImageData(0, 0, width, height);
  } catch (e) {
    console.error(e);
    return rgb;
  }
  data = data.data;
  length = data.length;
  while ((i += pixelInterval * 4) < length) {
    count++;
    rgb.r += data[i];
    rgb.g += data[i + 1];
    rgb.b += data[i + 2];
  }
  rgb.r = Math.floor(rgb.r / count);
  rgb.g = Math.floor(rgb.g / count);
  rgb.b = Math.floor(rgb.b / count);
  return rgb;
}

function getContrastYIQ(r, g, b) {
  var yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
  return (yiq >= 128) ? '#000' : '#FFF';
}

function rgb2hex(rgb) {
  rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
  return (rgb && rgb.length === 4) ? "#" +
    ("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';
}

function convertHex(hex) {
  hex = hex.replace('#', '');
  if (hex.length === 3) {
    hex = hex + hex;
  }
  r = parseInt(hex.substring(0, 2), 16);
  g = parseInt(hex.substring(2, 4), 16);
  b = parseInt(hex.substring(4, 6), 16);
  return [r, g, b];
}

function colorSubH(colorA, colorB) {
  rgbA = convertHex(colorA);
  rgbB = convertHex(colorB);
  c = [];
  for (i = 0; i < rgbA.length; i++) {
    c.push(parseInt((rgbA[i] + rgbB[i]) / 2));
  }
  return rgb2hex("rgb(" + c.join(",") + ")");
}
var myImg = document.getElementById("img1");
var color = getAverageColourAsRGB(myImg);
var colorArray = [color.r, color.g, color.b];
var bgColor = rgb2hex("rgb(" + colorArray.join(","));
var txtColor = getContrastYIQ(color.r, color.g, color.b)
var subHColor = colorSubH(txtColor, bgColor);
var footer = document.getElementsByClassName("imgFooter")[0];
footer.style.backgroundColor = bgColor;
footer.style.color = txtColor;
var span = footer.querySelector("span");
span.style.color = subHColor;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main {
  width: 25rem;
  height: 100%;
}

img {
  width: 100%;
  height: auto;
  margin-bottom: 0;
}

.main .imgFooter {
  position: relative;
  height: 2rem;
  display: block;
  color: #000;
  width: 23rem;
  bottom: 0;
  margin-top: -4rem;
  padding: 1rem;
}</code>```

  <img id="img1" src="data:image/jpeg;base64,[encoded data, 22588 characters]"
  />

    Header

Sub-header

```

Body:
Something like the example below might be found helpful for what you want to accomplish.

function getAverageColourAsRGB(img) {
  var canvas = document.createElement('canvas'),
    context = canvas.getContext && canvas.getContext('2d'),
    rgb = {
      r: 102,
      g: 102,
      b: 102
    },
    pixelInterval = 5,
    count = 0,
    i = -4,
    data, length;
  if (!context) {
    return rgb;
  }
  var height = canvas.height = img.naturalHeight || img.offsetHeight || img.height,
    width = canvas.width = img.naturalWidth || img.offsetWidth || img.width;
  context.drawImage(img, 0, 0);
  try {
    data = context.getImageData(0, 0, width, height);
  } catch (e) {
    console.error(e);
    return rgb;
  }
  data = data.data;
  length = data.length;
  while ((i += pixelInterval * 4) < length) {
    count++;
    rgb.r += data[i];
    rgb.g += data[i + 1];
    rgb.b += data[i + 2];
  }
  rgb.r = Math.floor(rgb.r / count);
  rgb.g = Math.floor(rgb.g / count);
  rgb.b = Math.floor(rgb.b / count);
  return rgb;
}

function getContrastYIQ(r, g, b) {
  var yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
  return (yiq >= 128) ? '#000' : '#FFF';
}

function rgb2hex(rgb) {
  rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
  return (rgb && rgb.length === 4) ? "#" +
    ("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';
}

function convertHex(hex) {
  hex = hex.replace('#', '');
  if (hex.length === 3) {
    hex = hex + hex;
  }
  r = parseInt(hex.substring(0, 2), 16);
  g = parseInt(hex.substring(2, 4), 16);
  b = parseInt(hex.substring(4, 6), 16);
  return [r, g, b];
}

function colorSubH(colorA, colorB) {
  rgbA = convertHex(colorA);
  rgbB = convertHex(colorB);
  c = [];
  for (i = 0; i < rgbA.length; i++) {
    c.push(parseInt((rgbA[i] + rgbB[i]) / 2));
  }
  return rgb2hex("rgb(" + c.join(",") + ")");
}
var myImg = document.getElementById("img1");
var color = getAverageColourAsRGB(myImg);
var colorArray = [color.r, color.g, color.b];
var bgColor = rgb2hex("rgb(" + colorArray.join(","));
var txtColor = getContrastYIQ(color.r, color.g, color.b)
var subHColor = colorSubH(txtColor, bgColor);
var footer = document.getElementsByClassName("imgFooter")[0];
footer.style.backgroundColor = bgColor;
footer.style.color = txtColor;
var span = footer.querySelector("span");
span.style.color = subHColor;

.main {
  width: 25rem;
  height: 100%;
}

img {
  width: 100%;
  height: auto;
  margin-bottom: 0;
}

.main .imgFooter {
  position: relative;
  height: 2rem;
  display: block;
  color: #000;
  width: 23rem;
  bottom: 0;
  margin-top: -4rem;
  padding: 1rem;
}

<div class="main">
  <img id="img1" src="data:image/jpeg;base64,[encoded data, 22588 characters]"
  />
  <div class="imgFooter">
    Header
    <br>
    <span>
Sub-header
</span>

  </div>
</div>
</div>


问:
How to separate whole number and decimal number to two different variable
I am  trying to separate whole number and decimal number
two int variable

```<code>#include <iostream>
#include <iomanip>
#include<math.h>

using namespace std;
int main()
{
    double initialAmount = 42800.13;
    double fractionalPart = initialAmount - floor(initialAmount);
    cout<<int(initialAmount)<<"\n"<<fractionalPart<<"\n";

}
</code>```

Present output is

```<code>42800
0.13
</code>```

expected output

```<code>42800
13
</code>```

It can be more than two decimal places .
any easy way to do that

答:
As suggested in the comments, it could help to convert the number into a string.  Here's one possibility:

```<code>#include <sstream>
#include <iostream>
#include <vector>
#include <string>

int main() {
  double d = 42800.13;
  std::vector<std::string> numbers_s;
  std::string s;
  std::istringstream numberAsString(std::to_string( d ));
  while (getline(numberAsString, s, '.')) {
    numbers_s.push_back(s);
  }
  std::cout << "whole number:" << numbers_s[0] << std::endl;
  //[ remove trailing zeros from fractional part:
  numbers_s[1].erase(numbers_s[1].find_last_not_of('0') + 1, std::string::npos);
  //]
   std::cout << "fractional part:" << std::stoi(numbers_s[1]) << std::endl;
}
</code>```

Error checks should be added to capture cases when the number does not contain a decimal point.

Body:
I am  trying to separate whole number and decimal number
two int variable

#include <iostream>
#include <iomanip>
#include<math.h>

using namespace std;
int main()
{
    double initialAmount = 42800.13;
    double fractionalPart = initialAmount - floor(initialAmount);
    cout<<int(initialAmount)<<"\n"<<fractionalPart<<"\n";

}

Present output is

42800
0.13

expected output

42800
13

It can be more than two decimal places .
any easy way to do that

Body:
As suggested in the comments, it could help to convert the number into a string.  Here's one possibility:

#include <sstream>
#include <iostream>
#include <vector>
#include <string>

int main() {
  double d = 42800.13;
  std::vector<std::string> numbers_s;
  std::string s;
  std::istringstream numberAsString(std::to_string( d ));
  while (getline(numberAsString, s, '.')) {
    numbers_s.push_back(s);
  }
  std::cout << "whole number:" << numbers_s[0] << std::endl;
  //[ remove trailing zeros from fractional part:
  numbers_s[1].erase(numbers_s[1].find_last_not_of('0') + 1, std::string::npos);
  //]
   std::cout << "fractional part:" << std::stoi(numbers_s[1]) << std::endl;
}

Error checks should be added to capture cases when the number does not contain a decimal point.


问:
Django: Insert image in a template whose path is dynamic
I know I can insert an image in an html generated page based on a template using:

```<code> <img src="{% static "myapp/my_image.jpg" %}" alt="Image Description">
</code>```

The problem is I want something slightly more complex. Let's say I have an object "user" in my template with a user.first_name and a user.last_name attributes. I would like to insert an image whose path would be:

```<code> <img src="{% static "myapp/{{user.first_name}}_{{user.last_name}}.jpg" %}" alt="Profile Picture">
</code>```

This line is wrong, I get an error (Django can't parse the expression). Can someone help?

I am building kind of a organization chart with photographs, is that a proper way of including profile pictures for every member (based on the fact that the pictures should be named firstname_lastname.jpg)?

Thanks

答:
You can do another thing:

```<code><img src ="{% static 'myapp/' %}{{user.first_name}}_{{user.last_name}}.jpg" alt="Profile Picture">
</code>```

This will work just as fine. Hope this helps :)

Body:
I know I can insert an image in an html generated page based on a template using:

The problem is I want something slightly more complex. Let's say I have an object "user" in my template with a user.first_name and a user.last_name attributes. I would like to insert an image whose path would be:

This line is wrong, I get an error (Django can't parse the expression). Can someone help?

I am building kind of a organization chart with photographs, is that a proper way of including profile pictures for every member (based on the fact that the pictures should be named firstname_lastname.jpg)?

Thanks

Body:
You can do another thing:

<img src ="{% static 'myapp/' %}{{user.first_name}}_{{user.last_name}}.jpg" alt="Profile Picture">

This will work just as fine. Hope this helps :)


问:
batch script to copy most recent file in directory
Hi here is what I need to get accomplished and not sure how. I have a SQL sever that does daily backup of the transaction logs to a local E drive on the sql server. What I need to do is copy the most recent log file from that server to a remote server. Once I get the script to work I will then setup as a schedule task. Can anyone give me advice on how to copy the most recent file to a different server. This will run daily as well so the file name date will change that is why I need the most recent file in the directory where the backup are going.  </p>

答:
Use in the batch file these command lines:

```<code>for /F "delims=" %%I in ('dir "C:\Path To\Source Folder\*" /A-D-H /B /O-D /TW 2^>nul') do copy /B /Y "C:\Path To\Source Folder\%%I" "X:\Path To\Destination Folder\" >nul & goto FileCopied

:FileCopied
rem More commands after copying file with newest last modification date.
</code>```

This code is explained for example at Get newest file in directory with specific extension. Command DIR excludes here also files with hidden attribute set as command COPY does not copy hidden files. The destination folder must already exist.

Enhanced version with real folder paths:

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFolder=E:\MSSQL\Backup\AaaImaging"
set "TargetFolder=\\servername\F\MSSQL\Backup\Pablo"
for /F "delims=" %%I in ('dir "%SourceFolder%\*" /A-D-H /B /O-D /TW 2^>nul') do copy /B /Y "%SourceFolder%\%%I" "%TargetFolder%\" >nul & goto FileCopied

:FileCopied
rem More commands after copying file with newest last modification date.
endlocal
</code>```

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

copy /?

dir /?

echo /?

endlocal /?

for /?

goto /?

rem /?

set /?

setlocal /?

Read also the Microsoft documentation page about Using command redirection operators and Single line with multiple commands using Windows batch file.

Body:
Use in the batch file these command lines:

for /F "delims=" %%I in ('dir "C:\Path To\Source Folder\*" /A-D-H /B /O-D /TW 2^>nul') do copy /B /Y "C:\Path To\Source Folder\%%I" "X:\Path To\Destination Folder\" >nul & goto FileCopied

:FileCopied
rem More commands after copying file with newest last modification date.

This code is explained for example at Get newest file in directory with specific extension. Command DIR excludes here also files with hidden attribute set as command COPY does not copy hidden files. The destination folder must already exist.

Enhanced version with real folder paths:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFolder=E:\MSSQL\Backup\AaaImaging"
set "TargetFolder=\\servername\F\MSSQL\Backup\Pablo"
for /F "delims=" %%I in ('dir "%SourceFolder%\*" /A-D-H /B /O-D /TW 2^>nul') do copy /B /Y "%SourceFolder%\%%I" "%TargetFolder%\" >nul & goto FileCopied

:FileCopied
rem More commands after copying file with newest last modification date.
endlocal

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

copy /?

dir /?

echo /?

endlocal /?

for /?

goto /?

rem /?

set /?

setlocal /?

Read also the Microsoft documentation page about Using command redirection operators and Single line with multiple commands using Windows batch file.


问:
Default argument followed by variable length arguments (Python)
I have a function that takes one positional argument, one default argument, variable length non keyword arguments and variable length keyword arguments. The function looks like below:

```<code>def set_football_team(name,
                     coach = '',
                     *players, **formations):
    print("Team: "+name)
    print("Coach: "+coach)
    for i, player in enumerate(players):
        print("Player "+str(i+1)+": "+player)
    for position, positional_players in formations.items():
        positional_players = ", ".join(positional_players)
        print(position+": "+positional_players)
</code>```

It is working fine when all arguments are passed.

```<code>name = "Real Madrid"
coach = "Zinedine Zidane"
players = ["Keylor Navas", "K. Casilla",
           "Sergio Ramos", "Varane", "Marcelo"]

formations = {"Goalkeeper": players[:2],
              "Defender": players[2:]}

set_football_team(name, coach, *players, **formations)

Output
==============================================
Team: Real Madrid
Coach: Zinedine  Zidane
Player 1: Keylor Navas
Player 2: K. Casilla
Player 3: Sergio Ramos
Player 4: Varane
Player 5: Marcelo
Goalkeeper: Keylor Navas, K. Casilla
Defender: Sergio Ramos, Varane, Marcelo
</code>```

But when I skip passing coach it shows unexpected output even I set coach to an empty string in the argument:

```<code>name = "Real Madrid"
players = ["Keylor Navas", "K. Casilla",
           "Sergio Ramos", "Varane", "Marcelo"]

formations = {"Goalkeeper": players[:2],
              "Defender": players[2:]}

set_football_team(name, *players, **formations)

Output
==============================================
Team: Real Madrid
Coach: Keylor Navas
Player 1: K. Casilla
Player 2: Sergio Ramos
Player 3: Varane
Player 4: Marcelo
Goalkeeper: Keylor Navas, K. Casilla
Defender: Sergio Ramos, Varane, Marcelo
</code>```

I know the order of function arguments:

positional argument > default argument > variable length non keyword arguments > variable length keyword arguments

What is the reason of the above behavior? What am I missing?

How can I overcome this?

答:
```<code>set_football_team(name, coach, *players, **formations)
</code>```

When the function is called as above with coach is passed as argument, coach is assigned the value which is passed in argument for function set_football_team.

```<code>set_football_team(name,*players, **formations)
</code>```

When the function is called as above when no coach argument is passed explicitly, coach is primarily being assigned first value of *players, the remaining values of players are passed on to players,which is why you notice only 4 players in players while the 0th element in the list got assigned to coach.

Body:
I have a function that takes one positional argument, one default argument, variable length non keyword arguments and variable length keyword arguments. The function looks like below:

def set_football_team(name,
                     coach = '',
                     *players, **formations):
    print("Team: "+name)
    print("Coach: "+coach)
    for i, player in enumerate(players):
        print("Player "+str(i+1)+": "+player)
    for position, positional_players in formations.items():
        positional_players = ", ".join(positional_players)
        print(position+": "+positional_players)

It is working fine when all arguments are passed.

name = "Real Madrid"
coach = "Zinedine Zidane"
players = ["Keylor Navas", "K. Casilla",
           "Sergio Ramos", "Varane", "Marcelo"]

formations = {"Goalkeeper": players[:2],
              "Defender": players[2:]}

set_football_team(name, coach, *players, **formations)

Output
==============================================
Team: Real Madrid
Coach: Zinedine  Zidane
Player 1: Keylor Navas
Player 2: K. Casilla
Player 3: Sergio Ramos
Player 4: Varane
Player 5: Marcelo
Goalkeeper: Keylor Navas, K. Casilla
Defender: Sergio Ramos, Varane, Marcelo

But when I skip passing coach it shows unexpected output even I set coach to an empty string in the argument:

name = "Real Madrid"
players = ["Keylor Navas", "K. Casilla",
           "Sergio Ramos", "Varane", "Marcelo"]

formations = {"Goalkeeper": players[:2],
              "Defender": players[2:]}

set_football_team(name, *players, **formations)

Output
==============================================
Team: Real Madrid
Coach: Keylor Navas
Player 1: K. Casilla
Player 2: Sergio Ramos
Player 3: Varane
Player 4: Marcelo
Goalkeeper: Keylor Navas, K. Casilla
Defender: Sergio Ramos, Varane, Marcelo

I know the order of function arguments:

positional argument > default argument > variable length non keyword arguments > variable length keyword arguments

What is the reason of the above behavior? What am I missing?

How can I overcome this?

Body:
set_football_team(name, coach, *players, **formations)

When the function is called as above with coach is passed as argument, coach is assigned the value which is passed in argument for function set_football_team.

set_football_team(name,*players, **formations)

When the function is called as above when no coach argument is passed explicitly, coach is primarily being assigned first value of *players, the remaining values of players are passed on to players,which is why you notice only 4 players in players while the 0th element in the list got assigned to coach.


问:
C - Value seems to pass to array element correctly but doesn't
Sorry I know that's a really badly worded question - I just couldn't think of a better way to say it.

I have asked this here as I cannot seem to word it correctly to find a solution my Googling.

Code explanation:

Separates file name 'echo' from file_name char array. file_name contains 'echo x y'

The loop starts at 'x' which is the previous file names length +1 (for the space).

The while loop loops until the next space is seen. The null char is to ensure the loop ends when the end of file_name is hit.

It assigns the value of file_name to arg_tmp until it hits a space then assigns this word / letter to the argv array

It then ++ the current_arg counter for the next arg

Hopefully this makes sense and there is enough code there to identify the problem.

MAX_FILE_NAME_LENGTH is 14

strlen(exec_name) = 4 so  the +1 makes it 5.

Length is 9.

Here is my code :

```<code>void
 setup_argv(const char *file_name, char *argv[], size_t argc, size_t length)
 {
   char exec_name[MAX_FILE_NAME_LENGTH];
   char arg_tmp[MAX_FILE_NAME_LENGTH]; // temp arg holder
   // get file name
   get_exec_name(file_name, exec_name);
   // add file name to argv
   argv[0] = exec_name;

   // get rest of args
   // +1 - start at first character of next arg
   int current_arg=1;
   for(size_t i = strlen(exec_name)+1; i < length; i++)
   {
     size_t j = 0;
     while(!(file_name[i] == NULL_CHAR || file_name[i] == SPACE))
     {
       arg_tmp[j] = file_name[i];
       printf("::WHILE::%s\n", arg_tmp);
       i++;
     }
     printf("::BOTH::%d %s\n", current_arg, arg_tmp);
     arg_tmp[++j] = NULL_CHAR;
     argv[current_arg] = arg_tmp;
     printf("::ARGV CUR ARG::%s\n", argv[current_arg]);
     printf("::ARGV::%s\n", argv[1]);
     printf("::CUR ARG::%d\n", current_arg);
     current_arg++;
     printf("::CUR ARG::%d\n", current_arg);
   }

   printf("::ARGV ALL::%s %s %s\n", argv[0], argv[1], argv[2]);
 }
</code>```

Here is my output:

```<code>::WHILE::x
::BOTH::1 x
::ARGV CUR ARG::x
::ARGV::x
::CUR ARG::1
::CUR ARG::2
::WHILE::y
::BOTH::2 y
::ARGV CUR ARG::y
::ARGV::y
::CUR ARG::2
::CUR ARG::3
::ARGV ALL::echo y y
</code>```

What should be printed in the last line is 'echo x y'.

I have used print statements to debug it and try to find where it goes wrong - but I can't seem to see it.

For some reason, it's printing and passing in y twice.

Why is this? What am I doing wrong?

EDIT :  As I have now figured out - I cannot use malloc or strdup (unless I write my own functions for these). This is because I am doing an operating systems modules coursework.  Is there alternatives methods or should I look for written functions of these?

答:
The variable argv is an array of pointers, and you make all pointers in the loop point to the very same place, the first element of arg_temp.

This is even worse than you think, because when setup_argv returns, then the lifetime of arg_temp ends and it ceases to exist, leaving you with an array of stray and invalid pointers. Attempting to dereference them will lead to undefined behavior.

As a solution I suggest you use the common strdup function, or make up your own string-duplication function which allocates new memory for the strings.

Lastly, for a correct argv style array, you should terminate it with a null pointer.

Body:
Sorry I know that's a really badly worded question - I just couldn't think of a better way to say it.

I have asked this here as I cannot seem to word it correctly to find a solution my Googling.

Code explanation:

Separates file name 'echo' from file_name char array. file_name contains 'echo x y'

The loop starts at 'x' which is the previous file names length +1 (for the space).

The while loop loops until the next space is seen. The null char is to ensure the loop ends when the end of file_name is hit.

It assigns the value of file_name to arg_tmp until it hits a space then assigns this word / letter to the argv array

It then ++ the current_arg counter for the next arg

Hopefully this makes sense and there is enough code there to identify the problem.

MAX_FILE_NAME_LENGTH is 14

strlen(exec_name) = 4 so  the +1 makes it 5.

Length is 9.

Here is my code :

void
 setup_argv(const char *file_name, char *argv[], size_t argc, size_t length)
 {
   char exec_name[MAX_FILE_NAME_LENGTH];
   char arg_tmp[MAX_FILE_NAME_LENGTH]; // temp arg holder
   // get file name
   get_exec_name(file_name, exec_name);
   // add file name to argv
   argv[0] = exec_name;

   // get rest of args
   // +1 - start at first character of next arg
   int current_arg=1;
   for(size_t i = strlen(exec_name)+1; i < length; i++)
   {
     size_t j = 0;
     while(!(file_name[i] == NULL_CHAR || file_name[i] == SPACE))
     {
       arg_tmp[j] = file_name[i];
       printf("::WHILE::%s\n", arg_tmp);
       i++;
     }
     printf("::BOTH::%d %s\n", current_arg, arg_tmp);
     arg_tmp[++j] = NULL_CHAR;
     argv[current_arg] = arg_tmp;
     printf("::ARGV CUR ARG::%s\n", argv[current_arg]);
     printf("::ARGV::%s\n", argv[1]);
     printf("::CUR ARG::%d\n", current_arg);
     current_arg++;
     printf("::CUR ARG::%d\n", current_arg);
   }

   printf("::ARGV ALL::%s %s %s\n", argv[0], argv[1], argv[2]);
 }

Here is my output:

::WHILE::x
::BOTH::1 x
::ARGV CUR ARG::x
::ARGV::x
::CUR ARG::1
::CUR ARG::2
::WHILE::y
::BOTH::2 y
::ARGV CUR ARG::y
::ARGV::y
::CUR ARG::2
::CUR ARG::3
::ARGV ALL::echo y y

What should be printed in the last line is 'echo x y'.

I have used print statements to debug it and try to find where it goes wrong - but I can't seem to see it.

For some reason, it's printing and passing in y twice.

Why is this? What am I doing wrong?

EDIT :  As I have now figured out - I cannot use malloc or strdup (unless I write my own functions for these). This is because I am doing an operating systems modules coursework.  Is there alternatives methods or should I look for written functions of these?


问:
Rails link_to not working correctly
I am trying to put in a link_to on my table to go to the show action but it is putting the URL as /admin/vulnerabilities.object_id instead of /admin/vulnerabilities/object_id
my index view is:

```<code>...
<% @vulnerabilities.each do |vulnerability| %>
  <tr>
    <td><%=link_to vulnerability.id, admin_vulnerabilities_path(vulnerability) %></td>
    <td><%= vulnerability.type %></td>
    <td><%=h truncate(vulnerability.description, :length => 80) %></td>
    <td><%= vulnerability.published %></td>
    <td><%= vulnerability.modified %></td>
    <td><%= link_to vulnerability.href, vulnerability.href , target: :_blank %></td>
  </tr>
<% end %>
...
</code>```

I have a show.html.erb template setup and my show action is as follows:

```<code>def show
  @vulnerabilities = Vulnerability.find(params[:id])
end
</code>```

From what I can see, this should work but when clicking the links it just redirects to the index page, effectively refreshing it and not using my show page at all.

答:
It would be helpful if you added the relevant parts of your routes.rb file to your question, but I speculate that the problem is that admin_vulnerabilities_path(vulnerability) should be admin_vulnerability_path(vulnerability).

Also, as noted in the comments, it is probably better to use @vulnerability as your instance name since find will return a single record.

Title: Rails link_to not working correctly

Body:
I am trying to put in a link_to on my table to go to the show action but it is putting the URL as /admin/vulnerabilities.object_id instead of /admin/vulnerabilities/object_id
my index view is:

...
<% @vulnerabilities.each do |vulnerability| %>

    <%=link_to vulnerability.id, admin_vulnerabilities_path(vulnerability) %>
    <%= vulnerability.type %>
    <%=h truncate(vulnerability.description, :length => 80) %>
    <%= vulnerability.published %>
    <%= vulnerability.modified %>
    <%= link_to vulnerability.href, vulnerability.href , target: :_blank %>

<% end %>
...

I have a show.html.erb template setup and my show action is as follows:

def show
  @vulnerabilities = Vulnerability.find(params[:id])
end

From what I can see, this should work but when clicking the links it just redirects to the index page, effectively refreshing it and not using my show page at all.


问:
How to select list in pandas dataframe
I have a dataframe which contains list item in a single cell.

For example, data frame 'home'

```<code>a       b                  c
'book'  ['living room']   ['cat','foo']
'shoes' ['door']          ['man','woman']
'cook'  []                ['knife']
</code>```

The question is how do I select the 'cook' based on b == [] (empty list).

like

```<code>home.loc[home.b==[]]
</code>```

BTW, I created the list using lambda x : [] function.

答:
IIUC, @MaxU method is optimal, I think.

However, you can try this:

```<code>home.loc[home.b.apply(lambda x: x == [])]
</code>```

Output:

```<code>      a   b        c
2  cook  []  [knife]
</code>```

Title: How to select list in pandas dataframe

Body:
I have a dataframe which contains list item in a single cell.

For example, data frame 'home'

a       b                  c
'book'  ['living room']   ['cat','foo']
'shoes' ['door']          ['man','woman']
'cook'  []                ['knife']

The question is how do I select the 'cook' based on b == [] (empty list).

like

home.loc[home.b==[]]

BTW, I created the list using lambda x : [] function.

Body:
IIUC, @MaxU method is optimal, I think.

However, you can try this:

home.loc[home.b.apply(lambda x: x == [])]

Output:

      a   b        c
2  cook  []  [knife]


问:
Organising TFS over multiple projects
I have inherited a TFS 2017 on-premise. It has 1 collection which contains 10 projects.  Each project has its own work items, builds, source code and produces a separate application/website.  This all makes sense from a developer perspective as all the software is independent and builds/releases separately.  Each new 'business project' however does tend to span multiple 'TFS projects' in order to deliver the features needed.

How is it best to organise this from a management perspective?
Options:
1) Create a 'Management' project that has no code or work items but just has dashboards and queries.
2) Put all the code into one project.
3) Create a 'Epic TFS project' that just contained Epics - with PBIs in the relevant TFS project.
4) Secret option 4 that I don't know about.

答:
Use one team project with multiple teams underneath.

Your current structure is like this:

Team Project Collection

Project 1

Project 2

Project N

The structure you're after is this:

Team Project Collection

Project A

Team A

Team 1 (corresponds to Project 1)

Team 2

Team 3

Basically, each Team is assigned to a separate area path. You can use the hierarchy of area paths to subdivide everything so that it can be rolled up and easily reported. In the example above, you can report on Team A (which rolls up Team 1, 2, 3), or on each of the Teams individually.

Each team can have its own separate subareas, iterations, etc. But all source code, builds, and so on live within the same team project. Access to those entities can be controlled via security groups.

Now, the question of "How do I go from the current structure to the new structure?" is a much bigger problem. There's no easy way to combine multiple team projects.

Title: Organising TFS over multiple projects


问:
Sum of rows in SQL with GROUP BY
I am having a table with data like:

```<code>ID  OrderId TAX%    Quantity UnitCost
1     5      28    2       1280
2     5      18    1       1180
</code>```

I want the output like:

```<code>ORDERID    TaxableValue       TaxValue
   5           3000               740
</code>```

How can I achieve this? I tried with:

```<code>SELECT orderid,
       ROUND((SUM(UnitCost*Quantity)*TAX)/(100+TAX),2) AS taxValue,
       ROUND(SUM(unitCost*quantity)-ROUND((SUM(UnitCost*Quantity)*TAX)/(100+TAX),2),2) AS taxableValue
FROM table1
GROUP BY OrderId;
</code>```

But the query above is not working.

Sorry all, That is the Tax percentage. This is the new Updated Query. Please consider this.

答:
```<code>select OrderId
    , SUM((unitcost * quantity * tax)/(100+tax)) as TaxValue
    , SUM(unitcost * quantity)-SUM((unitcost * quantity * tax)/(100+tax)) as taxableValue
from table1
group by OrderId
</code>```

Title: Sum of rows in SQL with GROUP BY

Body:
I am having a table with data like:

ID  OrderId TAX%    Quantity UnitCost
1     5      28    2       1280
2     5      18    1       1180

I want the output like:

ORDERID    TaxableValue       TaxValue
   5           3000               740

How can I achieve this? I tried with:

SELECT orderid,
       ROUND((SUM(UnitCost*Quantity)*TAX)/(100+TAX),2) AS taxValue,
       ROUND(SUM(unitCost*quantity)-ROUND((SUM(UnitCost*Quantity)*TAX)/(100+TAX),2),2) AS taxableValue
FROM table1
GROUP BY OrderId;

But the query above is not working.

Sorry all, That is the Tax percentage. This is the new Updated Query. Please consider this.


问:
C++ Openssl Encryption routines generates different output on each run
I have an application that has to Encrypt data.

However, when I run the following it returns me different output within the same execution. When I repeat the execution, the pattern of output is exactly the same, see end of my question.

```<code>int Encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext) {
    EVP_CIPHER_CTX *ctx;
    int len;
    int ciphertext_len;
    if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
    if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cfb(), NULL, key, iv)) {
        handleErrors();
        }
    if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) {
        handleErrors();
        }
    ciphertext_len = len;
    if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
        handleErrors();
        }
    ciphertext_len += len;
    EVP_CIPHER_CTX_free(ctx);
    return ciphertext_len;
    }
string EncryptThis(string Data, string Key, string IV, long long Buffer) {
    unsigned char *key = (unsigned char *)Key.c_str();
    unsigned char *iv = (unsigned char *)IV.c_str();
    unsigned char *plaintext = (unsigned char *)Data.c_str();
    unsigned char* ciphertext = new unsigned char[Buffer];
    ERR_load_crypto_strings();
    OpenSSL_add_all_algorithms();
    //cout << Data << endl; //ALWAYS THE SAME
    //cout << Key << endl; //ALWAYS THE SAME
    //cout << IV << endl; //ALWAYS THE SAME

    int ciphertext_len = Encrypt(plaintext, (int)strlen((char *)plaintext), key, iv, ciphertext);
    string Encrypted = base64_encode(reinterpret_cast<const unsigned char *>(ciphertext), ciphertext_len);
    EVP_cleanup();
    ERR_free_strings();
    return Encrypted;
    }
int main() {
    cout << EncryptThis("ThisisATest", "Test", "Test2", 11) << endl;
    cout << EncryptThis("ThisisATest", "Test", "Test2", 11) << endl;
    cout << EncryptThis("ThisisATest", "Test", "Test2", 11) << endl;
    }
</code>```

In this test the results where:

```<code>mJOjOk2wIe5D4oA=
GTvRQb8IZtFYbLI=
plOJA083gOSfVrs=
</code>```

However, when I run the same application again, it returns me exact the same output even in the same order. So it seems to be a problem with the repetition within the execution of the script?

To clarify. When this application would be called Test.exe and I execute the application three times, it would output the following:

```<code>//execute Test.exe
mJOjOk2wIe5D4oA=
GTvRQb8IZtFYbLI=
plOJA083gOSfVrs=

//Execute Test.exe
mJOjOk2wIe5D4oA=
GTvRQb8IZtFYbLI=
plOJA083gOSfVrs=

//execute Test.exe
mJOjOk2wIe5D4oA=
GTvRQb8IZtFYbLI=
plOJA083gOSfVrs=
</code>```

How is this possible and where is my error?

答:
The key and IV are to short. The key for EVP_aes_256_cfb needs to be 256-bits (32-bytes) and the IV needs to be the block size, 128-bits (16-bytes) for AES.

Since the key and IV are to short the extra length is made up somehow, there is no standard defined. For one or both what ever bytes follow are used. On call to main the memory is the same each time (possible zeroed) so the same results. On the internal calls the memory has been changed by execution but in the same way each time so the output is repeated.

The buffer is too short. it needs to be the length of the data to be encrypted + the block length: 11 + 16 -> 27. It is best if the encryption function (Encrypt) create the buffer, not the caller. The EVP_EncryptUpdate function will return the final length of the encrypted+padding.

Solution: use full length values for the key and IV and handle the buffer internally with the correct length.

Hint 1: CBC mode is more generally used that CFB mode.

Hint 2: Use a random IV, just prefix the encrypted data with the IV for use in decryption, it does not need to be secret. That way the user need not provide the IV.

Note: If you stil have problems with full length key and IV update the question and supply the valuies at the call to and after EVP_EncryptUpdate.

Body:
I have an application that has to Encrypt data.

However, when I run the following it returns me different output within the same execution. When I repeat the execution, the pattern of output is exactly the same, see end of my question.

int Encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext) {
    EVP_CIPHER_CTX *ctx;
    int len;
    int ciphertext_len;
    if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
    if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cfb(), NULL, key, iv)) {
        handleErrors();
        }
    if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) {
        handleErrors();
        }
    ciphertext_len = len;
    if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
        handleErrors();
        }
    ciphertext_len += len;
    EVP_CIPHER_CTX_free(ctx);
    return ciphertext_len;
    }
string EncryptThis(string Data, string Key, string IV, long long Buffer) {
    unsigned char *key = (unsigned char *)Key.c_str();
    unsigned char *iv = (unsigned char *)IV.c_str();
    unsigned char *plaintext = (unsigned char *)Data.c_str();
    unsigned char* ciphertext = new unsigned char[Buffer];
    ERR_load_crypto_strings();
    OpenSSL_add_all_algorithms();
    //cout << Data << endl; //ALWAYS THE SAME
    //cout << Key << endl; //ALWAYS THE SAME
    //cout << IV << endl; //ALWAYS THE SAME

    int ciphertext_len = Encrypt(plaintext, (int)strlen((char *)plaintext), key, iv, ciphertext);
    string Encrypted = base64_encode(reinterpret_cast<const unsigned char *>(ciphertext), ciphertext_len);
    EVP_cleanup();
    ERR_free_strings();
    return Encrypted;
    }
int main() {
    cout << EncryptThis("ThisisATest", "Test", "Test2", 11) << endl;
    cout << EncryptThis("ThisisATest", "Test", "Test2", 11) << endl;
    cout << EncryptThis("ThisisATest", "Test", "Test2", 11) << endl;
    }

In this test the results where:

mJOjOk2wIe5D4oA=
GTvRQb8IZtFYbLI=
plOJA083gOSfVrs=

However, when I run the same application again, it returns me exact the same output even in the same order. So it seems to be a problem with the repetition within the execution of the script?

To clarify. When this application would be called Test.exe and I execute the application three times, it would output the following:

//execute Test.exe
mJOjOk2wIe5D4oA=
GTvRQb8IZtFYbLI=
plOJA083gOSfVrs=

//Execute Test.exe
mJOjOk2wIe5D4oA=
GTvRQb8IZtFYbLI=
plOJA083gOSfVrs=

//execute Test.exe
mJOjOk2wIe5D4oA=
GTvRQb8IZtFYbLI=
plOJA083gOSfVrs=

How is this possible and where is my error?


问:
ApolloClient is not a constructor react-apollo
I am following this tutorial and trying to implement graphQl. There is an issue with the following line:

const client = new ApolloClient();

Strangely I cannot find anything in the react-apollo GitHub page for this. Is there something stupid that I am doing wrong.

```<code>import React, { Component } from 'react';
import ChannelsList from './ChannelsList.js';
import './App.css';

import {
  ApolloClient,
  gpl,
  graphql,
  ApolloProvider
} from 'react-apollo';

//issue with this line
const client = new ApolloClient();

const channelsListQuery = `
  query ChannelsListQuery {
    channels {
      id,
      name
    }
  }
`;

const ChannelsListWithData = graphql(channelsListQuery)(ChannelsList);

class App extends Component {
  render() {
    return (
      <ApolloProvider client={client}>
        <ChannelsListWithData />
      </ApolloProvider>
    );
  }
}

export default App;
</code>```

答:
having the same issue here and actually following the same article (https://dev-blog.apollodata.com/full-stack-react-graphql-tutorial-582ac8d24e3b) as the OP. The issue is that the article is really old and out of date and I would not recommend using it as a guide (take a look at the comments in the article). </p>

<p>For a start I'd recommend looking at the docs. This link (http://graphql.org/graphql-js/) in particular is a good starting place for getting something up and running. </p>

Body:
I am following this tutorial and trying to implement graphQl. There is an issue with the following line:

const client = new ApolloClient();

Strangely I cannot find anything in the react-apollo GitHub page for this. Is there something stupid that I am doing wrong.

import React, { Component } from 'react';
import ChannelsList from './ChannelsList.js';
import './App.css';

import {
  ApolloClient,
  gpl,
  graphql,
  ApolloProvider
} from 'react-apollo';

//issue with this line
const client = new ApolloClient();

const channelsListQuery = `
  query ChannelsListQuery {
    channels {
      id,
      name
    }
  }
`;

const ChannelsListWithData = graphql(channelsListQuery)(ChannelsList);

class App extends Component {
  render() {
    return (
      <ApolloProvider client={client}>
        <ChannelsListWithData />
      </ApolloProvider>
    );
  }
}

export default App;

Body:
having the same issue here and actually following the same article (https://dev-blog.apollodata.com/full-stack-react-graphql-tutorial-582ac8d24e3b) as the OP. The issue is that the article is really old and out of date and I would not recommend using it as a guide (take a look at the comments in the article).

For a start I'd recommend looking at the docs. This link (http://graphql.org/graphql-js/) in particular is a good starting place for getting something up and running.


问:
How to read Azure web site app settings values
I am trying to configure some key/value pairs for my Azure web application using app settings section on Windows Azure preview portal.

Now I am trying to read values like below

ConfigurationManager.AppSettings["MyWebApp.DbConnectionString"];

but it returns null values.

Reading app settings from Web.config in my web application works fine.

答:
In Azure, there are a few different ways of retrieving Application Settings and Connection Strings. However, connection strings work a little differently than vanilla application settings.

Application Settings can be retrieved by any method, regardless of whether or not they are present in the Web.config file.

Connection Strings can also be retrieved by any method if the string is defined in Web.config. However, if the connection string is NOT defined in Web.config, then it can only be retrieved using the Environment Variable method.

Retrieving as Environment Variable

```<code>Environment.GetEnvironmentVariable("APPSETTING_my-setting-key");
Environment.GetEnvironmentVariable("SQLAZURECONNSTR_my-connection-string-key");
</code>```

Note that the keys must be prepended with a string designating their type when using this method.

All Application Settings use the APPSETTING_ prefix.

Connection Strings have a different prefix depending on the type of database selected when creating the string in the portal:

```<code>"Sql Databases" --> "SQLAZURECONNSTR_my-connection-string-key"
"SQL Server" --> "SQLCONNSTR_my-connection-string-key"
"MySQL" --> "MYSQLCONNSTR_my-connection-string-key"
"Custom" --> "CUSTOMCONNSTR_my-connection-string-key"
</code>```

For a full overview, see the Windows Azure Web Sites documentation.

Body:
In Azure, there are a few different ways of retrieving Application Settings and Connection Strings. However, connection strings work a little differently than vanilla application settings.

Application Settings can be retrieved by any method, regardless of whether or not they are present in the Web.config file.

Connection Strings can also be retrieved by any method if the string is defined in Web.config. However, if the connection string is NOT defined in Web.config, then it can only be retrieved using the Environment Variable method.

Retrieving as Environment Variable

Environment.GetEnvironmentVariable("APPSETTING_my-setting-key");
Environment.GetEnvironmentVariable("SQLAZURECONNSTR_my-connection-string-key");

Note that the keys must be prepended with a string designating their type when using this method.

All Application Settings use the APPSETTING_ prefix.

Connection Strings have a different prefix depending on the type of database selected when creating the string in the portal:

"Sql Databases" --> "SQLAZURECONNSTR_my-connection-string-key"
"SQL Server" --> "SQLCONNSTR_my-connection-string-key"
"MySQL" --> "MYSQLCONNSTR_my-connection-string-key"
"Custom" --> "CUSTOMCONNSTR_my-connection-string-key"

For a full overview, see the Windows Azure Web Sites documentation.


问:
Passing dotenv to ActiveRecord rake tasks (no Rails)
I'm using ActiveRecords in no-Rails app and I'm trying to use dotenv with ActiveRecord rake tasks.

In the documentation of dotenv there is stated that you need to pass it to tasks like this:

```<code>require 'dotenv/tasks'

task mytask: :dotenv do
   # things that require .env
end
</code>```

But I'm loading my ActiveRecord rake tasks like this in my Rakefile:

```<code>load 'active_record/railties/databases.rake'
</code>```

How can I pass dotenv to ActiveRecord tasks?

Thanks

答:
I guess you should also require dotenv at your Rakefile

```<code>require 'dotenv/tasks'
load 'active_record/railties/databases.rake'
</code>```

So at the moment of loading your custom tasks, the dotenv will be loaded and ENV will be populated with data.

Body:
I'm using ActiveRecords in no-Rails app and I'm trying to use dotenv with ActiveRecord rake tasks.

In the documentation of dotenv there is stated that you need to pass it to tasks like this:

require 'dotenv/tasks'

task mytask: :dotenv do
   # things that require .env
end

But I'm loading my ActiveRecord rake tasks like this in my Rakefile:

load 'active_record/railties/databases.rake'

How can I pass dotenv to ActiveRecord tasks?

Thanks

Body:
I guess you should also require dotenv at your Rakefile

require 'dotenv/tasks'
load 'active_record/railties/databases.rake'

So at the moment of loading your custom tasks, the dotenv will be loaded and ENV will be populated with data.


问:
'Address already in use' when running tests using Spring LDAP embedded server
I am trying to use Spring LDAP in one of my Spring Boot projects but I am getting an 'Address already in use' error when running multiple tests.

I have cloned locally the sample project here:
https://spring.io/guides/gs/authenticating-ldap/

...and just added the boilerplate test normally created by Spring Boot to verify that the Application Context loads correctly:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
public class MyApplicationTests {
    @Test
    public void contextLoads() {
    }
}
</code>```

If run alone, this test passes. As soon as LdapAuthenticationTests and MyApplicationTests are run together, I get the error above for the latter.

After debugging a bit, I've found out that this happens because the system tries to spawn a second instance of the embedded server.

I am sure I am missing something very stupid in the configuration.
How can I fix this problem?

答:
Try specifying the web environment type and the base configuration class (the one with !SpringBootApplication on it).

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(
    classes = MyApplication.class,
    webEnvironment = RANDOM_PORT
)
public class MyApplicationTests {
    @Test
    public void contextLoads() {
    }
}
</code>```

Do this for all your test classes.

Body:
I am trying to use Spring LDAP in one of my Spring Boot projects but I am getting an 'Address already in use' error when running multiple tests.

I have cloned locally the sample project here:
https://spring.io/guides/gs/authenticating-ldap/

...and just added the boilerplate test normally created by Spring Boot to verify that the Application Context loads correctly:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyApplicationTests {
    @Test
    public void contextLoads() {
    }
}

If run alone, this test passes. As soon as LdapAuthenticationTests and MyApplicationTests are run together, I get the error above for the latter.

After debugging a bit, I've found out that this happens because the system tries to spawn a second instance of the embedded server.

I am sure I am missing something very stupid in the configuration.
How can I fix this problem?

Body:
Try specifying the web environment type and the base configuration class (the one with !SpringBootApplication on it).

@RunWith(SpringRunner.class)
@SpringBootTest(
    classes = MyApplication.class,
    webEnvironment = RANDOM_PORT
)
public class MyApplicationTests {
    @Test
    public void contextLoads() {
    }
}

Do this for all your test classes.


问:
Passing a function pointer as non-type template parameter
I have this template function, which is working well:

```<code>    template<typename RES, typename... PARMS> SQInteger GlobalBind(RES(*fn)(PARMS... parms), const char *sqName, HSQUIRRELVM v)
</code>```

Which is called like this :

```<code>GlobalBind(aFunction, "aName", vm);
</code>```

Its scope is binding function fn to a scripting engine.

Using it in this way, I must keep the fn pointer AND a proxy template pointer inside of the scripting engine; the proxy template (not shown here) is called with fn as parameter, does some stuff, and then calls fn.

What I'd like to achieve is to remove the fn pointer from the function call, and put it into the template as a parameter, something like this:

```<code>template<typename RES, typename... PARMS, RES(*fn)(PARMS...)> SQInteger GlobalBind(const char *sqName, HSQUIRRELVM v)
</code>```

So, a specific template is instantiated for each different fn, which means that I could avoid the fn pointer in the scripting language; the call should be:

```<code>GlobalBind<aFunction>("aName", vm);
</code>```

The template declaration is accepted by the compiler, but the call brings errors, even adding the parameter types before aFunction, like this (assuming aFunction returns and int and has const char * as a parameter):

```<code>GlobalBind<int, const char *, aFunction>("aName", vm);
</code>```

Is there a way to achieve this result (the former, without a parameters list)?

EDIT:
to simplify the question, is the template

```<code>template<typename RES, typename... PARMS, RES(*fn)(PARMS...)> RES TEST(PARMS... parms) {
    return fn(parms...);
}
</code>```

a valid one ? And if yes... how should it be called ?
I tried this :

```<code>int testfn(const char *s) { return strlen(s); }
TEST<testfn>("aString");   << ERROR
TEST<int, const char *, testfn>("aString");  << ERROR
</code>```

EDIT2:
This one :

```<code>template<int (*fn)(const char *)> int TEST2(const char *s) {
    return fn(s);
}
TEST2<testfn>("aString");
</code>```

works, but it's not useful for my purpose

答:
Found an (ugly) solution, but it works also for overloaded functions :

```<code>int myFunc(const char *s) {
    return strlen(s);
}

const char *myFunc(int i) {
    return "it's me";
}

template<typename FN, FN fn, typename RES, typename... PARMS> RES _DISPATCH(PARMS... parms) {
    return fn(parms...);
}

#define DISPATCH(RES, FN, ...) _DISPATCH<RES(*)(__VA_ARGS__), FN, RES, __VA_ARGS__>

Cout() << (void *)DISPATCH(int, myFunc, const char *) << "\n";
Cout() << (void *)DISPATCH(const char *, myFunc, int) << "\n";
</code>```

The DISPATCH() macro builds a dispatcher of which I can get the C address and pass to my scripting engine.
I'd rather to have a solution without macros, indeed. Still open to better solutions!

Body:
I have this template function, which is working well:

    template<typename RES, typename... PARMS> SQInteger GlobalBind(RES(*fn)(PARMS... parms), const char *sqName, HSQUIRRELVM v)

Which is called like this :

GlobalBind(aFunction, "aName", vm);

Its scope is binding function fn to a scripting engine.

Using it in this way, I must keep the fn pointer AND a proxy template pointer inside of the scripting engine; the proxy template (not shown here) is called with fn as parameter, does some stuff, and then calls fn.

What I'd like to achieve is to remove the fn pointer from the function call, and put it into the template as a parameter, something like this:

template<typename RES, typename... PARMS, RES(*fn)(PARMS...)> SQInteger GlobalBind(const char *sqName, HSQUIRRELVM v)

So, a specific template is instantiated for each different fn, which means that I could avoid the fn pointer in the scripting language; the call should be:

GlobalBind<aFunction>("aName", vm);

The template declaration is accepted by the compiler, but the call brings errors, even adding the parameter types before aFunction, like this (assuming aFunction returns and int and has const char * as a parameter):

GlobalBind<int, const char *, aFunction>("aName", vm);

Is there a way to achieve this result (the former, without a parameters list)?

EDIT:
to simplify the question, is the template

template<typename RES, typename... PARMS, RES(*fn)(PARMS...)> RES TEST(PARMS... parms) {
    return fn(parms...);
}

a valid one ? And if yes... how should it be called ?
I tried this :

int testfn(const char *s) { return strlen(s); }
TEST<testfn>("aString");   << ERROR
TEST<int, const char *, testfn>("aString");  << ERROR

EDIT2:
This one :

template<int (*fn)(const char *)> int TEST2(const char *s) {
    return fn(s);
}
TEST2<testfn>("aString");

works, but it's not useful for my purpose

Body:
Found an (ugly) solution, but it works also for overloaded functions :

int myFunc(const char *s) {
    return strlen(s);
}

const char *myFunc(int i) {
    return "it's me";
}

template<typename FN, FN fn, typename RES, typename... PARMS> RES _DISPATCH(PARMS... parms) {
    return fn(parms...);
}

#define DISPATCH(RES, FN, ...) _DISPATCH<RES(*)(__VA_ARGS__), FN, RES, __VA_ARGS__>

Cout() << (void *)DISPATCH(int, myFunc, const char *) << "\n";
Cout() << (void *)DISPATCH(const char *, myFunc, int) << "\n";

The DISPATCH() macro builds a dispatcher of which I can get the C address and pass to my scripting engine.
I'd rather to have a solution without macros, indeed. Still open to better solutions!


问:
First paint time in Python (may be using Selenium or without it)?
I want to find the time whatever (an object, image, text, link, DB or anything) loads first in a requested website using Python and Selenium.</p>

答:
Checkout performance.timing, it's JavaScript and comes default in your browser. You have a lot of options to display, like:

navigationStart

connectStart

connectEnd

domLoading

domInteractive

domComplete

Just go to your console window in your browser and type performance.timing. Might be of use to you.

If you find something you can use, you can use selenium to execute the JavaScript inside the browser using execute_script:

```<code>driver.execute_script(‘return performance.timing.domComplete’)
</code>```

Body:
Checkout performance.timing, it's JavaScript and comes default in your browser. You have a lot of options to display, like:

navigationStart

connectStart

connectEnd

domLoading

domInteractive

domComplete

Just go to your console window in your browser and type performance.timing. Might be of use to you.

If you find something you can use, you can use selenium to execute the JavaScript inside the browser using execute_script:

driver.execute_script(‘return performance.timing.domComplete’)


问:
Generate ngram (bigram or trigram) in Keras / Tensorflow
I want to generate generate n-grams from a sequence of tokens:

```<code>bigram:: "1 3 4 5" --> { (1,3), (3,4), (4,5) }
</code>```

After searching I found this thread that used:

```<code>def find_ngrams(input_list, n):
  return zip(*[input_list[i:] for i in range(n)])
</code>```

If I use this piece of code during my training time I think it kills the performance. So I looking for a better option.

答:
If you need to generate bigram in string format:

```<code>import tensorflow as tf

tf.enable_eager_execution()

sentence = ['this is example sentence']
x = tf.string_split(sentence).values[:-1] + ' ' + tf.string_split(sentence).values[1:]

# tf.Tensor([b'this is' b'is example' b'example sentence'], shape=(3,), dtype=string)
</code>```

You can also use tensorflow-transform to generate ngrams.

```<code>import tensorflow_transform as tft

tft.ngrams(tensor, (1,2), " ")
</code>```

Note: tensorflow-transform only supports python 2 until 22 January 2019.

Body:
I want to generate generate n-grams from a sequence of tokens:

bigram:: "1 3 4 5" --> { (1,3), (3,4), (4,5) }

After searching I found this thread that used:

def find_ngrams(input_list, n):
  return zip(*[input_list[i:] for i in range(n)])

If I use this piece of code during my training time I think it kills the performance. So I looking for a better option.

Body:
If you need to generate bigram in string format:

import tensorflow as tf

tf.enable_eager_execution()

sentence = ['this is example sentence']
x = tf.string_split(sentence).values[:-1] + ' ' + tf.string_split(sentence).values[1:]

# tf.Tensor([b'this is' b'is example' b'example sentence'], shape=(3,), dtype=string)

You can also use tensorflow-transform to generate ngrams.

import tensorflow_transform as tft

tft.ngrams(tensor, (1,2), " ")

Note: tensorflow-transform only supports python 2 until 22 January 2019.


问:
Service Fabric: The EntryPoint Blah.exe is not found
I did some project renaming and changed the folder structure and now I can't deploy my service fabric app to my local service fabric cluster.

Register-ServiceFabricApplicationType : The EntryPoint IdentityService.exe is not found.

The app was called IdentityApp and is now TheProject.Identity.App

The service was called IdentityWeb and is now TheProject.Identity.Service

More Log Details

Started executing script 'Deploy-FabricApplication.ps1'.

. 'C:\Users\mdepouw\source\repos\TheProject\TheProject.IdentityDomain\TheProject.Identity.App\Scripts\Deploy-FabricApplication.ps1' -ApplicationPackagePath 'C:\Users\mdepouw\source\repos\TheProject\TheProject.IdentityDomain\TheProject.Identity.App\pkg\Debug' -PublishProfileFile 'C:\Users\mdepouw\source\repos\TheProject\TheProject.IdentityDomain\TheProject.Identity.App\PublishProfiles\Local.5Node.xml' -DeployOnly:$true -ApplicationParameter:@{} -UnregisterUnusedApplicationVersionsAfterUpgrade $false -OverrideUpgradeBehavior 'None' -OverwriteBehavior 'Always' -SkipPackageValidation:$true -ErrorAction Stop

Copying application to image store...

Upload to Image Store succeeded

Registering application type...

Register-ServiceFabricApplicationType : The EntryPoint IdentityService.exe is not found.

FileName: C:\SfDevCluster\Data\ImageBuilderProxy\AppType\IdentityAppType\IdentityServicePkg\ServiceManifest.xml

At C:\Program Files\Microsoft SDKs\Service

Fabric\Tools\PSModule\ServiceFabricSDK\Publish-NewServiceFabricApplication.ps1:251 char:9

Register-ServiceFabricApplicationType -ApplicationPathInImage ...

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

CategoryInfo          : InvalidOperation: (Microsoft.Servi...usterConnection:ClusterConnection) [Register-Servic

eFabricApplicationType], FabricException

FullyQualifiedErrorId : RegisterApplicationTypeErrorId,Microsoft.ServiceFabric.Powershell.RegisterApplicationType

Finished executing script 'Deploy-FabricApplication.ps1'.

Time elapsed: 00:00:26.1378123

The PowerShell script failed to execute.

答:
In TheProject.Identity.Service\PackageRoot\ServiceManifest.xml I had to change the <Program> to match the new exe name

<CodePackage Name="Code" Version="1.0.0">
    <EntryPoint>
      <ExeHost>
        <Program>TheProject.Identity.Service.exe</Program>
        <WorkingFolder>CodePackage</WorkingFolder>
      </ExeHost>
    </EntryPoint>
</CodePackage>
```

Body:
In TheProject.Identity.Service\PackageRoot\ServiceManifest.xml I had to change the <Program> to match the new exe name

<!-- Code package is your service executable. -->
<CodePackage Name="Code" Version="1.0.0">
    <EntryPoint>
      <ExeHost>
        <Program>TheProject.Identity.Service.exe</Program>
        <WorkingFolder>CodePackage</WorkingFolder>
      </ExeHost>
    </EntryPoint>
</CodePackage>


问:
Angular FIrebase 5 objects keys not being displayed. So can't delete
The question has been answered but I'm looking for a, um, more straightforward one if available. It seems strange that we'd have to implement not one but two mappings just to have access to the object keys.

basic firebase db:

As can be seen, the course objects clearly have keys.
Mark-up:

```<code><ul>
  <li *ngFor="let course of courses$ | async">
    <b>Key:</b> {{course.$key}} <!-- doesn't show --!>
    <b>Title:</b> {{course.Title}}
    <b>Duration:</b> {{course.Duration}}
    <b>Author:</b> {{course.Author}}
    <p><button (click)="deleteCourse(course)">Remove</button></p>

    <hr>
  </li>
</ul>
</code>```

Now, the courses display just fine, but I don't know how to get a reference to the key in order to delete it. (Or perhaps I'm not using the right method on my firebaseDatabase Object).  Either way, when I log the key in the console, it shows as undefined.

```<code>export class AppComponent {
  courses;
  courses$: AngularFireList<any>;

  constructor(private db: AngularFireDatabase) {
    this.courses = db.list('/courses');
    this.courses$ = this.courses.valueChanges();
  }
  ...
  deleteCourse(course) {
    console.log(course.$key); // -> undefined
    this.db.object('/courses/' + course.$key).remove();
  }
}
</code>```

答:
Updated Answer

Rxjs have changed how it pipes data. now you have to use .pipe().

```<code>this.courses$ = this.courses.snapshotChanges().pipe(
  map(changes =>
    changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
  )
);
</code>```

Original Answer

.valueChanges() contain simply data, no key with it. you need to use .snapshotChanges()

```<code>this.courses$ = this.courses.snapshotChanges().map(changes => {
  return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
</code>```

now just use {{course.key}}

here is your corrected code

```<code>import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

export class AppComponent {
  courseRef: AngularFireList<any>;
  courses$: Observable<any[]>;

  constructor(private db: AngularFireDatabase) {
    this.courseRef = db.list('/courses');
    this.courses$ = this.courseRef.snapshotChanges().map(changes => {
        return changes.map(c => ({ key: c.payload.key, ...c.payload.val()
    }));
   });
  }
  ...
  deleteCourse(course) {
    console.log(course.key);
    this.db.object('/courses/' + course.key).remove();
  }
}
</code>```

Body:
The question has been answered but I'm looking for a, um, more straightforward one if available. It seems strange that we'd have to implement not one but two mappings just to have access to the object keys.

basic firebase db:

As can be seen, the course objects clearly have keys.
Mark-up:

    Key: {{course.$key}}

Body:
Updated Answer

Rxjs have changed how it pipes data. now you have to use .pipe().

this.courses$ = this.courses.snapshotChanges().pipe(
  map(changes =>
    changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
  )
);

Original Answer

.valueChanges() contain simply data, no key with it. you need to use .snapshotChanges()

this.courses$ = this.courses.snapshotChanges().map(changes => {
  return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});

now just use {{course.key}}

here is your corrected code

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

export class AppComponent {
  courseRef: AngularFireList<any>;
  courses$: Observable<any[]>;

  constructor(private db: AngularFireDatabase) {
    this.courseRef = db.list('/courses');
    this.courses$ = this.courseRef.snapshotChanges().map(changes => {
        return changes.map(c => ({ key: c.payload.key, ...c.payload.val()
    }));
   });
  }
  ...
  deleteCourse(course) {
    console.log(course.key);
    this.db.object('/courses/' + course.key).remove();
  }
}