问:
How to create loop where answer of first calculation is part of equation for second calculation etc
I am trying to create a loop in R that runs for 10 stages (say 10 years) when the results from year 1 are incorporated into the calculation for year 2 etc.. I'm sure this should be easy to do but I don't know if this type of calculation has a specific name so I haven't known what to search for..

so I'm basically going for something that would do the following:

```<code>(a*1.5)-(b*4)=c
(c*1.5)-(b*4)=d
(d*1.5)-(b*4)=e
</code>```

etc...
until you get the result of the tenth stage, but to organise it all as one equation

答:
What you are doing is simply called an iterative calculation.  You could do it like this:

```<code>a <- 2
b <- 3   # Replace these with your real starting values
for (i in 1:10) {
  a <- (a*1.5) - (b*4)
  print(c(i, a))
}
</code>```

The print statement isn't needed, but helps to show what is happening at each step:  your iteration diverges with those starting values.

```<code>[1]  1 -9
[1]   2.0 -25.5
[1]   3.00 -50.25
[1]   4.000 -87.375
[1]    5.0000 -143.0625
[1]    6.0000 -226.5938
[1]    7.0000 -351.8906
[1]    8.0000 -539.8359
[1]    9.0000 -821.7539
[1]    10.000 -1244.631
</code>```

Body:
I am trying to create a loop in R that runs for 10 stages (say 10 years) when the results from year 1 are incorporated into the calculation for year 2 etc.. I'm sure this should be easy to do but I don't know if this type of calculation has a specific name so I haven't known what to search for..

so I'm basically going for something that would do the following:

(a*1.5)-(b*4)=c
(c*1.5)-(b*4)=d
(d*1.5)-(b*4)=e

etc...
until you get the result of the tenth stage, but to organise it all as one equation

Body:
What you are doing is simply called an iterative calculation.  You could do it like this:

a <- 2
b <- 3   # Replace these with your real starting values
for (i in 1:10) {
  a <- (a*1.5) - (b*4)
  print(c(i, a))
}

The print statement isn't needed, but helps to show what is happening at each step:  your iteration diverges with those starting values.

[1]  1 -9
[1]   2.0 -25.5
[1]   3.00 -50.25
[1]   4.000 -87.375
[1]    5.0000 -143.0625
[1]    6.0000 -226.5938
[1]    7.0000 -351.8906
[1]    8.0000 -539.8359
[1]    9.0000 -821.7539
[1]    10.000 -1244.631


来源: stackexchange

问:
Android YouTube API "An error occurred while initializing YouTube player"
I have an android app, which allows to play youtube video. I am using the latest YouTube API (1.2.1). I try it on a several devices within android version 4.0.4, 4.3, 4.4.4 or 5.0 and it works perfect (on every device is YouTube app version 10.-. But on one device, where is android 4.0.4 and YouTube app version 4.4.11 it does not work and get an error "An error occurred while initializing YouTube player". In documentation is written, that the minimal required version of YouTube app is 4.2.16. So I don't know, where is the problem.

Does somebody have an idea, what is wrong or how can I fix it?

Thanks a lot...

答:
I would never have thought to look in that location for the settings. It worked just as you said.

Here are the instructions for that less knowledge of the settings.

First, you need to go Settings -> battery -> app launch -> YouTube.

Now make disable the option manage automatically.

After disabling the above option, a popup will be shown.

Now make enable the option Secondary Launch (can be launched by other apps)

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
How to set grid-template
My css is below. What I want is the header shall be fixed at top of the page and having width equal to the width of container irrespective to the changing width of browser. However, I always get the width of header expands over the width of Container. Please instruct me how to fix it?

html {
  font-size: 16px;
}

.container {
  width: 80%;
  margin: 0 auto;
}

header {
  width: 100%;
  display: grid;
  grid-template-columms: auto auto;
  grid-template-rows: 170px 60px;
  position: fixed;
  top: 0px;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <header>
    <div class="cart">
    </div>
  </header></code>```

答:
Set the width of the header to 80%;

Works automatically..

 * {
  margin:0;
  padding:0;
 }
.container {
  width: 80%;
  margin: auto;
  border: 1px solid red;
  height: 150vh;
}

header {
  background: green;
  position: fixed;
  width: 80%;
  top: 0;
  height: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <header>
    <div class="cart">
    </div>
  </header></code>```

Codepen Demo

Title: How to set grid-template

Body:
Set the width of the header to 80%;

Works automatically..

 * {
  margin:0;
  padding:0;
 }
.container {
  width: 80%;
  margin: auto;
  border: 1px solid red;
  height: 150vh;
}

header {
  background: green;
  position: fixed;
  width: 80%;
  top: 0;
  height: 50px;
}

<div class="container">
  <header>
    <div class="cart">
    </div>
  </header>

Codepen Demo


问:
String that ends wih a single underscore character
I am trying to find the correct regular expression that detects string that end with a single underscore, e.g. hello_, this_. So far I have re.match("[aA-zZ](_)", string) but detects strings like, day__, ball__, i.e, with two underscores which i do not want. Any ideas how to get string with a single underscore in the end.

Thanks

答:
You could also update your character class to use a-z and A-Z and then match a single underscore:

```<code>[a-zA-Z]_$
</code>```

For example using re.search

```<code>pattern = "[a-zA-Z]_$"
re.search(pattern, "day__")
</code>```

Python demo

Note that [aA-zZ] which is the same as [A-z] is different from [a-zA-Z]

Body:
You could also update your character class to use a-z and A-Z and then match a single underscore:

[a-zA-Z]_$

For example using re.search

pattern = "[a-zA-Z]_$"
re.search(pattern, "day__")

Python demo

Note that [aA-zZ] which is the same as [A-z] is different from [a-zA-Z]


问:
How to change stroke color of CAShaperLayer on button click
I am have create some custom layer and added on UIView ,i have two CAShaper Layer but i am just showing only one example here

```<code>    hexBorderOtline = CAShapeLayer()
    hexBorderOtline.name = "dhiru_border_hidden"
    hexBorderOtline.path = path2.cgPath
    hexBorderOtline.lineCap = .round
    hexBorderOtline.strokeColor = inActiveBorderColor.cgColor
    hexBorderOtline.fillColor = UIColor.clear.cgColor
    self.layer.addSublayer(hexBorderOtline)
</code>```

I want to change it's border color when button is clicked.

```<code>func btnAction()
{
    hexBorderOtline.strokeColor = activeBorderColor.cgColor
}
</code>```

But this is not working , i am posting one reference image  what i need to do on button click .

答:
Try this:

```<code>func btnAction()
{
    hexBorderOtline.removeFromSuperlayer()
    hexBorderOtline.strokeColor = activeBorderColor.cgColor
    self.layer.addSublayer(hexBorderOtline)
}
</code>```

Without UIView:

```<code>class ViewController: UIViewController {

    var hexBorderOtline: CAShapeLayer!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        hexBorderOtline = CAShapeLayer()
        hexBorderOtline.name = "dhiru_border_hidden"
        hexBorderOtline.path = UIBezierPath(arcCenter: CGPoint(x:self.view.frame.size.width/2, y: self.view.frame.size.height/2), radius: self.view.frame.size.height/2, startAngle: 180, endAngle: 0.0, clockwise: true).cgPath
        hexBorderOtline.lineCap = .round
        hexBorderOtline.strokeColor = UIColor.gray.cgColor
        hexBorderOtline.fillColor = UIColor.clear.cgColor
        self.view.layer.addSublayer(hexBorderOtline)
    }

    @IBAction func updateColor(_ sender: Any) {
        hexBorderOtline.removeFromSuperlayer()
        hexBorderOtline.strokeColor = UIColor.red.cgColor
        self.view.layer.addSublayer(hexBorderOtline)
    }
}
</code>```

Body:
I am have create some custom layer and added on UIView ,i have two CAShaper Layer but i am just showing only one example here

    hexBorderOtline = CAShapeLayer()
    hexBorderOtline.name = "dhiru_border_hidden"
    hexBorderOtline.path = path2.cgPath
    hexBorderOtline.lineCap = .round
    hexBorderOtline.strokeColor = inActiveBorderColor.cgColor
    hexBorderOtline.fillColor = UIColor.clear.cgColor
    self.layer.addSublayer(hexBorderOtline)

I want to change it's border color when button is clicked.

func btnAction()
{
    hexBorderOtline.strokeColor = activeBorderColor.cgColor
}

But this is not working , i am posting one reference image  what i need to do on button click .

Body:
Try this:

func btnAction()
{
    hexBorderOtline.removeFromSuperlayer()
    hexBorderOtline.strokeColor = activeBorderColor.cgColor
    self.layer.addSublayer(hexBorderOtline)
}

Without UIView:

class ViewController: UIViewController {

    var hexBorderOtline: CAShapeLayer!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        hexBorderOtline = CAShapeLayer()
        hexBorderOtline.name = "dhiru_border_hidden"
        hexBorderOtline.path = UIBezierPath(arcCenter: CGPoint(x:self.view.frame.size.width/2, y: self.view.frame.size.height/2), radius: self.view.frame.size.height/2, startAngle: 180, endAngle: 0.0, clockwise: true).cgPath
        hexBorderOtline.lineCap = .round
        hexBorderOtline.strokeColor = UIColor.gray.cgColor
        hexBorderOtline.fillColor = UIColor.clear.cgColor
        self.view.layer.addSublayer(hexBorderOtline)
    }

    @IBAction func updateColor(_ sender: Any) {
        hexBorderOtline.removeFromSuperlayer()
        hexBorderOtline.strokeColor = UIColor.red.cgColor
        self.view.layer.addSublayer(hexBorderOtline)
    }
}


问:
Why Does My Java Private Key Signature Not Match My Openssl Signature?
So the signature that I'm getting from Java doesn't match what I'm getting in openssl.  Here's an example of what I'm doing:

In a terminal using openssl I'm doing this.

```<code>    echo +pkCdYME5SzI7A2PV0r8/8FqYGZyvTp+4DoGkdaMYRs= hash
    openssl dgst -sha256 -sign "private.key" -out hash.sha256 hash
    base64 < hash.sha256 > hash.bin
    cat hash.bin
    results posted below
</code>```

Java Code: (hash matches the one I'm using for openssl)

```<code>    private String createSignature(String hash) throws ProductException {
      try {
        Signature privateSignature = Signature.getInstance("SHA256withRSA");
        privateSignature.initSign(getPrivateKey());
        privateSignature.update(hash.getBytes(UTF_8));
        byte[] signature = privateSignature.sign();
        String result = Base64.encodeBase64String(signature);
        System.out.println(result); //THIS RESULT SHOULD MATCH BUT DOESN'T
        return result;
      } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
        throw new ProductException(Codes.AUTHENTICATION_ERROR, e);
      }
    }
    private PrivateKey getPrivateKey() throws ProductException {
      try {
        String key = IOUtils.toString(this.getClass().getResourceAsStream("private.key"));
        PemObject pem = new PemReader(new StringReader(key)).readPemObject();
        byte[] content = pem.getContent();
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(content);
        return keyFactory.generatePrivate(ks);
      } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new ProductException(Codes.AUTHENTICATION_ERROR, e);
      }
    }
</code>```

PLEASE HELP!  I've scoured the interwebs and I don't know what I'm doing wrong.

My openssl signature =
O8DRek17ySzz+p2N8brH/9CdY3b+GN5bnyaTtn+ZP3SDIBvtqkk/lp+zb1BZ80a6xCIID8CTjNU+/svrV/q/rXEqEQc3jk3ZVUo0RJB52rgW26EQWyieAdqRlIbQqPhaCIrpWrs+WImGk7cPnkTEueIm+EzxG8ptjF5cAZH3lustVLt8SM9sXjQJzxzMgF2g0XN+1GQniAdWT/oNJXv0ZG7PSFACfcoSTSdN4wHkVAG4/PF/d6H+M5eTkEu6NhXfbfBBtavGmBiDgM6FPFDJ4r+2Rzvc/vpSiglUUQgxD58PTH47Y8xMc4t4/yahrchi2if2cJ7e89RBb1IHNus+eB8zPS0MHBn2OWDUM66P1KRanwzebDfg08VhRbW8zVnmNUNzXxAdCWa3kwsDe7hx+36oHfJwoyqIFwjJi8TKZm0JLKMf0SaLh/6zK0bIdgoXw23AfJni1ewmUqZbpE6Q4A0TgxaJg1aozb06l7Nb523FqV6ScRZ0wJK3s51Dduy5j1V1jt0+YYd+0zACyYfr5a+vypEygzsZ2Rzu3Q/l4VoPlZF2dr50TLnbhTvFnyK9mvc0zaTmsuHI5UJAbcpFBTXiDWb0DoWo4PkHRVFPvIMai37UxW4c5V0ybchlQHrEKYQ8NigYHGX5j8GsFhZJgg73Het1YwoWdsz1PksoYTY=

My Java Signature =
8dKc1otqL+thKQ7yTPeHX7T5fuOgv6PmHvlP5QyEHEXZILwD/234polMSs20i4na9wCuUdcSA+mHEKpY7Dkyd8VLTcZZ8RC8AlPE5bvzXc/uZhyPpBuSA7mDDOARbg3mx5usq4ythdqxj6OvdOBAJXXFB6Jc/c1XVd8IxDnRJoz5MlwxZIp94TAyW11QbMGNZuzcbsdEdsBuXU1MR4gzVfMLJjMcIM3YTtsP3bktsPAs5W2Asp9lDg5GuIOgWgXpTlj3VY6NF64SCI1tY4LhE7zq16YXQ6ykJ490YSVX5J9z+cDvZcVgfvgKCZuk4wgnXo6PbE4Wm4FDuzu35DEQi9Y5EEHzXlb5aNFQP3S6lumyfqOCmZlQcNVS53ur1fY4P8cnOuHZelyYS1Dw54q0SDCjFuANK2Ltl8rIZOZQWbg6jo45HbpaHUgt1NMkmj/UC/rLSnofa/YYbcJ2YZbqUdyX/yTBlzEuLR0/4Bgv9zvBw8HI0h3icv7/1NYaKo/eBSki6HNyDh2pDWX6IHQTFMzdFKeoXVAQLfaJREIpMPu+rDExI6Ozl0r9D61fY+XtMrptGNTFzf1h4cwUAZAC737Ahc6qsr+jQkDWDJt6oJbgziNE4C2JZriRtvRDACpryt6MGH1QnYPGYfCVs/xSxaYEtGJsjRRkG+lkpojcJ+A=

答:
Most likely your issue comes from using echo for preparing an input to your signature function.
By default, echo appends a newline to whatever its output is, and the byte representing it messes up the signature.

Try echo -n that skips the newline and see if it works.

Body:
So the signature that I'm getting from Java doesn't match what I'm getting in openssl.  Here's an example of what I'm doing:

In a terminal using openssl I'm doing this.

    echo +pkCdYME5SzI7A2PV0r8/8FqYGZyvTp+4DoGkdaMYRs= hash
    openssl dgst -sha256 -sign "private.key" -out hash.sha256 hash
    base64 < hash.sha256 > hash.bin
    cat hash.bin
    results posted below

Java Code: (hash matches the one I'm using for openssl)

    private String createSignature(String hash) throws ProductException {
      try {
        Signature privateSignature = Signature.getInstance("SHA256withRSA");
        privateSignature.initSign(getPrivateKey());
        privateSignature.update(hash.getBytes(UTF_8));
        byte[] signature = privateSignature.sign();
        String result = Base64.encodeBase64String(signature);
        System.out.println(result); //THIS RESULT SHOULD MATCH BUT DOESN'T
        return result;
      } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
        throw new ProductException(Codes.AUTHENTICATION_ERROR, e);
      }
    }
    private PrivateKey getPrivateKey() throws ProductException {
      try {
        String key = IOUtils.toString(this.getClass().getResourceAsStream("private.key"));
        PemObject pem = new PemReader(new StringReader(key)).readPemObject();
        byte[] content = pem.getContent();
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(content);
        return keyFactory.generatePrivate(ks);
      } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new ProductException(Codes.AUTHENTICATION_ERROR, e);
      }
    }

PLEASE HELP!  I've scoured the interwebs and I don't know what I'm doing wrong.

My openssl signature =
O8DRek17ySzz+p2N8brH/9CdY3b+GN5bnyaTtn+ZP3SDIBvtqkk/lp+zb1BZ80a6xCIID8CTjNU+/svrV/q/rXEqEQc3jk3ZVUo0RJB52rgW26EQWyieAdqRlIbQqPhaCIrpWrs+WImGk7cPnkTEueIm+EzxG8ptjF5cAZH3lustVLt8SM9sXjQJzxzMgF2g0XN+1GQniAdWT/oNJXv0ZG7PSFACfcoSTSdN4wHkVAG4/PF/d6H+M5eTkEu6NhXfbfBBtavGmBiDgM6FPFDJ4r+2Rzvc/vpSiglUUQgxD58PTH47Y8xMc4t4/yahrchi2if2cJ7e89RBb1IHNus+eB8zPS0MHBn2OWDUM66P1KRanwzebDfg08VhRbW8zVnmNUNzXxAdCWa3kwsDe7hx+36oHfJwoyqIFwjJi8TKZm0JLKMf0SaLh/6zK0bIdgoXw23AfJni1ewmUqZbpE6Q4A0TgxaJg1aozb06l7Nb523FqV6ScRZ0wJK3s51Dduy5j1V1jt0+YYd+0zACyYfr5a+vypEygzsZ2Rzu3Q/l4VoPlZF2dr50TLnbhTvFnyK9mvc0zaTmsuHI5UJAbcpFBTXiDWb0DoWo4PkHRVFPvIMai37UxW4c5V0ybchlQHrEKYQ8NigYHGX5j8GsFhZJgg73Het1YwoWdsz1PksoYTY=

My Java Signature =
8dKc1otqL+thKQ7yTPeHX7T5fuOgv6PmHvlP5QyEHEXZILwD/234polMSs20i4na9wCuUdcSA+mHEKpY7Dkyd8VLTcZZ8RC8AlPE5bvzXc/uZhyPpBuSA7mDDOARbg3mx5usq4ythdqxj6OvdOBAJXXFB6Jc/c1XVd8IxDnRJoz5MlwxZIp94TAyW11QbMGNZuzcbsdEdsBuXU1MR4gzVfMLJjMcIM3YTtsP3bktsPAs5W2Asp9lDg5GuIOgWgXpTlj3VY6NF64SCI1tY4LhE7zq16YXQ6ykJ490YSVX5J9z+cDvZcVgfvgKCZuk4wgnXo6PbE4Wm4FDuzu35DEQi9Y5EEHzXlb5aNFQP3S6lumyfqOCmZlQcNVS53ur1fY4P8cnOuHZelyYS1Dw54q0SDCjFuANK2Ltl8rIZOZQWbg6jo45HbpaHUgt1NMkmj/UC/rLSnofa/YYbcJ2YZbqUdyX/yTBlzEuLR0/4Bgv9zvBw8HI0h3icv7/1NYaKo/eBSki6HNyDh2pDWX6IHQTFMzdFKeoXVAQLfaJREIpMPu+rDExI6Ozl0r9D61fY+XtMrptGNTFzf1h4cwUAZAC737Ahc6qsr+jQkDWDJt6oJbgziNE4C2JZriRtvRDACpryt6MGH1QnYPGYfCVs/xSxaYEtGJsjRRkG+lkpojcJ+A=


问:
What packages do I need for a working CPAN tool chain under cygwin64?
There are a couple of perl modules I often use on my *nix systems (FreeBSD, Linux, Mac). I always install these from cpan. Earlier this year I needed to use some of these on a 64-bit Windows system, and in about 2 hours I got the then-most-recent Strawberry Perl package installed, and from cpan I installed the modules of my desire the same way I used to do under *nix. Everything worked as expected.

On another 64-bit Windows system I am now attempting to set up a cygwin64 environment instead of installing Strawberry Perl. There are a handful of tools we need on that system, and those are already working fine under cygwin64, so it seems like a good idea to add the new perl functionality to the already existing cygwin64 environment. To test this possibility without messing with the production environment, I am performing trial/error setups on a separate, clean Windows system.

I downloaded the now current cygwin64 installer, and can get all the tools we required in the past installed fine. I can also get perl5 installed. But installing modules via "cpan install" does not work.
Unfortunatelly, I am not really aware of the *nix packages that cpan depends on, because all on my unices (and apparently with Strawberry Perl under Windows too) every dependency is installed automatically, and I never had to care about these.
My cygwin64 environment obviously misses some packages required by the build process run by cpan. But cpan in cygwin64 does a very bad job of communicating what is missing or what is wrong.

I tried installing multiple combinations of clang, gcc, mingw and other developer tools using the cygwin installer, but still could not get "cpan install desired::module" working. Depending on the package mixture I used, I get different errors (or signs of errors).

As a fairly reliable starting point, could you please give me a list of cygwin packages I should most certainly install, in order to have an environment where "cpan install ..." is supposed to succeed.

Addition#1:

If I install only the most basic cygwin packages (zsh, perl) and those that come anyway, I end up with this ...

```<code>keve@cygtest ~
$ perl -v

This is perl 5, version 26, subversion 3 (v5.26.3) built for     x86_64-cygwin-threads-multi
(with 7 registered patches, see perl -V for more detail)

Copyright 1987-2018, Larry Wall

Perl may be copied only under the terms of either the Artistic License or     the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl".  If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.

keve@cygtest ~
$ curl --version
curl 7.55.1 (Windows) libcurl/7.55.1 WinSSL
Release-Date: [unreleased]
Protocols: dict file ftp ftps http https imap imaps pop3 pop3s smtp smtps     telnet tftp
Features: AsynchDNS IPv6 Largefile SSPI Kerberos SPNEGO NTLM SSL
</code>```

Any of make, gmake, cmake, nmake, gcc, clang results in a "command not found" response.

Starting cpan does this ...

```<code>$ cpan
Loading internal null logger. Install Log::Log4perl for logging messages
Sorry, we have to rerun the configuration dialog for CPAN.pm due to
some missing parameters. Configuration will be written to
 <</home/Valaki/.cpan/CPAN/MyConfig.pm>>

CPAN.pm requires configuration, but most of it can be done automatically.
If you answer 'no' below, you will enter an interactive dialog for each
configuration option instead.

Would you like to configure as much as possible automatically? [yes]

Use of uninitialized value $what in concatenation (.) or string at /usr/share/perl5/5.26/App/Cpan.pm line 669, <STDIN> line 1.
 <install_help>

Warning: You do not have write permission for Perl library directories.

To install modules, you need to configure a local Perl library directory or
escalate your privileges.  CPAN can help you by bootstrapping the local::lib
module or by configuring itself to use 'sudo' (if available).  You may also
resolve this problem manually if you need to customize your setup.

What approach do you want?  (Choose 'local::lib', 'sudo' or 'manual')
 [local::lib]

 ALERT: 'make' is an essential tool for building perl Modules.
Please make sure you have 'make' (or some equivalent) working.

Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
</code>```

and that "Press SPACE and ENTER" line keeps filling my screen until I press Ctrl+C.

So, I start the Cygwin installer again, and install the devel/make package. That way I have this ...

```<code>$ make -v
GNU Make 4.2.1
Built for x86_64-unknown-cygwin
Copyright (C) 1988-2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

$ cpan
Loading internal null logger. Install Log::Log4perl for logging messages
Sorry, we have to rerun the configuration dialog for CPAN.pm due to
some missing parameters. Configuration will be written to
 <</home/Valaki/.cpan/CPAN/MyConfig.pm>>

CPAN.pm requires configuration, but most of it can be done automatically.
If you answer 'no' below, you will enter an interactive dialog for each
configuration option instead.

Would you like to configure as much as possible automatically? [yes]

Use of uninitialized value $what in concatenation (.) or string at /usr/share/perl5/5.26/App/Cpan.pm line 669, <STDIN> line 1.
 <install_help>

Warning: You do not have write permission for Perl library directories.

To install modules, you need to configure a local Perl library directory or
escalate your privileges.  CPAN can help you by bootstrapping the local::lib
module or by configuring itself to use 'sudo' (if available).  You may also
resolve this problem manually if you need to customize your setup.

What approach do you want?  (Choose 'local::lib', 'sudo' or 'manual')
 [local::lib]

Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
</code>```

This time there is no warning about "make" missing, but the same "Press SPACE and ENTER" line fills the screen. There is still that "uninitialised $what", and the warning about not having proper permissions to folders. Which I have seen in questions by others, usually fixed by reinstalling the perl package with the most recent one (I have the most recent one).

So, what package do I miss?
Or did I make a wrong choice above by accepting the default?
Please note: I have installed additional devel packages with my earlier attempts. But to keep things simple for now, I only have "perl" and "make".

Addition#2

Following the answers by Håkon and mob, I started the cygwin installer again, and installed the recommended packages. So now I have devel/binutils, devel/clang, devel/cmake, devel/gcc-core, devel/gcc-g++, gccmakedep, and make installed. Also available is curl, which was already present so I did not need to install (perhaps came as a dependency).

Unfortunately, I still get this when starting "cpan":

```<code>$ cpan
Loading internal null logger. Install Log::Log4perl for logging messages
Sorry, we have to rerun the configuration dialog for CPAN.pm due to
some missing parameters. Configuration will be written to
 <</home/Valaki/.cpan/CPAN/MyConfig.pm>>

CPAN.pm requires configuration, but most of it can be done automatically.
If you answer 'no' below, you will enter an interactive dialog for each
configuration option instead.

Would you like to configure as much as possible automatically? [yes]

Use of uninitialized value $what in concatenation (.) or string at /usr/share/perl5/5.26/App/Cpan.pm line 669, <STDIN> line 1.
 <install_help>

Warning: You do not have write permission for Perl library directories.

To install modules, you need to configure a local Perl library directory or
escalate your privileges.  CPAN can help you by bootstrapping the local::lib
module or by configuring itself to use 'sudo' (if available).  You may also
resolve this problem manually if you need to customize your setup.

What approach do you want?  (Choose 'local::lib', 'sudo' or 'manual')
 [local::lib]

Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
</code>```

Regarding the $what warning:
Lines 660 to 670 of Cpan.pm go like this ...

```<code>BEGIN {
my $scalar = '';

sub _hook_into_CPANpm_report
    {
    no warnings 'redefine';

    *CPAN::Shell::myprint = sub {
        my($self,$what) = @_;
        $scalar .= $what;
</code>```

I can get rid of the warning by modifying line 669 to this ...

```<code>$scalar .= ($what // '');
</code>```

... but this does not solve the problem of why $what is undefined anyway. However, I still end up seeing that "Press SPACE and ENTER to disable curl" filling up the screen. And the same happens if I type "manual" and hit Enter instead of accepting the default local::lib option.

答:
Based on my own set of installed packages and my memory about which ones are useful in the cpan toolchain:</p>

```<code>binutils
bzip2
clang
cmake
gcc-core
gcc-g++
gccmakedep
make
curl  and/or  wget
</code>```

Body:
There are a couple of perl modules I often use on my *nix systems (FreeBSD, Linux, Mac). I always install these from cpan. Earlier this year I needed to use some of these on a 64-bit Windows system, and in about 2 hours I got the then-most-recent Strawberry Perl package installed, and from cpan I installed the modules of my desire the same way I used to do under *nix. Everything worked as expected.

On another 64-bit Windows system I am now attempting to set up a cygwin64 environment instead of installing Strawberry Perl. There are a handful of tools we need on that system, and those are already working fine under cygwin64, so it seems like a good idea to add the new perl functionality to the already existing cygwin64 environment. To test this possibility without messing with the production environment, I am performing trial/error setups on a separate, clean Windows system.

I downloaded the now current cygwin64 installer, and can get all the tools we required in the past installed fine. I can also get perl5 installed. But installing modules via "cpan install" does not work.
Unfortunatelly, I am not really aware of the *nix packages that cpan depends on, because all on my unices (and apparently with Strawberry Perl under Windows too) every dependency is installed automatically, and I never had to care about these.
My cygwin64 environment obviously misses some packages required by the build process run by cpan. But cpan in cygwin64 does a very bad job of communicating what is missing or what is wrong.

I tried installing multiple combinations of clang, gcc, mingw and other developer tools using the cygwin installer, but still could not get "cpan install desired::module" working. Depending on the package mixture I used, I get different errors (or signs of errors).

As a fairly reliable starting point, could you please give me a list of cygwin packages I should most certainly install, in order to have an environment where "cpan install ..." is supposed to succeed.

Addition#1:

If I install only the most basic cygwin packages (zsh, perl) and those that come anyway, I end up with this ...

keve@cygtest ~
$ perl -v

This is perl 5, version 26, subversion 3 (v5.26.3) built for     x86_64-cygwin-threads-multi
(with 7 registered patches, see perl -V for more detail)

Copyright 1987-2018, Larry Wall

Perl may be copied only under the terms of either the Artistic License or     the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl".  If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.

keve@cygtest ~
$ curl --version
curl 7.55.1 (Windows) libcurl/7.55.1 WinSSL
Release-Date: [unreleased]
Protocols: dict file ftp ftps http https imap imaps pop3 pop3s smtp smtps     telnet tftp
Features: AsynchDNS IPv6 Largefile SSPI Kerberos SPNEGO NTLM SSL

Any of make, gmake, cmake, nmake, gcc, clang results in a "command not found" response.

Starting cpan does this ...

$ cpan
Loading internal null logger. Install Log::Log4perl for logging messages
Sorry, we have to rerun the configuration dialog for CPAN.pm due to
some missing parameters. Configuration will be written to
 <</home/Valaki/.cpan/CPAN/MyConfig.pm>>

CPAN.pm requires configuration, but most of it can be done automatically.
If you answer 'no' below, you will enter an interactive dialog for each
configuration option instead.

Would you like to configure as much as possible automatically? [yes]

Use of uninitialized value $what in concatenation (.) or string at /usr/share/perl5/5.26/App/Cpan.pm line 669, <STDIN> line 1.
 <install_help>

Warning: You do not have write permission for Perl library directories.

To install modules, you need to configure a local Perl library directory or
escalate your privileges.  CPAN can help you by bootstrapping the local::lib
module or by configuring itself to use 'sudo' (if available).  You may also
resolve this problem manually if you need to customize your setup.

What approach do you want?  (Choose 'local::lib', 'sudo' or 'manual')
 [local::lib]

 ALERT: 'make' is an essential tool for building perl Modules.
Please make sure you have 'make' (or some equivalent) working.

Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl

and that "Press SPACE and ENTER" line keeps filling my screen until I press Ctrl+C.

So, I start the Cygwin installer again, and install the devel/make package. That way I have this ...

$ make -v
GNU Make 4.2.1
Built for x86_64-unknown-cygwin
Copyright (C) 1988-2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

$ cpan
Loading internal null logger. Install Log::Log4perl for logging messages
Sorry, we have to rerun the configuration dialog for CPAN.pm due to
some missing parameters. Configuration will be written to
 <</home/Valaki/.cpan/CPAN/MyConfig.pm>>

CPAN.pm requires configuration, but most of it can be done automatically.
If you answer 'no' below, you will enter an interactive dialog for each
configuration option instead.

Would you like to configure as much as possible automatically? [yes]

Use of uninitialized value $what in concatenation (.) or string at /usr/share/perl5/5.26/App/Cpan.pm line 669, <STDIN> line 1.
 <install_help>

Warning: You do not have write permission for Perl library directories.

To install modules, you need to configure a local Perl library directory or
escalate your privileges.  CPAN can help you by bootstrapping the local::lib
module or by configuring itself to use 'sudo' (if available).  You may also
resolve this problem manually if you need to customize your setup.

What approach do you want?  (Choose 'local::lib', 'sudo' or 'manual')
 [local::lib]

Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl

This time there is no warning about "make" missing, but the same "Press SPACE and ENTER" line fills the screen. There is still that "uninitialised $what", and the warning about not having proper permissions to folders. Which I have seen in questions by others, usually fixed by reinstalling the perl package with the most recent one (I have the most recent one).

So, what package do I miss?
Or did I make a wrong choice above by accepting the default?
Please note: I have installed additional devel packages with my earlier attempts. But to keep things simple for now, I only have "perl" and "make".

Addition#2

Following the answers by Håkon and mob, I started the cygwin installer again, and installed the recommended packages. So now I have devel/binutils, devel/clang, devel/cmake, devel/gcc-core, devel/gcc-g++, gccmakedep, and make installed. Also available is curl, which was already present so I did not need to install (perhaps came as a dependency).

Unfortunately, I still get this when starting "cpan":

$ cpan
Loading internal null logger. Install Log::Log4perl for logging messages
Sorry, we have to rerun the configuration dialog for CPAN.pm due to
some missing parameters. Configuration will be written to
 <</home/Valaki/.cpan/CPAN/MyConfig.pm>>

CPAN.pm requires configuration, but most of it can be done automatically.
If you answer 'no' below, you will enter an interactive dialog for each
configuration option instead.

Would you like to configure as much as possible automatically? [yes]

Use of uninitialized value $what in concatenation (.) or string at /usr/share/perl5/5.26/App/Cpan.pm line 669, <STDIN> line 1.
 <install_help>

Warning: You do not have write permission for Perl library directories.

To install modules, you need to configure a local Perl library directory or
escalate your privileges.  CPAN can help you by bootstrapping the local::lib
module or by configuring itself to use 'sudo' (if available).  You may also
resolve this problem manually if you need to customize your setup.

What approach do you want?  (Choose 'local::lib', 'sudo' or 'manual')
 [local::lib]

Press SPACE and ENTER to disable curl
Press SPACE and ENTER to disable curl

Regarding the $what warning:
Lines 660 to 670 of Cpan.pm go like this ...

BEGIN {
my $scalar = '';

sub _hook_into_CPANpm_report
    {
    no warnings 'redefine';

    *CPAN::Shell::myprint = sub {
        my($self,$what) = @_;
        $scalar .= $what;

I can get rid of the warning by modifying line 669 to this ...

$scalar .= ($what // '');

... but this does not solve the problem of why $what is undefined anyway. However, I still end up seeing that "Press SPACE and ENTER to disable curl" filling up the screen. And the same happens if I type "manual" and hit Enter instead of accepting the default local::lib option.

Body:
Based on my own set of installed packages and my memory about which ones are useful in the cpan toolchain:

binutils
bzip2
clang
cmake
gcc-core
gcc-g++
gccmakedep
make
curl  and/or  wget


问:
Bootstrap-select on click get clicked value
I am using a jQuery plug-in: bootstrap-select.js my HTML is select(multiple) -> option. I would like to get the currently clicked on option value when a user selects or deselects the option.

Example: User selects Item 4 = console.log item 4. Then the user also selects Item 2 = console.log item 2. Currently i'm getting item 4, item 2... they are always in a array and not individual.

My end goal is to show and hide divs on the page depending on what the user has selected. There will be multiple select option fields.

HTML code:

```<code><fieldset class="dreamT">
   <select name="team" id="team" multiple class="dropdown selectpicker show-menu-arrow show-tick form-control" title="Pelaajat" data-width="100%" data-size="auto" multiple data-selected-text-format="count > 2">
    <optgroup>
        <option value="item 1">Item 1</option>
        <option value="item 2">Item 2</option>
        <option value="item 3">Item 3</option>
        <option value="item 4">Item 4</option>
        <option value="item 5">Item 5</option>
        <option disabled value="item 6">Item 6</option>
    </optgroup>
   </select>
</fieldset>
</code>```

JS code:

```<code>$("select#team").on("change", function(value){
   var This      = $(this);
   var selectedD = $(this).val();
   console.log(selectedD);
});
</code>```

Current output: ["item 1", "item 3", "item 4", "item 5"]

Plug-in site: bootstrap-select

答:
Try this:

```<code>console.log(("#your-id option:selected").text());
</code>```

ref : enter link description here

Body:
I am using a jQuery plug-in: bootstrap-select.js my HTML is select(multiple) -> option. I would like to get the currently clicked on option value when a user selects or deselects the option.

Example: User selects Item 4 = console.log item 4. Then the user also selects Item 2 = console.log item 2. Currently i'm getting item 4, item 2... they are always in a array and not individual.

My end goal is to show and hide divs on the page depending on what the user has selected. There will be multiple select option fields.

HTML code:

<fieldset class="dreamT">
   <select name="team" id="team" multiple class="dropdown selectpicker show-menu-arrow show-tick form-control" title="Pelaajat" data-width="100%" data-size="auto" multiple data-selected-text-format="count > 2">
    <optgroup>
        <option value="item 1">Item 1</option>
        <option value="item 2">Item 2</option>
        <option value="item 3">Item 3</option>
        <option value="item 4">Item 4</option>
        <option value="item 5">Item 5</option>
        <option disabled value="item 6">Item 6</option>
    </optgroup>
   </select>
</fieldset>

JS code:

$("select#team").on("change", function(value){
   var This      = $(this);
   var selectedD = $(this).val();
   console.log(selectedD);
});

Current output: ["item 1", "item 3", "item 4", "item 5"]

Plug-in site: bootstrap-select

Body:
Try this:

console.log(("#your-id option:selected").text());

ref : enter link description here


问:
Deleting a cell in tableview, the cell also can be reused,why?
at first,i delete one cell in tableView,then i want to add another new cell in the tableView,but the  new cell is not new,it is just the cell which i delete. i know what dequeueReusableCellWithIdentifier means.i think when  delete one cell,the cache in dequeueReusableCellWithIdentifier is also deleted.why not?</p>

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"table reload");

    PDFModel* tempmodel=[PDFArray objectAtIndex:indexPath.row];
    NSString * CellIdentifier=tempmodel.PDFName;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSLog(@"cell %x",cell);
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
       //custom the cell
        cell.text=...
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleDelete)
    {
         [PDFArray removeObjectAtIndex:indexPath.row];
         NSMutableArray* array=[[NSMutableArray alloc] init];
         [array addObject:indexPath];
         [self.tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationRight];

    }
}
</code>```

答:
You seem confused by the difference between deleting a cell (an objective-c UI object) and the data it displays.

When you allow a user to delete a cell in the user interface you need to delete the corresponding data from your data model

The implementation of UITableView is highly optimized in iOS and it caches cells (UI objects) to improve performance. You don't really need to be concerned about this as your table will be optimally loaded and displayed based on your data.

In tableView:cellForRowAtIndexPath: you do the following:

Attempt to dequeue a cell instance. This takes advantage of caching done by UITableView

If dequeue does not return a cell, create a new one.

Once you have a cell, configure it with the appropriate data from your data model

When a user chooses a delete action from a cell, delete the data from your data model. optionally, you can animate removing the cell from the table or simply reload the whole table.

The specifics of #4 depend on the user interface you want and how you've configured your data model.

The Apple docs are pretty good about explaining this.

http://developer.apple.com/library/ios/#documentation/userexperience/conceptual/TableView_iPhone/AboutTableViewsiPhone/AboutTableViewsiPhone.html

Body:
at first,i delete one cell in tableView,then i want to add another new cell in the tableView,but the  new cell is not new,it is just the cell which i delete. i know what dequeueReusableCellWithIdentifier means.i think when  delete one cell,the cache in dequeueReusableCellWithIdentifier is also deleted.why not?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"table reload");

    PDFModel* tempmodel=[PDFArray objectAtIndex:indexPath.row];
    NSString * CellIdentifier=tempmodel.PDFName;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSLog(@"cell %x",cell);
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
       //custom the cell
        cell.text=...
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleDelete)
    {
         [PDFArray removeObjectAtIndex:indexPath.row];
         NSMutableArray* array=[[NSMutableArray alloc] init];
         [array addObject:indexPath];
         [self.tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationRight];

    }
}


问:
Unchecked cast behavior with and without assignment to variable
Why first line in main does not throw ClassCastException while the second does? </p>

```<code>import java.util.function.Function;

class Scratch {

    static <T> T getSomething(Function<Integer, T> fun) {
        return (T) fun;
    }

    public static void main(String[] args) {
        Scratch.<String>getSomething(x -> "hello");
        String something = Scratch.<String>getSomething(x -> "hello");
    }
}
</code>```

答:
The difference is because you don't use the result of the method in the first case, but you do in the second.

A cast is an expression, but it's not a StatementExpression. This means that you can't write this:

```<code>(String) somethingReturningAString();
</code>```

but you can write:

```<code>String aString = (String) somethingReturningAString();
</code>```

At compile time, the compiler inserts checkcast instructions where it needs to, and where it can:

It can't insert a cast for the first case, so no checking takes place.

It can (and has to) insert a cast in the second case, in order to ensure that it's assigning something that's actually a String to a String variable. As such, it checks the cast, and that fails.

It's worth noting that there are some perhaps unexpected cases where a cast isn't strictly necessary, but is inserted. For example:

```<code>Scratch.<String>getSomething(x -> "hello").toString();
</code>```

would fail with a ClassCastException, since it would be transformed to:

```<code>((String) Scratch.getSomething(x -> "hello")).toString();
</code>```

even though Object has a toString() method, and so it could invoke that without a cast.

Body:
Why first line in main does not throw ClassCastException while the second does?

import java.util.function.Function;

class Scratch {

    static <T> T getSomething(Function<Integer, T> fun) {
        return (T) fun;
    }

    public static void main(String[] args) {
        Scratch.<String>getSomething(x -> "hello");
        String something = Scratch.<String>getSomething(x -> "hello");
    }
}

Body:
The difference is because you don't use the result of the method in the first case, but you do in the second.

A cast is an expression, but it's not a StatementExpression. This means that you can't write this:

(String) somethingReturningAString();

but you can write:

String aString = (String) somethingReturningAString();

At compile time, the compiler inserts checkcast instructions where it needs to, and where it can:

It can't insert a cast for the first case, so no checking takes place.

It can (and has to) insert a cast in the second case, in order to ensure that it's assigning something that's actually a String to a String variable. As such, it checks the cast, and that fails.

It's worth noting that there are some perhaps unexpected cases where a cast isn't strictly necessary, but is inserted. For example:

Scratch.<String>getSomething(x -> "hello").toString();

would fail with a ClassCastException, since it would be transformed to:

((String) Scratch.getSomething(x -> "hello")).toString();

even though Object has a toString() method, and so it could invoke that without a cast.


问:
How to make left menu height grow according to the content on the right
I want the menu on the left to grow according to the content in the right, instead of setting the height of all the sections available.

In this case I would want the menu on the left to finish below the Choice 10 of the content in the right and then the menu would have a scroll (which I have already added in CSS).

Thanks in advance ! :)

@import url('https://fonts.googleapis.com/css?family=Roboto:400,400i');
* {
  font-family: Roboto, sans-serif !important;
}

@media screen and (max-width: 1300px) {
  .wrapper,
  .disclaimer {
    width: 90vw !important;
  }
}

ol {
  text-align: left;
}

.answered {
  font-weight: 900;
}

.answered::after {
  content: '•';
  color: black;
  margin-left: 10px;
  font-size: 15px;
}

.sections-choices {
  display: flex;
  align-items: flex-start;
  border: 1px solid #ddeafa;
  margin: 0 25px 15px 25px;
  width: 95%;
  margin-bottom: 15px;
  background-color: white;
  /* height: 300px;
                min-height: 300px;
                max-height: 350px; */
}

.sections {
  color: gainsboro;
  text-align: left;
  font-size: 13px;
  background-color: white;
  text-decoration: none;
  width: 20%;
  height: inherit;
  overflow-y: scroll;
}

.sections .question-select {
  margin-left: 10px;
}

.sections h4 {
  padding: 5px 0 5px 15px;
  background-color: #3a3838;
  color: white;
  margin-top: 0;
}

.sections .intro-text {
  padding-top: 2.5px;
  padding-bottom: 2.5px;
}

.sections a {
  text-decoration: none;
  color: black;
  padding-left: 15px;
}

.choices {
  color: black;
  font-size: 14px;
  text-align: left;
  width: 80%;
  padding-bottom: 15px;
  height: inherit;
}

.choices-section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: auto;
  background-color: #3a3838;
}

.choices-section-title h4 {
  margin: 0;
  padding: 15px 15px;
  color: white;
}

.choices-title {
  padding: 10px 15px 0 15px;
  line-height: 19px;
}

.help-text {
  padding: 5px 15px 0 15px;
  text-align: right;
  font-size: 11px;
}

.help-text p {
  margin: 0;
}

.choices-radio {
  padding: 15px 15px 0 25px;
}

.choices-radio label {
  /* word-wrap: break-word; */
  white-space: normal;
}

.choices-radio input {
  margin-bottom: 10px;
}

/* TOOLTIP */

.tooltip {
  position: relative;
  font-size: 12px;
  display: inline-flex;
  justify-content: flex-end;
  align-items: center;
  flex-direction: row;
  color: black;
}

.tooltip img {
  margin-right: 5px;
}

.tooltip .tooltiptext {
  visibility: hidden;
  width: 300px;
  background-color: #f7f7f7;
  color: black;
  text-align: left;
  border-radius: 6px;
  padding: 10px;
  /* Position the tooltip */
  position: absolute;
  z-index: 1;
  top: -5px;
  right: 105%;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
}

/* CHANGE RADIO BUTTONS ASPECT */

/* The container */

.radio-style {
  display: block;
  position: relative;
  padding-left: 25px;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 13px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* Hide the browser's default radio button */

.radio-style input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

/* Create a custom radio button */

.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 18px;
  width: 18px;
  background-color: gainsboro;
  border-radius: 50%;
}

/* On mouse-over, add a grey background color */

.radio-style:hover input~.checkmark {
  background-color: #ccc;
}

/* When the radio button is checked, add a blue background */

.radio-style input:checked~.checkmark {
  background-color: black;
}

/* Create the indicator (the dot/circle - hidden when not checked) */

.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

/* Show the indicator (dot/circle) when checked */

.radio-style input:checked~.checkmark:after {
  display: block;
}

/* Style the indicator (dot/circle) */

.radio-style .checkmark:after {
  top: 6px;
  left: 6px;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: white;
}

/* SCROLLBAR */

/* width */

 ::-webkit-scrollbar {
  width: 8px;
}

/* Track */

 ::-webkit-scrollbar-track {
  background: #f1f1f1;
}

/* Handle */

 ::-webkit-scrollbar-thumb {
  background: #888;
}

/* Handle on hover */

 ::-webkit-scrollbar-thumb:hover {
  background: #555;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<body style="margin: 0 auto; max-height: 70vh; background-color: #DCE3EA; text-align: center; margin-top: 15px; font-family: Roboto Condensed, sans-serif;">
  <div class="wrapper" style="padding: 15px 0; width: 70vw; margin: 0 auto; background-color: #ffffff; border-radius: 3px; border: 1px solid #c8c8c8;
    box-shadow: 2px 2px 8px #a8a8a8;">

    <div class="sections-choices">
      <div class="sections">
        <h4>1. Section 1</h4>
        <p class="question-select">Question 1</p>
        <p class="question-select">Question 2</p>
        <p class="question-select">Question 3</p>
        <p class="question-select">Question 4</p>

        <h4>2. Section 2</h4>
        <p class="question-select">Question 1</p>
        <p class="question-select">Question 2</p>

        <h4>3. Section 3</h4>
        <p class="question-select">Question 1</p>
        <p class="question-select">Question 2</p>
        <p class="question-select">Question 3</p>

        <h4>4. Section 4</h4>
        <p class="question-select">Question 1</p>

        <h4>5. Section 5</h4>
        <p class="question-select">Question 1</p>
        <p class="question-select">Question 2</p>
        <p class="question-select">Question 3</p>

        <h4>6. Section 6</h4>
        <p class="question-select">Question 1</p>
        <p class="question-select">Question 2</p>
        <p class="question-select">Question 3</p>
        <p class="question-select">Question 4</p>
        <p class="question-select">Question 5</p>
      </div>
      <div class="choices">
        <div class="choices-section-title">
          <h4>Section 1 out of 6</h4>
          <h4>Question 1 out of 4</h4>
        </div>
        <div class="choices-title"><b>1. This is Question 1 ?</b></div>
        <div class="help-text">
          <div class="tooltip">
            <img src="" width="18px"> More information
            <span class="tooltiptext"> Tooltip text </span>
          </div>
        </div>
        <div class="choices-radio">
          <label class="radio-style">Choice 1
                                <input type="radio" value="choice1" name="choice1"><br>
                                <span class="checkmark"></span>
                            </label>

          <label class="radio-style">Choice 2
                                <input type="radio" value="choice1" name="choice1"><br>
                                <span class="checkmark"></span>
                            </label>

          <label class="radio-style">Choice 3
                                <input type="radio" value="choice1" name="choice1"><br>
                                <span class="checkmark"></span>
                            </label>

          <label class="radio-style">Choice 4
                                <input type="radio" value="choice1" name="choice1"><br>
                                <span class="checkmark"></span>
                            </label>

          <label class="radio-style">Choice 5
                                <input type="radio" value="choice1" name="choice1"><br>
                                <span class="checkmark"></span>
                            </label>

          <label class="radio-style">Choice 6
                                <input type="radio" value="choice1" name="choice1"><br>
                                <span class="checkmark"></span>
                            </label>

          <label class="radio-style">Choice 7
                                <input type="radio" value="choice1" name="choice1"><br>
                                <span class="checkmark"></span>
                            </label>

          <label class="radio-style">Choice 8
                                <input type="radio" value="choice1" name="choice1"><br>
                                <span class="checkmark"></span>
                            </label>

          <label class="radio-style">Choice 9
                                <input type="radio" value="choice1" name="choice1"><br>
                                <span class="checkmark"></span>
                            </label>

          <label class="radio-style">Choice 10
                                <input type="radio" value="choice1" name="choice1"><br>
                                <span class="checkmark"></span>
                            </label>
        </div>
      </div>
    </div>
  </div>
</body>

</html></code>```

答:
Not overly sure about how to do this with pure css, however with jquery and css you could set the sections class to height:100% and change the height of the container to the same height of the choices class, something like this:

First, add the height attribute to the .sections element as 100%, this will fill out the container.

```<code>.sections {
    color: gainsboro;
    text-align: left;
    font-size: 13px;
    background-color: white;
    text-decoration: none;
    width: 20%;
    overflow: scroll;
    height:100%;
}
</code>```

Then with some jquery, you can change the height of its parent to be the same height as the .choices element:

```<code>$( document ).ready(function() {

var height = $(".choices").height();

console.log(height);

$(".sections-choices").css("height",height);

});
</code>```

Body:
I want the menu on the left to grow according to the content in the right, instead of setting the height of all the sections available.

In this case I would want the menu on the left to finish below the Choice 10 of the content in the right and then the menu would have a scroll (which I have already added in CSS).

Thanks in advance ! :)

@import url('https://fonts.googleapis.com/css?family=Roboto:400,400i');
* {
  font-family: Roboto, sans-serif !important;
}

@media screen and (max-width: 1300px) {
  .wrapper,
  .disclaimer {
    width: 90vw !important;
  }
}

ol {
  text-align: left;
}

.answered {
  font-weight: 900;
}

.answered::after {
  content: '•';
  color: black;
  margin-left: 10px;
  font-size: 15px;
}

.sections-choices {
  display: flex;
  align-items: flex-start;
  border: 1px solid #ddeafa;
  margin: 0 25px 15px 25px;
  width: 95%;
  margin-bottom: 15px;
  background-color: white;
  /* height: 300px;
                min-height: 300px;
                max-height: 350px; */
}

.sections {
  color: gainsboro;
  text-align: left;
  font-size: 13px;
  background-color: white;
  text-decoration: none;
  width: 20%;
  height: inherit;
  overflow-y: scroll;
}

.sections .question-select {
  margin-left: 10px;
}

.sections h4 {
  padding: 5px 0 5px 15px;
  background-color: #3a3838;
  color: white;
  margin-top: 0;
}

.sections .intro-text {
  padding-top: 2.5px;
  padding-bottom: 2.5px;
}

.sections a {
  text-decoration: none;
  color: black;
  padding-left: 15px;
}

.choices {
  color: black;
  font-size: 14px;
  text-align: left;
  width: 80%;
  padding-bottom: 15px;
  height: inherit;
}

.choices-section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: auto;
  background-color: #3a3838;
}

.choices-section-title h4 {
  margin: 0;
  padding: 15px 15px;
  color: white;
}

.choices-title {
  padding: 10px 15px 0 15px;
  line-height: 19px;
}

.help-text {
  padding: 5px 15px 0 15px;
  text-align: right;
  font-size: 11px;
}

.help-text p {
  margin: 0;
}

.choices-radio {
  padding: 15px 15px 0 25px;
}

.choices-radio label {
  /* word-wrap: break-word; */
  white-space: normal;
}

.choices-radio input {
  margin-bottom: 10px;
}

/* TOOLTIP */

.tooltip {
  position: relative;
  font-size: 12px;
  display: inline-flex;
  justify-content: flex-end;
  align-items: center;
  flex-direction: row;
  color: black;
}

.tooltip img {
  margin-right: 5px;
}

.tooltip .tooltiptext {
  visibility: hidden;
  width: 300px;
  background-color: #f7f7f7;
  color: black;
  text-align: left;
  border-radius: 6px;
  padding: 10px;
  /* Position the tooltip */
  position: absolute;
  z-index: 1;
  top: -5px;
  right: 105%;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
}

/* CHANGE RADIO BUTTONS ASPECT */

/* The container */

.radio-style {
  display: block;
  position: relative;
  padding-left: 25px;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 13px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* Hide the browser's default radio button */

.radio-style input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

/* Create a custom radio button */

.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 18px;
  width: 18px;
  background-color: gainsboro;
  border-radius: 50%;
}

/* On mouse-over, add a grey background color */

.radio-style:hover input~.checkmark {
  background-color: #ccc;
}

/* When the radio button is checked, add a blue background */

.radio-style input:checked~.checkmark {
  background-color: black;
}

/* Create the indicator (the dot/circle - hidden when not checked) */

.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

/* Show the indicator (dot/circle) when checked */

.radio-style input:checked~.checkmark:after {
  display: block;
}

/* Style the indicator (dot/circle) */

.radio-style .checkmark:after {
  top: 6px;
  left: 6px;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: white;
}

/* SCROLLBAR */

/* width */

 ::-webkit-scrollbar {
  width: 8px;
}

/* Track */

 ::-webkit-scrollbar-track {
  background: #f1f1f1;
}

/* Handle */

 ::-webkit-scrollbar-thumb {
  background: #888;
}

/* Handle on hover */

 ::-webkit-scrollbar-thumb:hover {
  background: #555;
}

<!DOCTYPE html>

1. Section 1

Question 1

Question 2

Question 3

Question 4

2. Section 2

Question 1

Question 2

3. Section 3

Question 1

Question 2

Question 3

4. Section 4

Question 1

5. Section 5

Question 1

Question 2

Question 3

6. Section 6

Question 1

Question 2

Question 3

Question 4

Question 5

Section 1 out of 6

Question 1 out of 4

1. This is Question 1 ?

             More information
             Tooltip text

          Choice 1
                                <input type="radio" value="choice1" name="choice1">

          Choice 2
                                <input type="radio" value="choice1" name="choice1">

          Choice 3
                                <input type="radio" value="choice1" name="choice1">

          Choice 4
                                <input type="radio" value="choice1" name="choice1">

          Choice 5
                                <input type="radio" value="choice1" name="choice1">

          Choice 6
                                <input type="radio" value="choice1" name="choice1">

          Choice 7
                                <input type="radio" value="choice1" name="choice1">

          Choice 8
                                <input type="radio" value="choice1" name="choice1">

          Choice 9
                                <input type="radio" value="choice1" name="choice1">

          Choice 10
                                <input type="radio" value="choice1" name="choice1">

Body:
Not overly sure about how to do this with pure css, however with jquery and css you could set the sections class to height:100% and change the height of the container to the same height of the choices class, something like this:

First, add the height attribute to the .sections element as 100%, this will fill out the container.

.sections {
    color: gainsboro;
    text-align: left;
    font-size: 13px;
    background-color: white;
    text-decoration: none;
    width: 20%;
    overflow: scroll;
    height:100%;
}

Then with some jquery, you can change the height of its parent to be the same height as the .choices element:

$( document ).ready(function() {

var height = $(".choices").height();

console.log(height);

$(".sections-choices").css("height",height);

});


问:
Sort java.util.Deque
I want to sort the contents of my Deque<Card> collection using the Card class' getRealValue() method.

```<code>public class Card implements Comparable<Card> {
  private final int value;
  private final CardType cardType;

  public Card(int value, CardType cardType) {
    this.value = value;
    this.cardType = cardType;
  }

  public int getRealValue() {
    int realValue = this.value == 1 ? 52 : 0;
    return realValue + this.value * 4 + this.cardType.ordinal();
  }

  public int compareTo(Card o) {
    return this.getRealValue() - o.getRealValue();
  }
}
</code>```

Here is my CardType enum

```<code>public enum CardType {
    CLUB("♣"),
    SPADE("♠"),
    HEART("♥"),
    DIAMOND("♦");

    public final String icon;

    private CardType(String icon) {
        this.icon = icon;
    }
}
</code>```

and I want to sort my Deque based on the realValue()

答:
Well you can always clear it and re-insert the elements in the right order:

```<code>Card[] a = deque.toArray(new Card[0]);
Arrays.sort(a);
deque.clear();
for (Card card : a) {
    deque.add(card);
}
</code>```

Bear in mind the performance of this. If sorting is a requirement of your structure, consider using a PriorityQueue.

Title: Sort java.util.Deque

Body:
I want to sort the contents of my Deque<Card> collection using the Card class' getRealValue() method.

public class Card implements Comparable<Card> {
  private final int value;
  private final CardType cardType;

  public Card(int value, CardType cardType) {
    this.value = value;
    this.cardType = cardType;
  }

  public int getRealValue() {
    int realValue = this.value == 1 ? 52 : 0;
    return realValue + this.value * 4 + this.cardType.ordinal();
  }

  public int compareTo(Card o) {
    return this.getRealValue() - o.getRealValue();
  }
}

Here is my CardType enum

public enum CardType {
    CLUB("♣"),
    SPADE("♠"),
    HEART("♥"),
    DIAMOND("♦");

    public final String icon;

    private CardType(String icon) {
        this.icon = icon;
    }
}

and I want to sort my Deque based on the realValue()

Body:
Well you can always clear it and re-insert the elements in the right order:

Card[] a = deque.toArray(new Card[0]);
Arrays.sort(a);
deque.clear();
for (Card card : a) {
    deque.add(card);
}

Bear in mind the performance of this. If sorting is a requirement of your structure, consider using a PriorityQueue.


问:
Get PDF out of arraybuffer in React Native
The websocket on my server sends my react-native app an arraybuffer of a PDF and from there I'm trying to figure out how to display the PDF. I feel like rn-fetch-blob would be the answer but I'm not sure what goes where. On the browser, I just did this:

```<code>const pdfBlob = new Blob([e.data], {type: "application/pdf"})
const url = URL.createObjectURL(pdfBlob);
pdfViewer.setAttribute("src", url)
</code>```

But React Native doesn't support making Blobs like that. My next attempt was doing something like this:

```<code>fetch(e.data, {
  responseType: "arraybuffer"
})
  .then(res => res.arrayBuffer())
  .then(res => res.blob())
  .then(pdfBlob => {
    const url = URL.createObjectURL(pdfBlob);
    /** ... */
  })
  .catch(e => console.error(e));
</code>```

But that didn't work either. I know this guy got it working for images when his response from the server was a blob, but I don't know if it's the same thing.

I'm still super shakey on arraybuffers, blobs, fetching, etc. so any help is much appreciated.

答:
Mmm this was a while ago so I'm not super sure about my own code or if it's already out of date. I remember reading something about RNFetchBlob being unnecessary with newer versions of React but here's how I did it:

```<code>import RNFetchBlob from "rn-fetch-blob";
const { fs } = RNFetchBlob;

connection.onmessage = e => {
  if (typeof e.data === "string") {
    /* not array buffer */
  } else if (e.data.constructor === ArrayBuffer) {
    const base64 = binaryToBase64(e.data);
    const filePath = `${fs.dirs.CacheDir}/${shortid.generate()}.pdf`;

    RNFetchBlob.fs.createFile(filePath, base64, "base64").then(path => {
      // necessary ?
      RNFetchBlob.session("all").add(path);
    });
  }
};
</code>```

I think I added the path to the session so I could delete the pdfs in bulk later on by their session id. Otherwise, I think with that path you can just pass that into the PDF component like this:

```<code><Pdf source={{ uri: path, cache: false }} />
</code>```

Body:
The websocket on my server sends my react-native app an arraybuffer of a PDF and from there I'm trying to figure out how to display the PDF. I feel like rn-fetch-blob would be the answer but I'm not sure what goes where. On the browser, I just did this:

const pdfBlob = new Blob([e.data], {type: "application/pdf"})
const url = URL.createObjectURL(pdfBlob);
pdfViewer.setAttribute("src", url)

But React Native doesn't support making Blobs like that. My next attempt was doing something like this:

fetch(e.data, {
  responseType: "arraybuffer"
})
  .then(res => res.arrayBuffer())
  .then(res => res.blob())
  .then(pdfBlob => {
    const url = URL.createObjectURL(pdfBlob);
    /** ... */
  })
  .catch(e => console.error(e));

But that didn't work either. I know this guy got it working for images when his response from the server was a blob, but I don't know if it's the same thing.

I'm still super shakey on arraybuffers, blobs, fetching, etc. so any help is much appreciated.

Body:
Mmm this was a while ago so I'm not super sure about my own code or if it's already out of date. I remember reading something about RNFetchBlob being unnecessary with newer versions of React but here's how I did it:

import RNFetchBlob from "rn-fetch-blob";
const { fs } = RNFetchBlob;

connection.onmessage = e => {
  if (typeof e.data === "string") {
    /* not array buffer */
  } else if (e.data.constructor === ArrayBuffer) {
    const base64 = binaryToBase64(e.data);
    const filePath = `${fs.dirs.CacheDir}/${shortid.generate()}.pdf`;

    RNFetchBlob.fs.createFile(filePath, base64, "base64").then(path => {
      // necessary ?
      RNFetchBlob.session("all").add(path);
    });
  }
};

I think I added the path to the session so I could delete the pdfs in bulk later on by their session id. Otherwise, I think with that path you can just pass that into the PDF component like this:

<Pdf source={{ uri: path, cache: false }} />


问:
Watson Discovery -- Import a Model with a Object Storage connection
I have a SDU Model created and I need import this model in other collection. The documentation explain that is necessary add 1 document and then import the model.

https://cloud.ibm.com/docs/services/discovery?topic=discovery-sdu#import

The problem is that my collection is connected with the object storage service with more than 1000 documents and not is possible add only one document and then import the model

I imported the model but SDU doesn't recognize my model. Is possible import a model with this type of connection?

Thanks.

答: After doing the initial crawl of Object Storage you should get the option to import the model.  If you are getting an error importing please post it here for further debugging.  (I am an IBM Watson employee)</p>


问:
AMP Webpush Error: 'X-Frame-Options' to 'deny'
So I'm trying to implement webpush notifications for an AMP page, following the official documentation:

https://amp.dev/documentation/components/amp-web-push

But there is an issue when adding the <amp-web-push> component and specifying the helper-iframe-url that points to the amp-web-push-helper-frame.html, the one I've downloaded from the official page.

When I open my AMP page in browser, there are an error in the console:

Refused to display
  'https://mytestsite.com/test/amp/amp-web-push-helper-frame.html?parentOrigin=https://mytestsite.com'
  in a frame because it set 'X-Frame-Options' to 'deny'.

And regarding that, I cant interact with the service worker. I took a look at the official AMP demo and there's no X-Frame-Options header with  deny value.

This is my HTML templates:

AMP component:

```<code><amp-web-push
        id="amp-web-push"
        layout="nodisplay"
        helper-iframe-url="https://mytestsite.com/test/amp/amp-web-push-helper-frame.html"
        permission-dialog-url="https://mytestsite.com/test/amp/amp-web-push-permission-dialog.html"
        service-worker-url="https://mytestsite.com/test/amp/service-worker.js">
</amp-web-push>
</code>```

AMP widget

```<code>    <amp-web-push-widget visibility="unsubscribed" layout="fixed" width="245" height="45">
        <!-- Custom banner goes here... -->
    </amp-web-push-widget>
</code>```

So I spent the whole day searching for solution and refactoring but still with the problem.

答:
The X-Frame-Options header is defined by your backend server software or reverse proxy (nginx, apache, envoy, etc).

You have to change it to X-Frame-Options: sameorigin.

Body:
So I'm trying to implement webpush notifications for an AMP page, following the official documentation:

https://amp.dev/documentation/components/amp-web-push

But there is an issue when adding the <amp-web-push> component and specifying the helper-iframe-url that points to the amp-web-push-helper-frame.html, the one I've downloaded from the official page.

When I open my AMP page in browser, there are an error in the console:

Refused to display
  'https://mytestsite.com/test/amp/amp-web-push-helper-frame.html?parentOrigin=https://mytestsite.com'
  in a frame because it set 'X-Frame-Options' to 'deny'.

And regarding that, I cant interact with the service worker. I took a look at the official AMP demo and there's no X-Frame-Options header with  deny value.

This is my HTML templates:

AMP component:

<amp-web-push
        id="amp-web-push"
        layout="nodisplay"
        helper-iframe-url="https://mytestsite.com/test/amp/amp-web-push-helper-frame.html"
        permission-dialog-url="https://mytestsite.com/test/amp/amp-web-push-permission-dialog.html"
        service-worker-url="https://mytestsite.com/test/amp/service-worker.js">
</amp-web-push>

AMP widget

    <amp-web-push-widget visibility="unsubscribed" layout="fixed" width="245" height="45">

    </amp-web-push-widget>

So I spent the whole day searching for solution and refactoring but still with the problem.


问:
How should I think about implement the closing of an open equity position in my portfolio app?
I have a model PortStock that has a schema that looks like this:

```<code># == Schema Information
#
# Table name: port_stocks
#
#  id                :bigint(8)        not null, primary key
#  portfolio_id      :integer
#  stock_id          :integer
#  volume            :integer
#  transaction_price :float
#  current_price     :float
#  percent_change    :float
#  created_at        :datetime         not null
#  updated_at        :datetime         not null
#  current_value     :float
#  dollar_change     :float
#  total_spend       :float
#  transaction_date  :datetime
#  action            :integer
#  position          :integer          default("open")
#  ticker            :string
#  slug              :string
#
</code>```

When someone buys a stock, the app creates a port_stock that has position: "open", action: :buy in their portfolio.

When they sell that position, essentially what happens is they create another port_stock but it just has position: "closed", action: :sell.

I have a few questions:

Is that really the most optimal structure? One immediate issue I see with this is that I have to close the buy position. So in essence, the full completed position would be two closed  buy and sell port_stock records. If there is only one, then the position is considered open. But does that make sense?

Should I create a method in my model to both close and open positions? I originally did this just in my controllers, but now that I am writing unit tests I don't have a clean way to close an existing open position.

Should I be approaching the buying & selling of port_stock differently?

Thoughts?

答:
I think that you need to keep each transactions.

If you bought 100 shares of Acme, and want to sell 20 shares later; you have to keep the both transactions in your portfolio.

To find out how many actions you have, you have to sum the transactions for each action.
Maybe it's repetitive but it's the best option for follow the value of a portfolio.

For example, if you want compute your P&L you have to sum (price*volume*spot_change) for each transaction, if action = sell you multiply by -1 else you multiply by 1.

What is the final goal of your code ? Tell me if I can help you more.

Body:
I have a model PortStock that has a schema that looks like this:

# == Schema Information
#
# Table name: port_stocks
#
#  id                :bigint(8)        not null, primary key
#  portfolio_id      :integer
#  stock_id          :integer
#  volume            :integer
#  transaction_price :float
#  current_price     :float
#  percent_change    :float
#  created_at        :datetime         not null
#  updated_at        :datetime         not null
#  current_value     :float
#  dollar_change     :float
#  total_spend       :float
#  transaction_date  :datetime
#  action            :integer
#  position          :integer          default("open")
#  ticker            :string
#  slug              :string
#

When someone buys a stock, the app creates a port_stock that has position: "open", action: :buy in their portfolio.

When they sell that position, essentially what happens is they create another port_stock but it just has position: "closed", action: :sell.

I have a few questions:

Is that really the most optimal structure? One immediate issue I see with this is that I have to close the buy position. So in essence, the full completed position would be two closed  buy and sell port_stock records. If there is only one, then the position is considered open. But does that make sense?

Should I create a method in my model to both close and open positions? I originally did this just in my controllers, but now that I am writing unit tests I don't have a clean way to close an existing open position.

Should I be approaching the buying & selling of port_stock differently?

Thoughts?


问:
Why does logging.Logger reset its state in new process on Windows?
I'm running into strange problem with python logging module on windows.
The code below shows it:

import multiprocessing
import logging
import sys

class ProcessLogger(multiprocessing.Process):
    def __init__(self):
        super().__init__()
        self.create_logger()
        print('state of logger in main proccess:')
        print(self.logger)
        print(self.logger.handlers)

    def run(self):
        print('state of logger in child proccess:')
        print(self.logger)
        print(self.logger.handlers)

    def create_logger(self):
        self.logger = logging.getLogger('something')
        self.logger.setLevel(logging.DEBUG)
        handler = logging.StreamHandler()
        self.logger.addHandler(handler)

if __name__ == '__main__':
    logg = ProcessLogger()
    logg.start()
    logg.join()
    print(sys.version)
```

<p>it prints following output on Windows:</p>

```state of logger in main proccess:
<Logger something (DEBUG)>
[<StreamHandler <stderr> (NOTSET)>]
state of logger in child proccess:
<Logger something (WARNING)>
[]
3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)]
```

<p>for some reason logger object in new process has default state.</p>

<p>I tried this on ubuntu, and it seems to work as expected:</p>

```state of logger in main proccess:
<Logger something (DEBUG)>
[<StreamHandler <stderr> (NOTSET)>]
state of logger in child proccess:
<Logger something (DEBUG)>
[<StreamHandler <stderr> (NOTSET)>]
3.7.1 (default, Oct 22 2018, 11:21:55)
[GCC 8.2.0]
```

Is this expected behaviour on windows?
Can someone explain this?

答:
The reason you observe the above behaviour on the two Operating Systems is due to the difference between the fork (Unix) and the spawn (Windows) process starting strategies.

With the fork strategy, a child process is created as an exact clone of the parent process. The two processes will be identical at first and the child will share all the properties (opened files, configuration choices etc..) of the parent.

With the spawn strategy instead, a new blank process is started. The process is given the Python module to load and pointer to the first instruction to execute in the run method. All the operations performed by the parent beforehand are not inherited.

Body:
I'm running into strange problem with python logging module on windows.
The code below shows it:

import multiprocessing
import logging
import sys

class ProcessLogger(multiprocessing.Process):
    def __init__(self):
        super().__init__()
        self.create_logger()
        print('state of logger in main proccess:')
        print(self.logger)
        print(self.logger.handlers)

    def run(self):
        print('state of logger in child proccess:')
        print(self.logger)
        print(self.logger.handlers)

    def create_logger(self):
        self.logger = logging.getLogger('something')
        self.logger.setLevel(logging.DEBUG)
        handler = logging.StreamHandler()
        self.logger.addHandler(handler)

if __name__ == '__main__':
    logg = ProcessLogger()
    logg.start()
    logg.join()
    print(sys.version)

it prints following output on Windows:

state of logger in main proccess:
<Logger something (DEBUG)>
[<StreamHandler <stderr> (NOTSET)>]
state of logger in child proccess:
<Logger something (WARNING)>
[]
3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)]

for some reason logger object in new process has default state.

I tried this on ubuntu, and it seems to work as expected:

state of logger in main proccess:
<Logger something (DEBUG)>
[<StreamHandler <stderr> (NOTSET)>]
state of logger in child proccess:
<Logger something (DEBUG)>
[<StreamHandler <stderr> (NOTSET)>]
3.7.1 (default, Oct 22 2018, 11:21:55)
[GCC 8.2.0]

Is this expected behaviour on windows?
Can someone explain this?


答: use latest 0.19.6 to re-pull all blocks from genesis works for me</p>

Title: Bitcoin-abc node seems not connect to bch testnet

Body:
I tried latest version(v.0.19.6) and v0.18.5, but both seems have different views from what is shown on bitcoin.com testnet explorer and latest height from bitcoin-abc always around 100 blocks ahead of what is shown on bitcoin.com explorer

for example, below is what I get using rpc call from bitcoin-abc for block at height 1306255:

{
    "bits": "1b3037a6",
    "chainwork": "00000000000000000000000000000000000000000000004c90a4d396ee6583d7",
    "confirmations": 57,
    "difficulty": 1359,
    "hash": "00000000002b9e83a7f55211bdb847b58ad7f37fae879478f9e32f8e75e6c9b4",
    "height": 1306255,
    "mediantime": 1559185963,
    "merkleroot": "088f104ca41a7ca4f83d6de267a85724dc0283aefc27d7ae978badcd571d40c0",
    "nextblockhash": "0000000000066ba2e8a751149138dc3a1be8168ea85fab1bc398ff3fbb9307e2",
    "nonce": 1464894606,
    "previousblockhash": "000000000020127e583624c682c96efb50cd56fc189928de917faba96a9c3d40",
    "size": 201,
    "time": 1559188014,
    "tx": [{
        "blockhash": "00000000002b9e83a7f55211bdb847b58ad7f37fae879478f9e32f8e75e6c9b4",
        "blocktime": 1559188014,
        "confirmations": 57,
        "hash": "088f104ca41a7ca4f83d6de267a85724dc0283aefc27d7ae978badcd571d40c0",
        "hex": "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff23038fee1300fefc980800fefb2308000963676d696e6572343208040000000000000000ffffffff01c817a804000000001976a9146db2250c113ad124a60e0a522faef0b7f0c8b0ed88ac00000000",
        "locktime": 0,
        "size": 120,
        "time": 1559188014,
        "txid": "088f104ca41a7ca4f83d6de267a85724dc0283aefc27d7ae978badcd571d40c0",
        "version": 1,
        "vin": [{
            "sequence": 4294967295
        }],
        "vout": [{
            "addressValid": true,
            "n": 0,
            "scriptPubKey": {
                "addresses": ["bchtest:qpkmyfgvzyadzf9xpc99ytaw7zmlpj9sa5qrn24u9t"],
                "asm": "OP_DUP OP_HASH160 6db2250c113ad124a60e0a522faef0b7f0c8b0ed OP_EQUALVERIFY OP_CHECKSIG",
                "hex": "76a9146db2250c113ad124a60e0a522faef0b7f0c8b0ed88ac",
                "reqSigs": 1,
                "type": "pubkeyhash"
            },
            "value": 0.78125
        }]
    }],
    "version": 536870912,
    "versionHex": "20000000"
}

while the bitcoin.com shows following for same height of 1306255 (even the block hash is different):
https://explorer.bitcoin.com/tbch/block/0000000000000340762ba9648a982a18442ff7423e787d4115da323a399dc57b

I am not sure what cause the problem, below is my conf:

server=1
daemon=1
txindex=1
logtimestamps=1

rpcuser=xxx
rpcpassword=xxxx
rpcport=18332
rpcallowip=0.0.0.0/0

datacarriersize=80

regtest=0
testnet=1

and I start bitcoin-abc node using following cmd:

bin/bitcoind -conf=/data/xxx-bch-test/bitcoin.conf -datadir=/data/xxx-bch-test/testnet -testnet &

and I noticed there is a log in debug.log not sure if it is related:

2019-05-30T11:33:56Z ERROR: AcceptBlockHeader: block 000000000000003a3fb0ca1611035346a803e0344d6bb2eb4f5ea75f4dc2291c is marked invalid
2019-05-30T11:33:56Z ERROR: invalid header received

but the hash looks good in bitcoin.com explorer


问:
Why does returning a string slice instead of a usize prevent mutating a String?
This code compiles:

```<code>fn main() {
    let mut s = String::from("some_string");
    let n = f1(&s);
    s.clear();
    println!("n = {}", n);
}

fn f1(s: &String) -> usize {
    10
}

fn f2(s: &String) -> &str {
    "def"
}
</code>```

However, replacing the call to f1() by f2() causes a compilation failure. It appears to me that both f1() and f2() do an immutable borrow, and s.clear() does a mutable borrow, so I should get compilation error in both cases. What am I missing?

答:
Here is the minimum code necessary to reproduce the issue:

```<code>fn f1(s: &String) -> usize { unimplemented!() }

fn f2(s: &String) -> &str { unimplemented!() }

fn main() {
    let mut s = String::from("some_string");
    let n = f1(&s);
    s.clear();
    println!("n = {}", n);
}
</code>```

Lifetime analysis is performed based on function signatures.

You will note in the above code that I have used unimplemented!() as the body of the functions, and the problem is exactly the same. This is normal.

In the vast majority of cases1, a function signature fully specifies the interface of a function, and it is unnecessary to look at its implementation.

As a corollary, this also means that whether the lifetime in a return type is linked to the lifetime in any of the arguments is fully specified within the signature, and in this case the full signature of f2 is therefore:

```<code>fn f2<'a>(s: &'a String) -> &'a str;
</code>```

Whether the implementation of f2 is "def" (with the 'static lifetime) or &*s (with the 'a lifetime) does not matter; only the signature matters, and the signature uses the same lifetime due to the elision rules.

1 The one exception I know of concerns the -> impl Trait feature and whether the resulting object implements Send or Sync.

In the case of f1, the return type is not linked to the argument, therefore the borrow of the argument ends at the end of the call to f1:

```<code>fn main() {
    let mut s = String::from("some_string");
    let n = {
        //  Immutable borrow of s starts here.
        f1(&s)
        //  Immutable borrow of s ends here.
    };
    s.clear();
    println!("n = {}", n);
}
</code>```

In the case of f2, the return type has the same lifetime as the argument, and therefore is considered to extend the borrow. In Rust 2015, the borrow would extend until the return value went out of scope (lexical borrow); with Rust 2018, the borrow extends until the last use of the return value (non-lexical borrow).

In your case, both are basically identical:

```<code>fn main() {
    let mut s = String::from("some_string");
    let n = {
        //  Immutable borrow of s starts here.
        f2(&s)
    };
    s.clear();  //  Conflicting attempt to mutably borrow s.
    println!("n = {}", n);
    //  Immutable borrow of s ends here.
}
</code>```

You could observe the difference by switching the order of s.clear() and println!.

Body:
This code compiles:

fn main() {
    let mut s = String::from("some_string");
    let n = f1(&s);
    s.clear();
    println!("n = {}", n);
}

fn f1(s: &String) -> usize {
    10
}

fn f2(s: &String) -> &str {
    "def"
}

However, replacing the call to f1() by f2() causes a compilation failure. It appears to me that both f1() and f2() do an immutable borrow, and s.clear() does a mutable borrow, so I should get compilation error in both cases. What am I missing?

Body:
Here is the minimum code necessary to reproduce the issue:

fn f1(s: &String) -> usize { unimplemented!() }

fn f2(s: &String) -> &str { unimplemented!() }

fn main() {
    let mut s = String::from("some_string");
    let n = f1(&s);
    s.clear();
    println!("n = {}", n);
}

Lifetime analysis is performed based on function signatures.

You will note in the above code that I have used unimplemented!() as the body of the functions, and the problem is exactly the same. This is normal.

In the vast majority of cases1, a function signature fully specifies the interface of a function, and it is unnecessary to look at its implementation.

As a corollary, this also means that whether the lifetime in a return type is linked to the lifetime in any of the arguments is fully specified within the signature, and in this case the full signature of f2 is therefore:

fn f2<'a>(s: &'a String) -> &'a str;

Whether the implementation of f2 is "def" (with the 'static lifetime) or &*s (with the 'a lifetime) does not matter; only the signature matters, and the signature uses the same lifetime due to the elision rules.

1 The one exception I know of concerns the -> impl Trait feature and whether the resulting object implements Send or Sync.

In the case of f1, the return type is not linked to the argument, therefore the borrow of the argument ends at the end of the call to f1:

fn main() {
    let mut s = String::from("some_string");
    let n = {
        //  Immutable borrow of s starts here.
        f1(&s)
        //  Immutable borrow of s ends here.
    };
    s.clear();
    println!("n = {}", n);
}

In the case of f2, the return type has the same lifetime as the argument, and therefore is considered to extend the borrow. In Rust 2015, the borrow would extend until the return value went out of scope (lexical borrow); with Rust 2018, the borrow extends until the last use of the return value (non-lexical borrow).

In your case, both are basically identical:

fn main() {
    let mut s = String::from("some_string");
    let n = {
        //  Immutable borrow of s starts here.
        f2(&s)
    };
    s.clear();  //  Conflicting attempt to mutably borrow s.
    println!("n = {}", n);
    //  Immutable borrow of s ends here.
}

You could observe the difference by switching the order of s.clear() and println!.


问:
How to use like query in mysql using nodejs
I have been trying to use like query on MySQL but it won't match the pattern with database and only works when the exact keyword is given(% sign doesn't work)

I have tried Concat method, using backslash for special characters,+ symbol and every other approach I can find but still, it isn't working

```<code>connection.query('SELECT * FROM job where domainname like ?', '%' + request.body.domain + '%' ,function(error, results){
            response.render('./results',{rows:results});

    });
and on front end part
  <tbody>
    <% for(var i=0; i < rows.length; i++) { %>
   <tr>
     <td><%= i %></td>
     <td><%= rows[i].companyname %></td>
     <td><%= rows[i].domainname %></td>
   </tr>
<% } %>
</code>```

Error: Cannot read property 'length' of undefined
it works if I don't use % and don't try pattern matching and then shows the results.

答:
Pushkar, welcome to StackOverflow. I might be able to shed a little light on your query. In my experience the 'LIKE' operator in MySQL works as follows:

% at the beginning means ignore character before the match. 'qweradsfzxcv

% at the end means ignore characters after the match. 'qwerasdfzxcv'

%% means the match can be in the middle of a string. 'qwerasdfzxcv'

The length error is due to 'rows' having no value. A good defensive programming habit is to never trust that data from a 3rd part is populated. Just like we never trust user input, never trust 3rd party data. In this case, wrap the SQL select with a check. If 'rows' has no values, do not try to render the the tbody.

Back to the SQL query; try hard coding all the values as string literals. See if the query as formulated return any values. Then pull it apart into the parameterized version.

Body:
I have been trying to use like query on MySQL but it won't match the pattern with database and only works when the exact keyword is given(% sign doesn't work)

I have tried Concat method, using backslash for special characters,+ symbol and every other approach I can find but still, it isn't working

connection.query('SELECT * FROM job where domainname like ?', '%' + request.body.domain + '%' ,function(error, results){
            response.render('./results',{rows:results});

    });
and on front end part

    <% for(var i=0; i < rows.length; i++) { %>

     <%= i %>
     <%= rows[i].companyname %>
     <%= rows[i].domainname %>

<% } %>

Error: Cannot read property 'length' of undefined
it works if I don't use % and don't try pattern matching and then shows the results.


问:
How to run cucumber selenium using Thin server instead of default Webrick?
my cucumber features with selenium  runs (for Rails 3 app) using the default Webrick server.

How can I force or setup to run with Thin server instead of Webrick?
Any settings to put in env.rb file or else?

答:
Two ways:

1) turn off capybara's built in server and run it yourself.

2) Looks like someone patched in the capability here https://github.com/jnicklas/capybara/pull/175

ContentLicense: CC BY-SA 2.5


问:
Custom form fields in cart and get the data in checkout on Woocommerce
Adding From,To and Message fields in cart page before checkout.I have added some code in cart.php file but after adding that code the cart page is displaying blank.

```<code>/**
* Add the order_comments field to the cart
**/
 add_action('woocommerce_cart_collaterals',
'order_comments_custom_cart_field');

 function order_comments_custom_cart_field() {
  echo '<div id="cart_order_notes">';
  ?>
 <div class="customer_notes_on_cart">
 <label for="customer_notes_text"><?php _e('Order notes','woocommerce'); ?>
 </label>
 <textarea id="customer_notes_text"></textarea>
 </div>
 <?php
  }
  /**
  * Process the checkout and overwriting the normal button
  *
  */
function woocommerce_button_proceed_to_checkout() {
$checkout_url = wc_get_checkout_url();
?>
   <form id="checkout_form" method="POST" action="<?php echo $checkout_url;
  ?>">
   <input type="hidden" name="customer_notes" id="customer_notes" value="">
   <a  href="#" onclick="document.getElementById('customer_notes').value=document.getElementById('customer_notes_text').value;document.getElementById('checkout_form').submit()" class="checkout-button button alt wc-forward">
   <?php _e( 'Proceed to checkout', 'woocommerce' ); ?></a>
   </form>
   <?php
   }
  // getting the values in checkout again
 add_action('woocommerce_checkout_before_customer_details',function(){
 ?>
 <script>
 jQuery( document ).ready(function() {
jQuery('#order_comments' ).val("<?php echo
 sanitize_text_field($_POST['customer_notes']); ?>");
  });
 </script>
<?php
 });
</code>```

In cart.php i have added this code at the bottom before closing the form tag as well as after the form tag.But i am getting a blank page after adding this piece of code in cart.php.

In the same format i am trying to get those from,to and message fields.

答:
I think is better no change "proceed to checkout" form, is better to store vars in localstorage when data in field changed, and get it after, when user is in checkout form.

```<code>function order_comments_custom_cart_field() {
      echo '<div id="cart_order_notes">';
      ?>
     <div class="customer_notes_on_cart">
     <label for="customer_notes_text"><?php _e('Order notes','woocommerce'); ?>
     </label>
     <textarea id="customer_notes_text"></textarea>
     </div>
    <script>
       jQuery(document).ready(function (jQuery) {
         jQuery("#customer_notes_text").on('change', function () {
           localStorage.setItem(jQuery(this).attr('id'), this.val());
         });
       });
    </script>
 <?php
  }
</code>```

Then you can get it with

LocalStore.getItem(item);

Don't forget to destroy element after obtain it, with

LocalStorage.removeItem(item);

Body:
Adding From,To and Message fields in cart page before checkout.I have added some code in cart.php file but after adding that code the cart page is displaying blank.

/**
* Add the order_comments field to the cart
**/
 add_action('woocommerce_cart_collaterals',
'order_comments_custom_cart_field');

 function order_comments_custom_cart_field() {
  echo '
';
  ?>

 <?php _e('Order notes','woocommerce'); ?>

 <textarea id="customer_notes_text"></textarea>

 <?php
  }
  /**
  * Process the checkout and overwriting the normal button
  *
  */
function woocommerce_button_proceed_to_checkout() {
$checkout_url = wc_get_checkout_url();
?>
   <form id="checkout_form" method="POST" action="<?php echo $checkout_url;
  ?>">
   <input type="hidden" name="customer_notes" id="customer_notes" value="">

   <?php _e( 'Proceed to checkout', 'woocommerce' ); ?>
   </form>
   <?php
   }
  // getting the values in checkout again
 add_action('woocommerce_checkout_before_customer_details',function(){
 ?>

<?php
 });

In cart.php i have added this code at the bottom before closing the form tag as well as after the form tag.But i am getting a blank page after adding this piece of code in cart.php.

In the same format i am trying to get those from,to and message fields.

Body:
I think is better no change "proceed to checkout" form, is better to store vars in localstorage when data in field changed, and get it after, when user is in checkout form.

function order_comments_custom_cart_field() {
      echo '<div id="cart_order_notes">';
      ?>
     <div class="customer_notes_on_cart">
     <label for="customer_notes_text"><?php _e('Order notes','woocommerce'); ?>
     </label>
     <textarea id="customer_notes_text"></textarea>
     </div>
    <script>
       jQuery(document).ready(function (jQuery) {
         jQuery("#customer_notes_text").on('change', function () {
           localStorage.setItem(jQuery(this).attr('id'), this.val());
         });
       });
    </script>
 <?php
  }

Then you can get it with

LocalStore.getItem(item);

Don't forget to destroy element after obtain it, with

LocalStorage.removeItem(item);


问:
Is there a way to restrict container access for user in Docker?
I'm using a Docker machine to host some process such as game servers with friends. I want to give access to CLI of some containers for some users (and only for that), so that they cannot interfer eachothers. I don't want those to be roots on this server.

A solution might be to create users, allow them to perform certains commands in adequation with their containers (such as sudo docker attach ) and let them do everything. I would like to know if there is another, better and proper way to do it so.

Do you have done any experimentation of this kind ?

Thanks.

答:
Why not creating a separate Docker container for each service?

So in other words, You create one container for each friend, and on each container you create a user which is a member in sudo (so your friend will be the root of his own container). Then install openssh-server, and give each of your friends the SSH access data (his username and password) to his container. This way they can do what ever they want, without affecting each other.

Of course do not forget to forward the SSH connection (and any other connections of the services you want) from the host to the container.