问:
Bootstrap in rails app works only with .scss
I am currently learning Rails and working on a simple SocialMedia/Blog app.
I am at a point where I have a basic view set up and am attempting to apply BootStrap CSS to it.

I followed the following steps in attempting to apply BootStrap to my application:

1.) added gem 'bootstrap-sass' into gemfile and ran 'bundle install'

2.) added '*=require bootstrap' to application.css

3.) added '//= require bootstrap' to application.js

4.)
added:

```<code><div class="container">
   <%= yield %>
 </div>
</code>```

However when I would open the app, I got an error stating

```<code>couldn't find file 'bootstrap' with type 'text/css'
</code>```

It would highlight the line "*=require bootstrap"

However, when I changed the extension to application.css.scss and added an @import statement as below, it worked with BootStrap applied

application.css.scss:

```<code>* This is a manifest file that'll be compiled into application.css,
which will include all the files
* listed below.
*
* Any CSS and SCSS file within this directory,
lib/assets/stylesheets, or any plugin's
* vendor/assets/stylesheets directory can be referenced here using a
relative path.
*
* You're free to add application-wide styles to this file and they'll
appear at the bottom of the
* compiled file so the styles you add here take precedence over
styles defined in any other CSS/SCSS
* files in this directory. Styles in this file should be added after
the last require_* statement.
* It is generally better to create a new file per style scope.
*
*= require_tree .
*= require bootstrap
*= require_self
*/
@import "bootstrap";
</code>```

So 2 questions...

1.) Why does my app require .scss and @import in order for BootStrap to work  ?

2.) why does my "=require bootstrap" need to be "=require_bootstrap"?

THANKS!!

答:
application.css.scss:

```<code>*= require bootstrap  #remove it
*= require_self
*= require_tree .
*/
</code>```

application.js

```<code>//= require bootstrap-sprockets
//= require jquery
</code>```

And most important is open a new scss file and add :

```<code>@import "bootstrap-sprockets";
@import "bootstrap";
</code>```

Body:
I am currently learning Rails and working on a simple SocialMedia/Blog app.
I am at a point where I have a basic view set up and am attempting to apply BootStrap CSS to it.

I followed the following steps in attempting to apply BootStrap to my application:

1.) added gem 'bootstrap-sass' into gemfile and ran 'bundle install'

2.) added '*=require bootstrap' to application.css

3.) added '//= require bootstrap' to application.js

4.)
added:

   <%= yield %>

However when I would open the app, I got an error stating

couldn't find file 'bootstrap' with type 'text/css'

It would highlight the line "*=require bootstrap"

However, when I changed the extension to application.css.scss and added an @import statement as below, it worked with BootStrap applied

application.css.scss:

* This is a manifest file that'll be compiled into application.css,
which will include all the files
* listed below.
*
* Any CSS and SCSS file within this directory,
lib/assets/stylesheets, or any plugin's
* vendor/assets/stylesheets directory can be referenced here using a
relative path.
*
* You're free to add application-wide styles to this file and they'll
appear at the bottom of the
* compiled file so the styles you add here take precedence over
styles defined in any other CSS/SCSS
* files in this directory. Styles in this file should be added after
the last require_* statement.
* It is generally better to create a new file per style scope.
*
*= require_tree .
*= require bootstrap
*= require_self
*/
@import "bootstrap";

So 2 questions...

1.) Why does my app require .scss and @import in order for BootStrap to work  ?

2.) why does my "=require bootstrap" need to be "=require_bootstrap"?

THANKS!!

Body:
application.css.scss:

*= require bootstrap  #remove it
*= require_self
*= require_tree .
*/

application.js

//= require bootstrap-sprockets
//= require jquery

And most important is open a new scss file and add :

@import "bootstrap-sprockets";
@import "bootstrap";


来源: stackexchange

问:
Singleton method vs. class method
Are class method and singleton method doing the same or different? Here is an example.</p>

```<code>class C
  def self.classmethod
    puts "class method #{self}"
  end
end

C.classmethod  # class method C
c = C.new

def c.singletonmethod
  puts "instance method #{self}"
end

c.singletonmethod  # instance method #<C:0x0000000118ed08>
</code>```

答:
Since all methods are implemented and stored by the class definition, it should be impossible for an object to define its own methods. However, Ruby provides a way around this - you can define methods that are available only for a specific object. Such methods are called Singleton Methods.

```<code>class Instance
  def instance_method
    puts "instance method called"
  end
end

in_obj = Instance.new
</code>```

The above statement you a reference object of class Instance, you might get a different id.

```<code>#<Instance:0x00000000e9ee68>
</code>```

let's call the instance method with the object and we will get output.

```<code>in_obj.instance_method
instance method called
</code>```

Now, create the singleton method.

```<code>sin_obj = Instance.new
#<Instance:0x00000000e98d60>
def sin_obj.singleton_method
  puts "singleton method called"
end
</code>```

calling the singleton method

```<code>sin_obj.sigleton_method
singleton method called
</code>```

Here, the object sin_obj has the singleton method singleton_method. This is a
  singleton method because it belongs to just one instance of a class
  and will not be shared with others.

However, singleton methods contradict that instance objects cannot
  hold methods, only class definitions (objects of class Class) can. It
  happens that the truth is somewhere in-between.
  When you declare a singleton method on an object, Ruby automatically creates a class to hold just that method. This class is called the 'metaclass' of the object. All subsequent singleton methods of this object goes to its metaclass. Whenever you send a message to the object, it first looks to see whether the method exists in its metaclass. If it is not there, it gets propagated to the actual class of the object and if it is not found there, the message traverses the inheritance hierarchy.
  Let defined the class method in the same Instance class.
  Now, lets check the fact that I stats above with an example.

```<code>foo = "Hey I am a string"
def foo.foo_instance_method
    p self.upcase
end
</code>```

Verify the fact that signleton method definition goes to the meta class.

```<code>p foo.class.instance_methods.include?:foo_instance_method
 false
p foo.metaclass.instance_methods.include?:foo_instance_method
 true
p foo.metaclass.class
 Class
p foo.metaclass
 #<Class:#<String:0x00000000e8f0f8>>
</code>```

Let look how meta class is implemented.

```<code>class Instance
  def metaclass
    class << self
      self
    end
  end
end
</code>```

The class << self syntax changes the current self to point to the metaclass of the current object. Since we are already inside an instance method, this would be the instance's metaclass. The method simply returns self which at this point is the metaclass of the instance.

A metaclass is almost a class in many respects. It however can't be
  instantiated. To check this see the example below.

```<code>a = Instance.new
a.metaclass.new
You will get is error when try to intantiate the meta class.
*TypeError: can't create instance of singleton class*
</code>```

In Ruby, both 'metaclass' and 'singleton class' means the same. You'll
  find them being used interchangeably in Ruby literature.

```<code>class Instance
    def self.class_method #instead one can use def Instance.class_method
        puts "class method called"
    end
end
</code>```

However, one can also follow this syntax to defined a class method

```<code>class Instance
  class << self
    def show
      puts "Class method show invoked"
    end
  end
end
</code>```

calling class_method

```<code>Instance.class_method
class method called
Instance.show
Class method show invoked
</code>```

It consists of building a new anonymous class only for the current object (self). To create the anonymous class, we use the << notation. Look closely how class method and singleton method are defined you find the difference.
consider the example.

```<code>class Instance
 puts self
 def meth
  p self
 end
end
</code>```

here, outside of meth method self is nothing but the class, inside an instance_method the self pointing to the current instance or object.

Additionally, You can also check that a method responds to a particular object or not.

```<code>p Instance.new.respond_to?(:singleton_method)
p Instance.new.respond_to?(:class_method)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Singleton method vs. class method

Body:
Are class method and singleton method doing the same or different? Here is an example.

class C
  def self.classmethod
    puts "class method #{self}"
  end
end

C.classmethod  # class method C
c = C.new

def c.singletonmethod
  puts "instance method #{self}"
end

c.singletonmethod  # instance method #<C:0x0000000118ed08>

Body:
Since all methods are implemented and stored by the class definition, it should be impossible for an object to define its own methods. However, Ruby provides a way around this - you can define methods that are available only for a specific object. Such methods are called Singleton Methods.

class Instance
  def instance_method
    puts "instance method called"
  end
end

in_obj = Instance.new

The above statement you a reference object of class Instance, you might get a different id.

#<Instance:0x00000000e9ee68>

let's call the instance method with the object and we will get output.

in_obj.instance_method
instance method called

Now, create the singleton method.

sin_obj = Instance.new
#<Instance:0x00000000e98d60>
def sin_obj.singleton_method
  puts "singleton method called"
end

calling the singleton method

sin_obj.sigleton_method
singleton method called

Here, the object sin_obj has the singleton method singleton_method. This is a
  singleton method because it belongs to just one instance of a class
  and will not be shared with others.

However, singleton methods contradict that instance objects cannot
  hold methods, only class definitions (objects of class Class) can. It
  happens that the truth is somewhere in-between.
  When you declare a singleton method on an object, Ruby automatically creates a class to hold just that method. This class is called the 'metaclass' of the object. All subsequent singleton methods of this object goes to its metaclass. Whenever you send a message to the object, it first looks to see whether the method exists in its metaclass. If it is not there, it gets propagated to the actual class of the object and if it is not found there, the message traverses the inheritance hierarchy.
  Let defined the class method in the same Instance class.
  Now, lets check the fact that I stats above with an example.

foo = "Hey I am a string"
def foo.foo_instance_method
    p self.upcase
end

Verify the fact that signleton method definition goes to the meta class.

p foo.class.instance_methods.include?:foo_instance_method
 false
p foo.metaclass.instance_methods.include?:foo_instance_method
 true
p foo.metaclass.class
 Class
p foo.metaclass
 #<Class:#<String:0x00000000e8f0f8>>

Let look how meta class is implemented.

class Instance
  def metaclass
    class << self
      self
    end
  end
end

The class << self syntax changes the current self to point to the metaclass of the current object. Since we are already inside an instance method, this would be the instance's metaclass. The method simply returns self which at this point is the metaclass of the instance.

A metaclass is almost a class in many respects. It however can't be
  instantiated. To check this see the example below.

a = Instance.new
a.metaclass.new
You will get is error when try to intantiate the meta class.
*TypeError: can't create instance of singleton class*

In Ruby, both 'metaclass' and 'singleton class' means the same. You'll
  find them being used interchangeably in Ruby literature.

class Instance
    def self.class_method #instead one can use def Instance.class_method
        puts "class method called"
    end
end

However, one can also follow this syntax to defined a class method

class Instance
  class << self
    def show
      puts "Class method show invoked"
    end
  end
end

calling class_method

Instance.class_method
class method called
Instance.show
Class method show invoked

It consists of building a new anonymous class only for the current object (self). To create the anonymous class, we use the << notation. Look closely how class method and singleton method are defined you find the difference.
consider the example.

class Instance
 puts self
 def meth
  p self
 end
end

here, outside of meth method self is nothing but the class, inside an instance_method the self pointing to the current instance or object.

Additionally, You can also check that a method responds to a particular object or not.

p Instance.new.respond_to?(:singleton_method)
p Instance.new.respond_to?(:class_method)


问:
RewriteCond %{QUERY_STRING} ignore capital letters
I'm trying to redirect

forum/show.asp?messageid=22  and forum/show.asp?messageID=22

to:

http://www.example.com/forum/show/22

I did this role:

```<code>RewriteCond %{QUERY_STRING} ^messageid=(\d+)
RewriteRule ^forum/show.asp?$    http://www.example.com/forum/show/%1 [R=301,NC,L]
</code>```

But It's ignoring forum/show.asp?messageID=22

What can I do?

答:
Change the regex :)

```<code>RewriteCond %{QUERY_STRING} ^(?i)messageid=(\d+)
RewriteRule ^forum/show.asp?$    http://www.example.com/forum/show/%1 [R=301,NC,L]
</code>```

Notice the (?i), which indicates case insensitivity.

https://regex101.com/r/8hw1J8/1

Explanation is on the right panel when you follow the link.

Body:
I'm trying to redirect

forum/show.asp?messageid=22  and forum/show.asp?messageID=22

to:

http://www.example.com/forum/show/22

I did this role:

RewriteCond %{QUERY_STRING} ^messageid=(\d+)
RewriteRule ^forum/show.asp?$    http://www.example.com/forum/show/%1 [R=301,NC,L]

But It's ignoring forum/show.asp?messageID=22

What can I do?

Body:
Change the regex :)

RewriteCond %{QUERY_STRING} ^(?i)messageid=(\d+)
RewriteRule ^forum/show.asp?$    http://www.example.com/forum/show/%1 [R=301,NC,L]

Notice the (?i), which indicates case insensitivity.

https://regex101.com/r/8hw1J8/1

Explanation is on the right panel when you follow the link.


问:
Inline Object Comparison Java
I am trying to sort an arraylist with the following method. I want US to be first, followed by UK, etc. However this doesn't seem to be doing anything. What am I doing wrong?</p>

```<code>    orderedTerritories.sort((o1, o2) -> {
        if (o1.getCode().equals("US*"))
            return 1;
        else if (o2.getCode().equals("US*"))
            return 0;
        else if (o1.getCode().contains("UK") && o1.getContains() != null)
            return 1;
        else if (o2.getCode().contains("UK") && o2.getContains() != null)
            return 0;
        else if (o1.getCode().equals("DE*"))
            return 1;
        else if (o2.getCode().equals("DE*"))
            return 0;
        else if (o1.getCode().equals("JP"))
            return 1;
        else if (o2.getCode().equals("JP"))
            return 0;
        else if (o1.getCode().equals("IN"))
            return 1;
        else if (o2.getCode().equals("IN"))
            return 0;
        else return 1;
    });
</code>```

答:
Thank you, I factored in what you guys said to the following solution, which works:

```<code>       List<Territory> orderedTerritories = new LinkedList<>();
       List<Integer> integerValues = new ArrayList<>();
       Map<Integer, Territory> intToTerritoryMap = new HashMap<>();
       int i = 5;
       for (Territory territory : finalSet) {
            int index = 5;
            if (territory.getCode().equals("US*"))
                index = 0;
            else if (territory.getCode().contains("UK") && territory.getContains() != null)
                index = 1;
            else if (territory.getCode().equals("DE*"))
                index = 2;
            else if (territory.getCode().equals("JP"))
                index = 3;
            else if (territory.getCode().equals("IN"))
                index = 4;
            if (index < 5) {
                intToTerritoryMap.put(index, territory);
                integerValues.add(index);
            } else {
                intToTerritoryMap.put(i, territory);
                integerValues.add(i++);
            }
        }
        Collections.sort(integerValues);

        integerValues.forEach(j -> {
            orderedTerritories.add(intToTerritoryMap.get(j));
        });

        return orderedTerritories;
</code>```

Which is verbose and hard codes in numbers. I wish there was a simpler way.

Title: Inline Object Comparison Java

Body:
I am trying to sort an arraylist with the following method. I want US to be first, followed by UK, etc. However this doesn't seem to be doing anything. What am I doing wrong?

    orderedTerritories.sort((o1, o2) -> {
        if (o1.getCode().equals("US*"))
            return 1;
        else if (o2.getCode().equals("US*"))
            return 0;
        else if (o1.getCode().contains("UK") && o1.getContains() != null)
            return 1;
        else if (o2.getCode().contains("UK") && o2.getContains() != null)
            return 0;
        else if (o1.getCode().equals("DE*"))
            return 1;
        else if (o2.getCode().equals("DE*"))
            return 0;
        else if (o1.getCode().equals("JP"))
            return 1;
        else if (o2.getCode().equals("JP"))
            return 0;
        else if (o1.getCode().equals("IN"))
            return 1;
        else if (o2.getCode().equals("IN"))
            return 0;
        else return 1;
    });

Body:
Thank you, I factored in what you guys said to the following solution, which works:

       List<Territory> orderedTerritories = new LinkedList<>();
       List<Integer> integerValues = new ArrayList<>();
       Map<Integer, Territory> intToTerritoryMap = new HashMap<>();
       int i = 5;
       for (Territory territory : finalSet) {
            int index = 5;
            if (territory.getCode().equals("US*"))
                index = 0;
            else if (territory.getCode().contains("UK") && territory.getContains() != null)
                index = 1;
            else if (territory.getCode().equals("DE*"))
                index = 2;
            else if (territory.getCode().equals("JP"))
                index = 3;
            else if (territory.getCode().equals("IN"))
                index = 4;
            if (index < 5) {
                intToTerritoryMap.put(index, territory);
                integerValues.add(index);
            } else {
                intToTerritoryMap.put(i, territory);
                integerValues.add(i++);
            }
        }
        Collections.sort(integerValues);

        integerValues.forEach(j -> {
            orderedTerritories.add(intToTerritoryMap.get(j));
        });

        return orderedTerritories;

Which is verbose and hard codes in numbers. I wish there was a simpler way.


问:
Connections to api.github.com not working after windows 10 creator's update
I've been doing some laravel development over the past few months with no issue. After the Windows 10 Creator's update I've been unable to get any OpenSSL related functionality to work. They all point to the same error code: 1.

First failed attempt was something simple like:

```<code>laravel new blog
</code>```

produces the following output

```<code>Crafting application...
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Package operations: 59 installs, 0 updates, 0 removals
  - Installing doctrine/inflector (v1.1.0): Loading from cache
  - Installing erusev/parsedown (1.6.2): Downloading (failed)
Downloading (failed)
Downloading (failed)    Failed to download erusev/parsedown from dist: The "https://api.github.com/repos/erusev/parsedown/zipball/1bf24f7334fe16c88bf9d467863309ceaf285b01" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
Failed to enable crypto
failed to open stream: operation failed
Now trying to download from source
</code>```

... And continues on like that for most of the packages

Re-installing php didn't help

I tried reinstalling php to a newer version 7.1.5 instead of my current 7.1.3 (which worked before the Creator's Update).

Trying to update composer didn't fix it

I went to reinstall composer and get basically the same errors posted above, but just one single error:

```<code>The "https://getcomposer.org/versions" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
Failed to enable crypto
failed to open stream: operation failed
</code>```

I'm not sure if I changed some setting when I allowed the Windows 10 Creator's Update that broke all of this.

Any help would be greatly appreciated.

答:
```<code>Downloading (failed)    Failed to download erusev/parsedown from dist: The
</code>```

"https://api.github.com/repos/erusev/parsedown/zipball/1bf24f7334fe16c88bf9d467863309ceaf285b01"
  file could not be downloaded: SSL operation failed with code 1.
  OpenSSL Error messages:
      error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed

You need to provide more information, like the precise details of the connection and the trust store details.

Here are three things you should ensure:

Use Server Name Indication (SNI)

Use TLS 1.0 and above

Install the DigiCert SHA2 High Assurance Server CA in your trust store.

```<code>$ openssl s_client -connect api.github.com:443 -servername api.github.com -tls1 | openssl x509 -text -noout
depth=1 C = US, O = DigiCert Inc, OU = www.digicert.com, CN = DigiCert SHA2 High Assurance Server CA
verify error:num=20:unable to get local issuer certificate
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            0d:9d:dd:e7:cf:ac:61:9a:c3:86:6f:ae:35:45:8a:94
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert SHA2 High Assurance Server CA
        Validity
            Not Before: Jan 18 00:00:00 2017 GMT
            Not After : Apr 17 12:00:00 2020 GMT
        Subject: C=US, ST=California, L=San Francisco, O=GitHub, Inc., CN=*.github.com
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:a9:c0:8f:30:49:2d:bb:12:e8:0c:0c:5d:1d:08:
                    08:f7:91:70:78:7e:05:6b:af:8b:b2:55:36:aa:69:
                    94:04:5f:a9:bb:86:4e:52:fa:48:43:15:54:e7:0a:
                    9d:59:ac:59:6a:ec:46:d6:76:14:4e:b0:16:74:f6:
                    f5:9f:4b:a6:80:bb:06:13:b5:98:5c:99:d0:3c:97:
                    b0:20:ae:10:86:e6:b4:2e:ca:e2:ac:87:47:91:cc:
                    07:43:cd:cd:11:88:fe:96:cc:21:83:47:d4:41:44:
                    6d:d3:a5:2d:6b:96:a4:2e:8b:c3:74:93:cb:a9:3b:
                    93:4b:f9:ec:84:e6:bb:ea:14:74:a2:e5:a7:ae:ab:
                    9c:2c:bd:6c:cd:cb:d7:fe:86:c1:f8:db:1b:9a:be:
                    7c:32:b8:3c:a6:b4:1f:46:82:ba:89:bc:e5:67:2b:
                    15:f3:ca:8f:70:2a:5c:e7:b9:6a:e9:00:4a:43:61:
                    7d:5a:04:0c:b2:c4:22:81:77:d3:36:6f:25:00:04:
                    3e:2f:a8:02:66:78:1d:e0:a7:c7:60:f4:89:60:0d:
                    3b:a0:55:a6:b9:23:9a:96:08:74:d1:68:7c:3d:48:
                    ee:44:6a:dc:37:15:a9:9a:07:c0:2d:01:c7:15:88:
                    28:0d:c0:fe:6b:cf:86:a0:99:3e:19:d2:5d:de:89:
                    e0:65
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Authority Key Identifier:
                keyid:51:68:FF:90:AF:02:07:75:3C:CC:D9:65:64:62:A2:12:B8:59:72:3B

            X509v3 Subject Key Identifier:
                EA:61:52:B2:FE:0A:40:80:E5:20:8A:30:37:24:A0:EA:A6:6C:6A:AA
            X509v3 Subject Alternative Name:
                DNS:*.github.com, DNS:github.com
            X509v3 Key Usage: critical
                Digital Signature, Key Encipherment
            X509v3 Extended Key Usage:
                TLS Web Server Authentication, TLS Web Client Authentication
            X509v3 CRL Distribution Points:

                Full Name:
                  URI:http://crl3.digicert.com/sha2-ha-server-g5.crl

                Full Name:
                  URI:http://crl4.digicert.com/sha2-ha-server-g5.crl

            X509v3 Certificate Policies:
                Policy: 2.16.840.1.114412.1.1
                  CPS: https://www.digicert.com/CPS
                Policy: 2.23.140.1.2.2

            Authority Information Access:
                OCSP - URI:http://ocsp.digicert.com
                CA Issuers - URI:http://cacerts.digicert.com/DigiCertSHA2HighAssuranceServerCA.crt

            X509v3 Basic Constraints: critical
                CA:FALSE
            CT Precertificate SCTs:
                Signed Certificate Timestamp:
                    Version   : v1(0)
                    Log ID    : A4:B9:09:90:B4:18:58:14:87:BB:13:A2:CC:67:70:0A:
                                3C:35:98:04:F9:1B:DF:B8:E3:77:CD:0E:C8:0D:DC:10
                    Timestamp : Jan 18 17:25:01.131 2017 GMT
                    Extensions: none
                    Signature : ecdsa-with-SHA256
                                30:44:02:20:1E:AC:0E:EF:D1:B5:53:47:56:E5:29:3E:
                                88:CC:41:5D:34:06:D2:F4:9D:BE:B0:C2:32:37:A0:DA:
                                77:C4:06:42:02:20:03:DE:1E:2A:28:E7:D7:67:11:3A:
                                1A:F3:34:3E:BE:B6:15:56:FC:F7:48:99:4C:D3:12:87:
                                42:18:58:1A:08:F5
                Signed Certificate Timestamp:
                    Version   : v1(0)
                    Log ID    : 56:14:06:9A:2F:D7:C2:EC:D3:F5:E1:BD:44:B2:3E:C7:
                                46:76:B9:BC:99:11:5C:C0:EF:94:98:55:D6:89:D0:DD
                    Timestamp : Jan 18 17:25:01.340 2017 GMT
                    Extensions: none
                    Signature : ecdsa-with-SHA256
                                30:45:02:20:24:A6:69:92:C0:28:82:C6:2D:7C:BD:B5:
                                B0:C2:45:CA:8A:C7:82:9A:5D:A3:85:20:2C:54:1C:B0:
                                DA:BE:1B:D3:02:21:00:8A:25:EF:B9:CA:F5:65:81:DC:
                                A0:9D:62:C7:EF:D4:03:25:B8:4B:2D:7E:49:F2:31:57:
                                FF:CF:56:E3:2E:98:57
                Signed Certificate Timestamp:
                    Version   : v1(0)
                    Log ID    : EE:4B:BD:B7:75:CE:60:BA:E1:42:69:1F:AB:E1:9E:66:
                                A3:0F:7E:5F:B0:72:D8:83:00:C4:7B:89:7A:A8:FD:CB
                    Timestamp : Jan 18 17:25:01.614 2017 GMT
                    Extensions: none
                    Signature : ecdsa-with-SHA256
                                30:44:02:20:72:AB:CC:0E:48:6F:33:44:18:CA:F6:36:
                                66:E6:70:99:DC:B9:44:D9:1E:C1:D1:26:A5:34:78:26:
                                5C:89:A9:F9:02:20:46:18:85:F9:69:D5:94:6E:3B:85:
                                5A:20:5B:D5:99:C4:91:8B:07:F3:5F:E8:CD:B6:06:9B:
                                9C:58:DF:A2:24:C7
                Signed Certificate Timestamp:
                    Version   : v1(0)
                    Log ID    : BB:D9:DF:BC:1F:8A:71:B5:93:94:23:97:AA:92:7B:47:
                                38:57:95:0A:AB:52:E8:1A:90:96:64:36:8E:1E:D1:85
                    Timestamp : Jan 18 17:25:01.149 2017 GMT
                    Extensions: none
                    Signature : ecdsa-with-SHA256
                                30:45:02:21:00:92:4C:BD:09:5D:FD:CE:FD:02:D8:45:
                                12:3D:36:A9:57:5A:CD:FF:D2:9A:39:1B:FA:08:0D:FC:
                                38:EB:48:1D:BC:02:20:06:12:34:B0:C4:28:F8:AF:E3:
                                E7:52:0C:C5:B5:44:5B:2E:87:E4:DE:20:2F:10:22:E3:
                                F4:D6:4E:D9:26:5B:75
    Signature Algorithm: sha256WithRSAEncryption
         7c:83:2f:49:4a:bd:67:81:14:9e:22:3d:ef:a6:8e:91:74:d2:
         3f:06:bc:19:3f:8a:17:39:4b:a5:cc:8f:99:c5:3f:c7:c0:13:
         a6:d5:2c:01:19:d2:f7:a6:33:c7:b0:56:b5:c8:69:ad:7b:03:
         58:a7:45:2e:09:90:fd:84:d3:76:05:1f:cb:f4:32:cb:b6:da:
         26:f0:b2:2f:00:5f:e1:c2:69:b0:17:58:68:ac:5c:8a:07:b6:
         76:70:09:8e:05:48:be:5f:23:10:ee:24:fa:50:f9:05:68:2a:
         42:04:44:94:35:e3:d1:25:55:41:0d:70:77:43:19:4c:a5:a5:
         0d:56:f1:98:ab:17:ce:ee:48:d2:45:82:1b:af:e6:7c:17:09:
         73:ee:87:f8:00:56:73:56:08:2b:ea:4b:3f:58:c3:61:c0:bc:
         c2:3f:5f:46:44:c2:a5:95:bf:de:56:7f:36:df:ac:9c:cd:6e:
         8d:34:59:ed:14:c1:95:11:b6:b8:92:e9:21:7d:79:26:28:52:
         a6:b1:2b:de:ed:fd:44:75:29:1c:e3:83:2c:dc:d5:03:0e:b7:
         cd:f2:6a:08:9b:cf:b5:a0:ab:fb:f2:97:2a:ba:9f:8e:4f:59:
         f9:ee:cd:9a:0f:88:c4:e7:f8:33:f3:31:6e:8c:78:28:9b:cb:
         95:7f:29:c1
</code>```

Body:
I've been doing some laravel development over the past few months with no issue. After the Windows 10 Creator's update I've been unable to get any OpenSSL related functionality to work. They all point to the same error code: 1.

First failed attempt was something simple like:

laravel new blog

produces the following output

Crafting application...
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Package operations: 59 installs, 0 updates, 0 removals
  - Installing doctrine/inflector (v1.1.0): Loading from cache
  - Installing erusev/parsedown (1.6.2): Downloading (failed)
Downloading (failed)
Downloading (failed)    Failed to download erusev/parsedown from dist: The "https://api.github.com/repos/erusev/parsedown/zipball/1bf24f7334fe16c88bf9d467863309ceaf285b01" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
Failed to enable crypto
failed to open stream: operation failed
Now trying to download from source

... And continues on like that for most of the packages

Re-installing php didn't help

I tried reinstalling php to a newer version 7.1.5 instead of my current 7.1.3 (which worked before the Creator's Update).

Trying to update composer didn't fix it

I went to reinstall composer and get basically the same errors posted above, but just one single error:

The "https://getcomposer.org/versions" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
Failed to enable crypto
failed to open stream: operation failed

I'm not sure if I changed some setting when I allowed the Windows 10 Creator's Update that broke all of this.

Any help would be greatly appreciated.

Body:
Downloading (failed)    Failed to download erusev/parsedown from dist: The

"https://api.github.com/repos/erusev/parsedown/zipball/1bf24f7334fe16c88bf9d467863309ceaf285b01"
  file could not be downloaded: SSL operation failed with code 1.
  OpenSSL Error messages:
      error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed

You need to provide more information, like the precise details of the connection and the trust store details.

Here are three things you should ensure:

Use Server Name Indication (SNI)

Use TLS 1.0 and above

Install the DigiCert SHA2 High Assurance Server CA in your trust store.

$ openssl s_client -connect api.github.com:443 -servername api.github.com -tls1 | openssl x509 -text -noout
depth=1 C = US, O = DigiCert Inc, OU = www.digicert.com, CN = DigiCert SHA2 High Assurance Server CA
verify error:num=20:unable to get local issuer certificate
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            0d:9d:dd:e7:cf:ac:61:9a:c3:86:6f:ae:35:45:8a:94
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert SHA2 High Assurance Server CA
        Validity
            Not Before: Jan 18 00:00:00 2017 GMT
            Not After : Apr 17 12:00:00 2020 GMT
        Subject: C=US, ST=California, L=San Francisco, O=GitHub, Inc., CN=*.github.com
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:a9:c0:8f:30:49:2d:bb:12:e8:0c:0c:5d:1d:08:
                    08:f7:91:70:78:7e:05:6b:af:8b:b2:55:36:aa:69:
                    94:04:5f:a9:bb:86:4e:52:fa:48:43:15:54:e7:0a:
                    9d:59:ac:59:6a:ec:46:d6:76:14:4e:b0:16:74:f6:
                    f5:9f:4b:a6:80:bb:06:13:b5:98:5c:99:d0:3c:97:
                    b0:20:ae:10:86:e6:b4:2e:ca:e2:ac:87:47:91:cc:
                    07:43:cd:cd:11:88:fe:96:cc:21:83:47:d4:41:44:
                    6d:d3:a5:2d:6b:96:a4:2e:8b:c3:74:93:cb:a9:3b:
                    93:4b:f9:ec:84:e6:bb:ea:14:74:a2:e5:a7:ae:ab:
                    9c:2c:bd:6c:cd:cb:d7:fe:86:c1:f8:db:1b:9a:be:
                    7c:32:b8:3c:a6:b4:1f:46:82:ba:89:bc:e5:67:2b:
                    15:f3:ca:8f:70:2a:5c:e7:b9:6a:e9:00:4a:43:61:
                    7d:5a:04:0c:b2:c4:22:81:77:d3:36:6f:25:00:04:
                    3e:2f:a8:02:66:78:1d:e0:a7:c7:60:f4:89:60:0d:
                    3b:a0:55:a6:b9:23:9a:96:08:74:d1:68:7c:3d:48:
                    ee:44:6a:dc:37:15:a9:9a:07:c0:2d:01:c7:15:88:
                    28:0d:c0:fe:6b:cf:86:a0:99:3e:19:d2:5d:de:89:
                    e0:65
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Authority Key Identifier:
                keyid:51:68:FF:90:AF:02:07:75:3C:CC:D9:65:64:62:A2:12:B8:59:72:3B

            X509v3 Subject Key Identifier:
                EA:61:52:B2:FE:0A:40:80:E5:20:8A:30:37:24:A0:EA:A6:6C:6A:AA
            X509v3 Subject Alternative Name:
                DNS:*.github.com, DNS:github.com
            X509v3 Key Usage: critical
                Digital Signature, Key Encipherment
            X509v3 Extended Key Usage:
                TLS Web Server Authentication, TLS Web Client Authentication
            X509v3 CRL Distribution Points:

                Full Name:
                  URI:http://crl3.digicert.com/sha2-ha-server-g5.crl

                Full Name:
                  URI:http://crl4.digicert.com/sha2-ha-server-g5.crl

            X509v3 Certificate Policies:
                Policy: 2.16.840.1.114412.1.1
                  CPS: https://www.digicert.com/CPS
                Policy: 2.23.140.1.2.2

            Authority Information Access:
                OCSP - URI:http://ocsp.digicert.com
                CA Issuers - URI:http://cacerts.digicert.com/DigiCertSHA2HighAssuranceServerCA.crt

            X509v3 Basic Constraints: critical
                CA:FALSE
            CT Precertificate SCTs:
                Signed Certificate Timestamp:
                    Version   : v1(0)
                    Log ID    : A4:B9:09:90:B4:18:58:14:87:BB:13:A2:CC:67:70:0A:
                                3C:35:98:04:F9:1B:DF:B8:E3:77:CD:0E:C8:0D:DC:10
                    Timestamp : Jan 18 17:25:01.131 2017 GMT
                    Extensions: none
                    Signature : ecdsa-with-SHA256
                                30:44:02:20:1E:AC:0E:EF:D1:B5:53:47:56:E5:29:3E:
                                88:CC:41:5D:34:06:D2:F4:9D:BE:B0:C2:32:37:A0:DA:
                                77:C4:06:42:02:20:03:DE:1E:2A:28:E7:D7:67:11:3A:
                                1A:F3:34:3E:BE:B6:15:56:FC:F7:48:99:4C:D3:12:87:
                                42:18:58:1A:08:F5
                Signed Certificate Timestamp:
                    Version   : v1(0)
                    Log ID    : 56:14:06:9A:2F:D7:C2:EC:D3:F5:E1:BD:44:B2:3E:C7:
                                46:76:B9:BC:99:11:5C:C0:EF:94:98:55:D6:89:D0:DD
                    Timestamp : Jan 18 17:25:01.340 2017 GMT
                    Extensions: none
                    Signature : ecdsa-with-SHA256
                                30:45:02:20:24:A6:69:92:C0:28:82:C6:2D:7C:BD:B5:
                                B0:C2:45:CA:8A:C7:82:9A:5D:A3:85:20:2C:54:1C:B0:
                                DA:BE:1B:D3:02:21:00:8A:25:EF:B9:CA:F5:65:81:DC:
                                A0:9D:62:C7:EF:D4:03:25:B8:4B:2D:7E:49:F2:31:57:
                                FF:CF:56:E3:2E:98:57
                Signed Certificate Timestamp:
                    Version   : v1(0)
                    Log ID    : EE:4B:BD:B7:75:CE:60:BA:E1:42:69:1F:AB:E1:9E:66:
                                A3:0F:7E:5F:B0:72:D8:83:00:C4:7B:89:7A:A8:FD:CB
                    Timestamp : Jan 18 17:25:01.614 2017 GMT
                    Extensions: none
                    Signature : ecdsa-with-SHA256
                                30:44:02:20:72:AB:CC:0E:48:6F:33:44:18:CA:F6:36:
                                66:E6:70:99:DC:B9:44:D9:1E:C1:D1:26:A5:34:78:26:
                                5C:89:A9:F9:02:20:46:18:85:F9:69:D5:94:6E:3B:85:
                                5A:20:5B:D5:99:C4:91:8B:07:F3:5F:E8:CD:B6:06:9B:
                                9C:58:DF:A2:24:C7
                Signed Certificate Timestamp:
                    Version   : v1(0)
                    Log ID    : BB:D9:DF:BC:1F:8A:71:B5:93:94:23:97:AA:92:7B:47:
                                38:57:95:0A:AB:52:E8:1A:90:96:64:36:8E:1E:D1:85
                    Timestamp : Jan 18 17:25:01.149 2017 GMT
                    Extensions: none
                    Signature : ecdsa-with-SHA256
                                30:45:02:21:00:92:4C:BD:09:5D:FD:CE:FD:02:D8:45:
                                12:3D:36:A9:57:5A:CD:FF:D2:9A:39:1B:FA:08:0D:FC:
                                38:EB:48:1D:BC:02:20:06:12:34:B0:C4:28:F8:AF:E3:
                                E7:52:0C:C5:B5:44:5B:2E:87:E4:DE:20:2F:10:22:E3:
                                F4:D6:4E:D9:26:5B:75
    Signature Algorithm: sha256WithRSAEncryption
         7c:83:2f:49:4a:bd:67:81:14:9e:22:3d:ef:a6:8e:91:74:d2:
         3f:06:bc:19:3f:8a:17:39:4b:a5:cc:8f:99:c5:3f:c7:c0:13:
         a6:d5:2c:01:19:d2:f7:a6:33:c7:b0:56:b5:c8:69:ad:7b:03:
         58:a7:45:2e:09:90:fd:84:d3:76:05:1f:cb:f4:32:cb:b6:da:
         26:f0:b2:2f:00:5f:e1:c2:69:b0:17:58:68:ac:5c:8a:07:b6:
         76:70:09:8e:05:48:be:5f:23:10:ee:24:fa:50:f9:05:68:2a:
         42:04:44:94:35:e3:d1:25:55:41:0d:70:77:43:19:4c:a5:a5:
         0d:56:f1:98:ab:17:ce:ee:48:d2:45:82:1b:af:e6:7c:17:09:
         73:ee:87:f8:00:56:73:56:08:2b:ea:4b:3f:58:c3:61:c0:bc:
         c2:3f:5f:46:44:c2:a5:95:bf:de:56:7f:36:df:ac:9c:cd:6e:
         8d:34:59:ed:14:c1:95:11:b6:b8:92:e9:21:7d:79:26:28:52:
         a6:b1:2b:de:ed:fd:44:75:29:1c:e3:83:2c:dc:d5:03:0e:b7:
         cd:f2:6a:08:9b:cf:b5:a0:ab:fb:f2:97:2a:ba:9f:8e:4f:59:
         f9:ee:cd:9a:0f:88:c4:e7:f8:33:f3:31:6e:8c:78:28:9b:cb:
         95:7f:29:c1


问:
Join to a table only when column value is true
I am using SQL Server 2005. I am trying to join 2 tables together, but only when a column value in the main table is true. Like this:

```<code>select * from T1
join T2 on T1.value = T2.value
where T2.value2 = 'variable2'
and T2.value3 = 'variable3'
</code>```

There is a column value in T1 which says if I have to use the values in T2. I could to a case around the where clause, but it will always join to the table, and if the value in T1 is false, there are no values in T2 to join to, so the select returns no rows.

You can't put a case around the join, so I am a little bit stuck with this ... can anyone help ?

答:
```<code>select *
from T1
join T2
  on  T1.value = T2.value
  and T1.booleancolumn = 1
where T2.value2 = 'variable2'
and T2.value3 = 'variable3';
</code>```

OwnerDisplayName: Arni Gunnar Ragnarsson

Body:
I am using SQL Server 2005. I am trying to join 2 tables together, but only when a column value in the main table is true. Like this:

select * from T1
join T2 on T1.value = T2.value
where T2.value2 = 'variable2'
and T2.value3 = 'variable3'

There is a column value in T1 which says if I have to use the values in T2. I could to a case around the where clause, but it will always join to the table, and if the value in T1 is false, there are no values in T2 to join to, so the select returns no rows.

You can't put a case around the join, so I am a little bit stuck with this ... can anyone help ?

OwnerDisplayName: Dave Markle

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Dave Markle


问:
Using decltype to declare the entire function type itself (not pointer!)
So I have a function with a specific signature in a header file, and I want to declare another function with the exact same signature inside a class without typing the parameters again, and of course, hopefully without a macro... The member function should also have an extra hidden parameter obviously, the this pointer (since it's not a static member function).

Now, I'm actually surprised that the following hack/trick works in both GCC and ICC, but I'm not sure if it's "legal" C++. I'm not particularly concerned with legality if it's a supported extension, but unfortunately I do not want it to break on a compiler version update because some people decided to arbitrarily block this useful feature since the standard says "no" (that kind of stuff really annoys me to be honest).

Here's what I mean:

```<code>// test.hpp
int func(int x) { return x; }

struct foo
{
  decltype(func) fn;  // <-- legal?
};

int test()
{
  return foo().fn(6);
}

// then in test.cpp
int foo::fn(int x) { return x + 42; }
</code>```

This works (with GCC and ICC), but I don't know if it's "legal" in the standard. I'm asking just to be assured that it is legal and it won't suddenly stop working in the future.

(if it's not legal and you want to report it as a bug, please mark it as a suggestion to make it a legal compiler extension instead of killing it...)

Basically, it's the same as declaring int fn(int x); in the struct, and that's how it works currently.

If you ask me for a use case: it's to declare a wrapper member function for the other free function which does something with the this pointer before passing it to the free function. Its parameters must match exactly, obviously. Again, I don't want to type the parameters again.

答: That looks legal; but at definition you have to retype.  Consider using perfect forwarding instead.</p>

Body:
So I have a function with a specific signature in a header file, and I want to declare another function with the exact same signature inside a class without typing the parameters again, and of course, hopefully without a macro... The member function should also have an extra hidden parameter obviously, the this pointer (since it's not a static member function).

Now, I'm actually surprised that the following hack/trick works in both GCC and ICC, but I'm not sure if it's "legal" C++. I'm not particularly concerned with legality if it's a supported extension, but unfortunately I do not want it to break on a compiler version update because some people decided to arbitrarily block this useful feature since the standard says "no" (that kind of stuff really annoys me to be honest).

Here's what I mean:

// test.hpp
int func(int x) { return x; }

struct foo
{
  decltype(func) fn;  // <-- legal?
};

int test()
{
  return foo().fn(6);
}

// then in test.cpp
int foo::fn(int x) { return x + 42; }

This works (with GCC and ICC), but I don't know if it's "legal" in the standard. I'm asking just to be assured that it is legal and it won't suddenly stop working in the future.

(if it's not legal and you want to report it as a bug, please mark it as a suggestion to make it a legal compiler extension instead of killing it...)

Basically, it's the same as declaring int fn(int x); in the struct, and that's how it works currently.

If you ask me for a use case: it's to declare a wrapper member function for the other free function which does something with the this pointer before passing it to the free function. Its parameters must match exactly, obviously. Again, I don't want to type the parameters again.


问:
How can I check the input from a message box's buttons in Python using the ctypes library?
So, I'm trying to store the input from a dialog box with the ctypes library:

```<code>import ctypes
def mbox(message, title, style):
    ctypes.windll.user32.MessageBoxW(message, title, style)

mbox("This is a message box test", "Message Box", 1)
</code>```

The style is, of course, an OK and a Cancel button. How do I take the input from when you click on one of the buttons and then split into a separate function or something, such as:

```<code>if [Insert said check here]:
    mbox("You pressed OK!", "Answer", 0)
else:
    mbox("You pressed Cancel!", "Answer", 0)
</code>```

答:
Provide the style MB_OKCANCEL to the MessageBox and test its return value. You can find the numerical values in the MessageBox function

```<code>import ctypes
class MbConstants:
    MB_OKCANCEL = 1
    IDCANCEL = 2
    IDOK = 1

def mbox(message, title):
    return ctypes.windll.user32.MessageBoxW(0,message, title, MbConstants.MB_OKCANCEL)

rc = mbox("message","title")
if  rc == MbConstants.IDOK:
    print("ok")
elif rc == MbConstants.IDCANCEL:
    print("cancel")
</code>```

Body:
So, I'm trying to store the input from a dialog box with the ctypes library:

import ctypes
def mbox(message, title, style):
    ctypes.windll.user32.MessageBoxW(message, title, style)

mbox("This is a message box test", "Message Box", 1)

The style is, of course, an OK and a Cancel button. How do I take the input from when you click on one of the buttons and then split into a separate function or something, such as:

if [Insert said check here]:
    mbox("You pressed OK!", "Answer", 0)
else:
    mbox("You pressed Cancel!", "Answer", 0)

Body:
Provide the style MB_OKCANCEL to the MessageBox and test its return value. You can find the numerical values in the MessageBox function

import ctypes
class MbConstants:
    MB_OKCANCEL = 1
    IDCANCEL = 2
    IDOK = 1

def mbox(message, title):
    return ctypes.windll.user32.MessageBoxW(0,message, title, MbConstants.MB_OKCANCEL)

rc = mbox("message","title")
if  rc == MbConstants.IDOK:
    print("ok")
elif rc == MbConstants.IDCANCEL:
    print("cancel")


问:
Variable quantifier in perl6
Suppose i want to match words with at least 4 letters, (and store them in an array), I have written the following regex, which works fine:

```<code>if ( $text ~~ m:g/(\w ** 4..*)/ )
{
  my @words = $/;
  ...
}
</code>```

The quantifier being from 4 to unlimited

```<code>**4..*
</code>```

Now if I try to substitute 4 with a scalar $min_length. Both:

```<code>if ($text ~~ m:g/(\w ** $::min_length..*)/)
</code>```

and:

```<code>if ($text ~~ m:g/(\w ** <$::min_length>..*)/)
</code>```

results in an error at compilation:
Quantifier quantifies nothing

Is there a way for having a scalar as a quantifier?

答:
When the right-hand side of the ** quantifier is not a number or range literal, but an arbitrary Perl 6 expression, you have to enclose it in braces:

my $text = "The quick brown fox jumps over the lazy dog.";
my $min-length = 4;

my @words = $text.comb(/ \w ** {$min-length .. *} /);

.say for @words;
```

<p>Output:</p>

```quick
brown
jumps
over
lazy
```

Title: Variable quantifier in perl6

Body:
Suppose i want to match words with at least 4 letters, (and store them in an array), I have written the following regex, which works fine:

if ( $text ~~ m:g/(\w ** 4..*)/ )
{
  my @words = $/;
  ...
}

The quantifier being from 4 to unlimited

**4..*

Now if I try to substitute 4 with a scalar $min_length. Both:

if ($text ~~ m:g/(\w ** $::min_length..*)/)

and:

if ($text ~~ m:g/(\w ** <$::min_length>..*)/)

results in an error at compilation:
Quantifier quantifies nothing

Is there a way for having a scalar as a quantifier?

Body:
When the right-hand side of the ** quantifier is not a number or range literal, but an arbitrary Perl 6 expression, you have to enclose it in braces:

my $text = "The quick brown fox jumps over the lazy dog.";
my $min-length = 4;

my @words = $text.comb(/ \w ** {$min-length .. *} /);

.say for @words;

Output:

quick
brown
jumps
over
lazy


问:
rsync with ssh without using credentials stored in ~/.ssh/config
I have a script that transfers files. Everytime I run it It needs to connect to a different host. That's why I'm adding the host as parameter.

The script is executed as: ./transfer.sh <hostname>

```<code>#!/bin/bash -evx

SSH="ssh \
-o UseRoaming=no \
-o UserKnownHostsFile=/dev/null \
-o StrictHostKeyChecking=no \
-i ~/.ssh/privateKey.pem \
-l ec2-user \
${1}"

files=(
  file1
  file2
)

files="${files[@]}"

# this works
$SSH

# this does not work
rsync -avzh --stats --progress $files -e $SSH:/home/ec2-user/

# also this does not work
rsync -avzh --stats --progress $files -e $SSH ec2-user@$1:/home/ec2-user/
</code>```

I can properly connect with the ssh connection stored in $SSH, but the rsync connection attempts fails because of the wrong key:

```<code>Permission denied (publickey).
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: unexplained error (code 255) at io.c(226) [sender=3.1.2]
</code>```

What would be the correct syntax for the rsync connection?

答:
Write set -x before the rsync line and watch how the arguments are expanded. I believe it will be wrong.

You need to enclose the ssh command with arguments (without hostname) into the quotes, otherwise the arguments will get passed to the rsync command and not to the ssh.

Body:
I have a script that transfers files. Everytime I run it It needs to connect to a different host. That's why I'm adding the host as parameter.

The script is executed as: ./transfer.sh <hostname>

#!/bin/bash -evx

SSH="ssh \
-o UseRoaming=no \
-o UserKnownHostsFile=/dev/null \
-o StrictHostKeyChecking=no \
-i ~/.ssh/privateKey.pem \
-l ec2-user \
${1}"

files=(
  file1
  file2
)

files="${files[@]}"

# this works
$SSH

# this does not work
rsync -avzh --stats --progress $files -e $SSH:/home/ec2-user/

# also this does not work
rsync -avzh --stats --progress $files -e $SSH ec2-user@$1:/home/ec2-user/

I can properly connect with the ssh connection stored in $SSH, but the rsync connection attempts fails because of the wrong key:

Permission denied (publickey).
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: unexplained error (code 255) at io.c(226) [sender=3.1.2]

What would be the correct syntax for the rsync connection?


问:
find file in subfolder, move to other directory, and delete subfolder after moving with find -exec
I am looking for the following:
I want to search files with .m4a in all subfolders in my directory. When a file with this ending was found, I would like to move it to another folder. But afterwards I would like to delete this subfolder. I am stuck with the last step.
So far I have:

```<code>    find . -name '*.m4a' -type f -exec mv {} /path/to/storage \;
</code>```

I don't know how to delete the subfolder, the m4a file was found in. Also I don't want to delete by accident any other folder (I mean in case I apply the rm command wrongly. Deleting a subfolder, where I found a m4a file in, is okay). Basically, I am not sure how to control the deleting and would I be able to add this command with another -exec in the find command, please?
Thank you!

答:
Something like this should be ok.

If you are happy with the results, you can remove the echo to perform real actions:

```<code>find . -name '*.m4a' -type f -exec sh -c 'echo "mv {} /path/to/storage";echo "rm -r "$(dirname {})"" ' \;
</code>```

Be carefull that if the /path/to/storage is a subdirectory under the current working working you performed find, will also be removed , like this:

```<code>$ pwd
/home/gv/Desktop/PythonTests/tmp/tmp2
$ find . -name 'test.txt' -exec sh -c 'echo "mv {} /home/gv/Desktop/PythonTests/tmp/tmp2";echo "rm -r "$(dirname {})"" ' \;
mv ./tmp3/test.txt /home/gv/Desktop/PythonTests/tmp/tmp2  #indeed test.txt was in subfolder tmp3 under cwd tmp2
rm -r ./tmp3  #this is good - file moved , tmp3 removed also
mv ./test.txt /home/gv/Desktop/PythonTests/tmp/tmp2  #oops. find returned the result after previous mv , now file is found under tmp2
rm -r .  #tmp2 gone also!
</code>```

Body:
I am looking for the following:
I want to search files with .m4a in all subfolders in my directory. When a file with this ending was found, I would like to move it to another folder. But afterwards I would like to delete this subfolder. I am stuck with the last step.
So far I have:

    find . -name '*.m4a' -type f -exec mv {} /path/to/storage \;

I don't know how to delete the subfolder, the m4a file was found in. Also I don't want to delete by accident any other folder (I mean in case I apply the rm command wrongly. Deleting a subfolder, where I found a m4a file in, is okay). Basically, I am not sure how to control the deleting and would I be able to add this command with another -exec in the find command, please?
Thank you!

Body:
Something like this should be ok.

If you are happy with the results, you can remove the echo to perform real actions:

find . -name '*.m4a' -type f -exec sh -c 'echo "mv {} /path/to/storage";echo "rm -r "$(dirname {})"" ' \;

Be carefull that if the /path/to/storage is a subdirectory under the current working working you performed find, will also be removed , like this:

$ pwd
/home/gv/Desktop/PythonTests/tmp/tmp2
$ find . -name 'test.txt' -exec sh -c 'echo "mv {} /home/gv/Desktop/PythonTests/tmp/tmp2";echo "rm -r "$(dirname {})"" ' \;
mv ./tmp3/test.txt /home/gv/Desktop/PythonTests/tmp/tmp2  #indeed test.txt was in subfolder tmp3 under cwd tmp2
rm -r ./tmp3  #this is good - file moved , tmp3 removed also
mv ./test.txt /home/gv/Desktop/PythonTests/tmp/tmp2  #oops. find returned the result after previous mv , now file is found under tmp2
rm -r .  #tmp2 gone also!


问:
Trying to to use Caffe classifier causes "sequence argument must have length equal to input rank "error
I am trying to use Caffe.Classifier class and its predict() method on my Imagenet trained caffemodel.

Images were resized to 256x256 and crops of 227x227 were used to train the net.

Everything is simple and straight forward, yet I keep getting weird errors such as the following :

```<code>---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-7-3b440ebf1f6e> in <module>()
     17                        image_dims=(256, 256))
     18
---> 19     out = net.predict([image_caffe], oversample=True)
     20     print(labels[out[0].argmax()].strip(),' (', out[0][out[0].argmax()] , ')')
     21     plabel = int(labels[out[0].argmax()].strip())

<ipython-input-5-e6ae1810b820> in predict(self, inputs, oversample)
     65         for ix, in_ in enumerate(inputs):
     66             print('image dims = ',self.image_dims[0],',',self.image_dims[1] ,'_in = ',in_.shape)
---> 67             input_[ix] = caffe.io.resize_image(in_, self.image_dims)
     68
     69         if oversample:

C:\Users\Master\Anaconda3\envs\anaconda35\lib\site-packages\caffe\io.py in resize_image(im, new_dims, interp_order)
    335         # ndimage interpolates anything but more slowly.
    336         scale = tuple(np.array(new_dims, dtype=float) / np.array(im.shape[:2]))
--> 337         resized_im = zoom(im, scale + (1,), order=interp_order)
    338     return resized_im.astype(np.float32)
    339

C:\Users\Master\Anaconda3\envs\anaconda35\lib\site-packages\scipy\ndimage\interpolation.py in zoom(input, zoom, output, order, mode, cval, prefilter)
    588     else:
    589         filtered = input
--> 590     zoom = _ni_support._normalize_sequence(zoom, input.ndim)
    591     output_shape = tuple(
    592             [int(round(ii * jj)) for ii, jj in zip(input.shape, zoom)])

C:\Users\Master\Anaconda3\envs\anaconda35\lib\site-packages\scipy\ndimage\_ni_support.py in _normalize_sequence(input, rank, array_type)
     63         if len(normalized) != rank:
     64             err = "sequence argument must have length equal to input rank"
---> 65             raise RuntimeError(err)
     66     else:
     67         normalized = [input] * rank

RuntimeError: sequence argument must have length equal to input rank
</code>```

And here is the snippets of code I'm using :

```<code>import sys
import caffe
import numpy as np
import lmdb
import matplotlib.pyplot as plt
import itertools

def flat_shape(x):
    "Returns x without singleton dimension, eg: (1,28,28) -> (28,28)"
    return x.reshape(x.shape)

def db_reader(fpath, type='lmdb'):
    if type == 'lmdb':
        return lmdb_reader(fpath)
    else:
        return leveldb_reader(fpath)

def lmdb_reader(fpath):
    import lmdb
    lmdb_env = lmdb.open(fpath)
    lmdb_txn = lmdb_env.begin()
    lmdb_cursor = lmdb_txn.cursor()

    for key, value in lmdb_cursor:
        datum = caffe.proto.caffe_pb2.Datum()
        datum.ParseFromString(value)
        label = int(datum.label)
        image = caffe.io.datum_to_array(datum).astype(np.uint8)
        yield (key, flat_shape(image), label)

def leveldb_reader(fpath):
    import leveldb
    db = leveldb.LevelDB(fpath)

    for key, value in db.RangeIter():
        datum = caffe.proto.caffe_pb2.Datum()
        datum.ParseFromString(value)
        label = int(datum.label)
        image = caffe.io.datum_to_array(datum).astype(np.uint8)
        yield (key, flat_shape(image), label)
</code>```

Classifier class (copied form Caffe's python directory):

```<code>    import numpy as np
    import caffe

    class Classifier(caffe.Net):
        """
        Classifier extends Net for image class prediction
        by scaling, center cropping, or oversampling.

        Parameters
        ----------
        image_dims : dimensions to scale input for cropping/sampling.
            Default is to scale to net input size for whole-image crop.
        mean, input_scale, raw_scale, channel_swap: params for
            preprocessing options.
        """
        def __init__(self, model_file, pretrained_file, image_dims=None,
                     mean=None, input_scale=None, raw_scale=None,
                     channel_swap=None):
            caffe.Net.__init__(self, model_file, pretrained_file, caffe.TEST)

            # configure pre-processing
            in_ = self.inputs[0]
            print('inputs[0]',self.inputs[0])
            self.transformer = caffe.io.Transformer(
                {in_: self.blobs[in_].data.shape})
            self.transformer.set_transpose(in_, (2, 0, 1))

            if mean is not None:
                self.transformer.set_mean(in_, mean)
            if input_scale is not None:
                self.transformer.set_input_scale(in_, input_scale)
            if raw_scale is not None:
                self.transformer.set_raw_scale(in_, raw_scale)
            if channel_swap is not None:
                self.transformer.set_channel_swap(in_, channel_swap)

            print('crops: ',self.blobs[in_].data.shape[2:])
            self.crop_dims = np.array(self.blobs[in_].data.shape[2:])
            if not image_dims:
                image_dims = self.crop_dims
            self.image_dims = image_dims

        def predict(self, inputs, oversample=True):
            """
            Predict classification probabilities of inputs.

            Parameters
            ----------
            inputs : iterable of (H x W x K) input ndarrays.
            oversample : boolean
                average predictions across center, corners, and mirrors
                when True (default). Center-only prediction when False.

            Returns
            -------
            predictions: (N x C) ndarray of class probabilities for N images and C
                classes.
            """
            # Scale to standardize input dimensions.
            input_ = np.zeros((len(inputs),
                               self.image_dims[0],
                               self.image_dims[1],
                               inputs[0].shape[2]),
                              dtype=np.float32)
            for ix, in_ in enumerate(inputs):
                print('image dims = ',self.image_dims[0],',',self.image_dims[1] ,'_in = ',in_.shape)
                input_[ix] = caffe.io.resize_image(in_, self.image_dims)

            if oversample:
                # Generate center, corner, and mirrored crops.
                input_ = caffe.io.oversample(input_, self.crop_dims)
            else:
                # Take center crop.
                center = np.array(self.image_dims) / 2.0
                crop = np.tile(center, (1, 2))[0] + np.concatenate([
                    -self.crop_dims / 2.0,
                    self.crop_dims / 2.0
                ])
                input_ = input_[:, crop[0]:crop[2], crop[1]:crop[3], :]

            # Classify
            caffe_in = np.zeros(np.array(input_.shape)[[0, 3, 1, 2]],
                                dtype=np.float32)
            for ix, in_ in enumerate(input_):
                caffe_in[ix] = self.transformer.preprocess(self.inputs[0], in_)
            out = self.forward_all(**{self.inputs[0]: caffe_in})
            predictions = out[self.outputs[0]]

            # For oversampling, average predictions across crops.
            if oversample:
                predictions = predictions.reshape((len(predictions) / 10, 10, -1))
                predictions = predictions.mean(1)

            return predictions
</code>```

Main section :

```<code>proto ='deploy.prototxt'
model='snap1.caffemodel'
mean='imagenet_mean.binaryproto'
db_path='G:/imagenet/ilsvrc12_val_lmdb'

# Extract mean from the mean image file
#mean_blobproto_new = caffe.proto.caffe_pb2.BlobProto()
#f = open(mean, 'rb')
#mean_blobproto_new.ParseFromString(f.read())
#mean_image = caffe.io.blobproto_to_array(mean_blobproto_new)
#f.close()
mu = np.load('mean.npy').mean(1).mean(1)
caffe.set_mode_gpu()
reader = lmdb_reader(db_path)

i = 0
for i, image, label in reader:
    image_caffe = image.reshape(1, *image.shape)
    print(image_caffe.shape, mu.shape)

    net = Classifier(proto, model,
                     mean= mu,
                     channel_swap=(2,1,0),
                     raw_scale=255,
                     image_dims=(256, 256))

    out = net.predict([image_caffe], oversample=True)
    print(i, labels[out[0].argmax()].strip(),' (', out[0][out[0].argmax()] , ')')
    i+=1
</code>```

What is wrong here?

答:
I found the cause, I had to feed the image in the form of 3D tensor not a 4D one!
so our 4d tensor:

```<code>image_caffe = image.reshape(1, *image.shape)
</code>```

needed to be changed to a 3D one:

```<code>image_caffe = image.transpose(2,1,0)
</code>```

As a side note, try using python2 for running any caffe related. python3 might work at first but will definitely cause a lot of headaches. for instance, predict method with oversample set to True, will crash under python3 but works just fine under python2!

Body:
I am trying to use Caffe.Classifier class and its predict() method on my Imagenet trained caffemodel.

Images were resized to 256x256 and crops of 227x227 were used to train the net.

Everything is simple and straight forward, yet I keep getting weird errors such as the following :

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-7-3b440ebf1f6e> in <module>()
     17                        image_dims=(256, 256))
     18
---> 19     out = net.predict([image_caffe], oversample=True)
     20     print(labels[out[0].argmax()].strip(),' (', out[0][out[0].argmax()] , ')')
     21     plabel = int(labels[out[0].argmax()].strip())

<ipython-input-5-e6ae1810b820> in predict(self, inputs, oversample)
     65         for ix, in_ in enumerate(inputs):
     66             print('image dims = ',self.image_dims[0],',',self.image_dims[1] ,'_in = ',in_.shape)
---> 67             input_[ix] = caffe.io.resize_image(in_, self.image_dims)
     68
     69         if oversample:

C:\Users\Master\Anaconda3\envs\anaconda35\lib\site-packages\caffe\io.py in resize_image(im, new_dims, interp_order)
    335         # ndimage interpolates anything but more slowly.
    336         scale = tuple(np.array(new_dims, dtype=float) / np.array(im.shape[:2]))
--> 337         resized_im = zoom(im, scale + (1,), order=interp_order)
    338     return resized_im.astype(np.float32)
    339

C:\Users\Master\Anaconda3\envs\anaconda35\lib\site-packages\scipy\ndimage\interpolation.py in zoom(input, zoom, output, order, mode, cval, prefilter)
    588     else:
    589         filtered = input
--> 590     zoom = _ni_support._normalize_sequence(zoom, input.ndim)
    591     output_shape = tuple(
    592             [int(round(ii * jj)) for ii, jj in zip(input.shape, zoom)])

C:\Users\Master\Anaconda3\envs\anaconda35\lib\site-packages\scipy\ndimage\_ni_support.py in _normalize_sequence(input, rank, array_type)
     63         if len(normalized) != rank:
     64             err = "sequence argument must have length equal to input rank"
---> 65             raise RuntimeError(err)
     66     else:
     67         normalized = [input] * rank

RuntimeError: sequence argument must have length equal to input rank

And here is the snippets of code I'm using :

import sys
import caffe
import numpy as np
import lmdb
import matplotlib.pyplot as plt
import itertools

def flat_shape(x):
    "Returns x without singleton dimension, eg: (1,28,28) -> (28,28)"
    return x.reshape(x.shape)

def db_reader(fpath, type='lmdb'):
    if type == 'lmdb':
        return lmdb_reader(fpath)
    else:
        return leveldb_reader(fpath)

def lmdb_reader(fpath):
    import lmdb
    lmdb_env = lmdb.open(fpath)
    lmdb_txn = lmdb_env.begin()
    lmdb_cursor = lmdb_txn.cursor()

    for key, value in lmdb_cursor:
        datum = caffe.proto.caffe_pb2.Datum()
        datum.ParseFromString(value)
        label = int(datum.label)
        image = caffe.io.datum_to_array(datum).astype(np.uint8)
        yield (key, flat_shape(image), label)

def leveldb_reader(fpath):
    import leveldb
    db = leveldb.LevelDB(fpath)

    for key, value in db.RangeIter():
        datum = caffe.proto.caffe_pb2.Datum()
        datum.ParseFromString(value)
        label = int(datum.label)
        image = caffe.io.datum_to_array(datum).astype(np.uint8)
        yield (key, flat_shape(image), label)

Classifier class (copied form Caffe's python directory):

    import numpy as np
    import caffe

    class Classifier(caffe.Net):
        """
        Classifier extends Net for image class prediction
        by scaling, center cropping, or oversampling.

        Parameters
        ----------
        image_dims : dimensions to scale input for cropping/sampling.
            Default is to scale to net input size for whole-image crop.
        mean, input_scale, raw_scale, channel_swap: params for
            preprocessing options.
        """
        def __init__(self, model_file, pretrained_file, image_dims=None,
                     mean=None, input_scale=None, raw_scale=None,
                     channel_swap=None):
            caffe.Net.__init__(self, model_file, pretrained_file, caffe.TEST)

            # configure pre-processing
            in_ = self.inputs[0]
            print('inputs[0]',self.inputs[0])
            self.transformer = caffe.io.Transformer(
                {in_: self.blobs[in_].data.shape})
            self.transformer.set_transpose(in_, (2, 0, 1))

            if mean is not None:
                self.transformer.set_mean(in_, mean)
            if input_scale is not None:
                self.transformer.set_input_scale(in_, input_scale)
            if raw_scale is not None:
                self.transformer.set_raw_scale(in_, raw_scale)
            if channel_swap is not None:
                self.transformer.set_channel_swap(in_, channel_swap)

            print('crops: ',self.blobs[in_].data.shape[2:])
            self.crop_dims = np.array(self.blobs[in_].data.shape[2:])
            if not image_dims:
                image_dims = self.crop_dims
            self.image_dims = image_dims

        def predict(self, inputs, oversample=True):
            """
            Predict classification probabilities of inputs.

            Parameters
            ----------
            inputs : iterable of (H x W x K) input ndarrays.
            oversample : boolean
                average predictions across center, corners, and mirrors
                when True (default). Center-only prediction when False.

            Returns
            -------
            predictions: (N x C) ndarray of class probabilities for N images and C
                classes.
            """
            # Scale to standardize input dimensions.
            input_ = np.zeros((len(inputs),
                               self.image_dims[0],
                               self.image_dims[1],
                               inputs[0].shape[2]),
                              dtype=np.float32)
            for ix, in_ in enumerate(inputs):
                print('image dims = ',self.image_dims[0],',',self.image_dims[1] ,'_in = ',in_.shape)
                input_[ix] = caffe.io.resize_image(in_, self.image_dims)

            if oversample:
                # Generate center, corner, and mirrored crops.
                input_ = caffe.io.oversample(input_, self.crop_dims)
            else:
                # Take center crop.
                center = np.array(self.image_dims) / 2.0
                crop = np.tile(center, (1, 2))[0] + np.concatenate([
                    -self.crop_dims / 2.0,
                    self.crop_dims / 2.0
                ])
                input_ = input_[:, crop[0]:crop[2], crop[1]:crop[3], :]

            # Classify
            caffe_in = np.zeros(np.array(input_.shape)[[0, 3, 1, 2]],
                                dtype=np.float32)
            for ix, in_ in enumerate(input_):
                caffe_in[ix] = self.transformer.preprocess(self.inputs[0], in_)
            out = self.forward_all(**{self.inputs[0]: caffe_in})
            predictions = out[self.outputs[0]]

            # For oversampling, average predictions across crops.
            if oversample:
                predictions = predictions.reshape((len(predictions) / 10, 10, -1))
                predictions = predictions.mean(1)

            return predictions

Main section :

proto ='deploy.prototxt'
model='snap1.caffemodel'
mean='imagenet_mean.binaryproto'
db_path='G:/imagenet/ilsvrc12_val_lmdb'

# Extract mean from the mean image file
#mean_blobproto_new = caffe.proto.caffe_pb2.BlobProto()
#f = open(mean, 'rb')
#mean_blobproto_new.ParseFromString(f.read())
#mean_image = caffe.io.blobproto_to_array(mean_blobproto_new)
#f.close()
mu = np.load('mean.npy').mean(1).mean(1)
caffe.set_mode_gpu()
reader = lmdb_reader(db_path)

i = 0
for i, image, label in reader:
    image_caffe = image.reshape(1, *image.shape)
    print(image_caffe.shape, mu.shape)

    net = Classifier(proto, model,
                     mean= mu,
                     channel_swap=(2,1,0),
                     raw_scale=255,
                     image_dims=(256, 256))

    out = net.predict([image_caffe], oversample=True)
    print(i, labels[out[0].argmax()].strip(),' (', out[0][out[0].argmax()] , ')')
    i+=1

What is wrong here?

Body:
I found the cause, I had to feed the image in the form of 3D tensor not a 4D one!
so our 4d tensor:

image_caffe = image.reshape(1, *image.shape)

needed to be changed to a 3D one:

image_caffe = image.transpose(2,1,0)

As a side note, try using python2 for running any caffe related. python3 might work at first but will definitely cause a lot of headaches. for instance, predict method with oversample set to True, will crash under python3 but works just fine under python2!


问:
Distance Transform in OpenCV Python automatically converting CV_8UC3 to CV_32SC1 creating an assertion error
I am trying to apply the WaterShed algorithm to an image as per the tutorial: OpenCv WaterShed Docs . I have earlier applied Otsu's thresholding after Gaussian filtering and Morpholigical Transformations on a greyscale image to improve Image quality as per the code:

```<code>img = cv2.imread('Results\Feb_16-0.jpg',0)
kernel = np.ones((1,1),np.uint8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
blur = cv2.GaussianBlur(opening,(1,1),0)
ret3,th4 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
</code>```

Applying the distance transform as the first stage of the watershed algorithm as per the code:

```<code># sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=1)
# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,3)
</code>```

creates the error:

```<code>error: (-215) src.type() == CV_8UC3 && dst.type() == CV_32SC1 in function cv::watershed
</code>```

wherein the 8bit 3 channel image is being attempted to be converted to a 32bit single channel image. How do I prevent this and yet work with the Distance Transform?

答:
In function cv2.watershed(img,markers) your input parameter img must have 3 channels.
Full working code:

```<code>#Load image in grayscale
img = cv2.imread('Results\Feb_16-0.jpg',0)

kernel = np.ones((1,1),np.uint8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
blur = cv2.GaussianBlur(opening,(1,1),0)
ret3,th4 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

# sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=1)
# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,3)

ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg,sure_fg)

ret, markers = cv2.connectedComponents(sure_fg)
markers = markers+1
markers[unknown==255] = 0
markers = markers.astype('int32')

#now load same image as color image
img = cv2.imread('Results\Feb_16-0.jpg',1)

markers = cv2.watershed(img,markers)
img[markers == -1] = [255,0,0]
</code>```

Body:
I am trying to apply the WaterShed algorithm to an image as per the tutorial: OpenCv WaterShed Docs . I have earlier applied Otsu's thresholding after Gaussian filtering and Morpholigical Transformations on a greyscale image to improve Image quality as per the code:

img = cv2.imread('Results\Feb_16-0.jpg',0)
kernel = np.ones((1,1),np.uint8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
blur = cv2.GaussianBlur(opening,(1,1),0)
ret3,th4 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

Applying the distance transform as the first stage of the watershed algorithm as per the code:

# sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=1)
# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,3)

creates the error:

error: (-215) src.type() == CV_8UC3 && dst.type() == CV_32SC1 in function cv::watershed

wherein the 8bit 3 channel image is being attempted to be converted to a 32bit single channel image. How do I prevent this and yet work with the Distance Transform?

Body:
In function cv2.watershed(img,markers) your input parameter img must have 3 channels.
Full working code:

#Load image in grayscale
img = cv2.imread('Results\Feb_16-0.jpg',0)

kernel = np.ones((1,1),np.uint8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
blur = cv2.GaussianBlur(opening,(1,1),0)
ret3,th4 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

# sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=1)
# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,3)

ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg,sure_fg)

ret, markers = cv2.connectedComponents(sure_fg)
markers = markers+1
markers[unknown==255] = 0
markers = markers.astype('int32')

#now load same image as color image
img = cv2.imread('Results\Feb_16-0.jpg',1)

markers = cv2.watershed(img,markers)
img[markers == -1] = [255,0,0]


问:
How to convert a string of 10 double-values into 10 separated doubles in c++
i have a question i didn´t find an answer to.. i don´t know if i missed something, but here i go:

I´m trying to convert a string that i read in from a file into 10 splitted doubles.

This is how i read in the last row in my file which contains values like this:

{1444.555;1553.9999; ....and so on}

What i´m trying to do is an Array out of this string which consists of these values like

```<code>    Array[0]=1444.555
    Array[1]=1553.999
</code>```

and so on..

My code-snippet till here looks like this:

```<code>    string line;
    string new1;
    ifstream myfile("example.txt");
    while (getline(myfile, line))
    {
        new1 = line;

    }
    cout << new1 << endl;
    myfile.close();
</code>```

So i need a conversion of the new1-string to an Array of doubles.

Alternatively you could tell me how to parse the content of a string like this one to a Matrix[i][j]? Actually this is what i´m trying to do.

答:
Thanks to your answers but i found a way to do it.

I used vectors now and changed the separator between the doubles to whitespaces. So my code looks like this now:

```<code> #include <vectors>
....
....
ifstream myfile("example.txt", std::ios::in);
    vector<double> scores;

    //check
    if (!myfile.is_open()) {
        std::cerr << "There was a problem opening the input file!\n";
        exit(1);
    }
    //store values
    double num = 0.0;

    while (myfile >> num) {
        scores.push_back(num);
    }

    // extract last line in my file to my Matrix
    for (i = 0; i <= x_max; i++) {

        Matrix[i][0] = scores[i + m_max * (y_max-1)];

        cout << Matrix[i][0] << endl;
    }
</code>```

Body:
i have a question i didn´t find an answer to.. i don´t know if i missed something, but here i go:

I´m trying to convert a string that i read in from a file into 10 splitted doubles.

This is how i read in the last row in my file which contains values like this:

{1444.555;1553.9999; ....and so on}

What i´m trying to do is an Array out of this string which consists of these values like

    Array[0]=1444.555
    Array[1]=1553.999

and so on..

My code-snippet till here looks like this:

    string line;
    string new1;
    ifstream myfile("example.txt");
    while (getline(myfile, line))
    {
        new1 = line;

    }
    cout << new1 << endl;
    myfile.close();

So i need a conversion of the new1-string to an Array of doubles.

Alternatively you could tell me how to parse the content of a string like this one to a Matrix[i][j]? Actually this is what i´m trying to do.

Body:
Thanks to your answers but i found a way to do it.

I used vectors now and changed the separator between the doubles to whitespaces. So my code looks like this now:

 #include <vectors>
....
....
ifstream myfile("example.txt", std::ios::in);
    vector<double> scores;

    //check
    if (!myfile.is_open()) {
        std::cerr << "There was a problem opening the input file!\n";
        exit(1);
    }
    //store values
    double num = 0.0;

    while (myfile >> num) {
        scores.push_back(num);
    }

    // extract last line in my file to my Matrix
    for (i = 0; i <= x_max; i++) {

        Matrix[i][0] = scores[i + m_max * (y_max-1)];

        cout << Matrix[i][0] << endl;
    }


问:
Python: UnicodeDecodeError: 'utf8'
I'm having problem to save accented letters. I'm using POSTGRESQL and Python 2.7

```<code>POSTGRESQL -  ENCODING = 'LATIN1'
</code>```

I already added this line but does not worked!

```<code>#!/usr/bin/python
# -*- coding: UTF-8 -*-
</code>```

More about error message:

```<code>UnicodeDecodeError: 'utf8' codec can't decode byte 0xed
</code>```

Please, any idea how to fix it?

@Edit:

```<code>cur = conn.cursor()
cur.execute("SELECT * FROM users")
rows = cur.fetchall()

obj_list = list()
for row in rows:
 ob = dict()
 ob['ID'] = row[0]
 ob['NAME'] = row[1]
 ob['CITY'] = row[2]
 ob['USERNAME'] = row[3]

 obj_list.append(ob)

# print obj_list
# sys.exit()
def add_object(ob, row):
 ws.cell(column=3, row=row).value = ob['ID']
 ws.cell(column=4, row=row).value = ob['NAME']
 ws.cell(column=6, row=row).value = ob['CITY']
 ws.cell(column=8, row=row).value = ob['USERNANE']
</code>```

This part of code is triggering the error. It's returning accent..

```<code>ob['CITY'] = row[2]
</code>```

答: First thing to check is whether your "accented letters" belong to LATIN1 set - for example, á does, but ś doesn't. If not, you really should use UTF8 encoding in PostgreSQL (it is probably safer anyway).</p>

Title: Python: UnicodeDecodeError: 'utf8'

Body:
I'm having problem to save accented letters. I'm using POSTGRESQL and Python 2.7

POSTGRESQL -  ENCODING = 'LATIN1'

I already added this line but does not worked!

#!/usr/bin/python
# -*- coding: UTF-8 -*-

More about error message:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xed

Please, any idea how to fix it?

@Edit:

cur = conn.cursor()
cur.execute("SELECT * FROM users")
rows = cur.fetchall()

obj_list = list()
for row in rows:
 ob = dict()
 ob['ID'] = row[0]
 ob['NAME'] = row[1]
 ob['CITY'] = row[2]
 ob['USERNAME'] = row[3]

 obj_list.append(ob)

# print obj_list
# sys.exit()
def add_object(ob, row):
 ws.cell(column=3, row=row).value = ob['ID']
 ws.cell(column=4, row=row).value = ob['NAME']
 ws.cell(column=6, row=row).value = ob['CITY']
 ws.cell(column=8, row=row).value = ob['USERNANE']

This part of code is triggering the error. It's returning accent..

ob['CITY'] = row[2]


问:
How to test if a c-string contains characters outside certain ascii range?
So, let say I have simple code below:

```<code>int main() {
    char string1[256]="TEST1";
    char string2[256]="TESTOK"; //Also could be "TEST OK"

    if(//string doesn't contain "A-Z" || doesn't contain "SPACE")
    {
        //do something
    }

    return 0;
}
</code>```

Where the if statement is, all I would want to do is have string1 go into the if statement, because it contains something other than ASCII characters A-Z or a SPACE. However, in both examples of string2, I would want them to bypass the if statement because it contains A-Z or may have a SPACE, which all would be ok and should mean the char string doesn't go into the if statement.

I can not find a simple way to do this with c, to test for this. I have considered just looping through all the characters and testing if the ASCII value is of a certain value range or equals 32 for the space. However, that seems overly complicated. Also, I purposely set the 256 larger than the amount of characters in the string, so I worry about NULL characters messing things up possibly too.

Anyways, is there a simple way to do a test like this in C? Thanks for any help.

答:
Use strspn() (or strcspn()), prototype in <string.h>

```<code>char okchar[] = "ABC...Z 0123456789";
if (strspn(input, okchar) == strlen(input)) /* ok */;
</code>```

Body:
So, let say I have simple code below:

int main() {
    char string1[256]="TEST1";
    char string2[256]="TESTOK"; //Also could be "TEST OK"

    if(//string doesn't contain "A-Z" || doesn't contain "SPACE")
    {
        //do something
    }

    return 0;
}

Where the if statement is, all I would want to do is have string1 go into the if statement, because it contains something other than ASCII characters A-Z or a SPACE. However, in both examples of string2, I would want them to bypass the if statement because it contains A-Z or may have a SPACE, which all would be ok and should mean the char string doesn't go into the if statement.

I can not find a simple way to do this with c, to test for this. I have considered just looping through all the characters and testing if the ASCII value is of a certain value range or equals 32 for the space. However, that seems overly complicated. Also, I purposely set the 256 larger than the amount of characters in the string, so I worry about NULL characters messing things up possibly too.

Anyways, is there a simple way to do a test like this in C? Thanks for any help.

Body:
Use strspn() (or strcspn()), prototype in <string.h>

char okchar[] = "ABC...Z 0123456789";
if (strspn(input, okchar) == strlen(input)) /* ok */;


问:
Low speed network with high risk of disconnection
I have some computers on a network, the network is somehow serial, I mean computers are connected to each other via radio transmitters and in a line, if a radio transmitter goes off or face some problems other computers are not accessible.
the architecture would be something like this:

RT = radio transmitters

Computer#1<-RT#1->Computer#2<-RT#2->Computer#3<-RT#3->....<-RT#(N-1)->Computer#N

Distances between computers are about 20 to 30 kilometers and network speed varies between 0 and 10Kbps. computers are running windows XP and a very high loaded program (2GB of ram, 90% CPU Usage) are always running on them, all computers IP addresses are known and static.

I'm going to write a program which is going to run on every computer and get commands or packages to run or install and update on that computer. because of the low speed network and high risk of disconnection sending data between computers should have resume capability. the question is how should I implement that? using .NET remoting or use simple network sockets and TCP? which one is better? feel free to explain your suggestion or approaches you think suites this solution.

答:
You could use a framework like NServiceBus that is based on messaging, and then abstract your programs from the connections themselves.

The system can allow "repeat until success" messaging with a buffer somewhere along the line, and you won't need to worry about too much low level stuff.

http://www.nservicebus.com/

I'm not sure if it allows large data transfer, but check it out for the commands


问:
Unable to download excel sheet from array using Laravel-Excel?
I have written code for exporting the data(which is from Query builder) and downloading that sheet immediately to user's browser. I am using Laravel-Excel package for this, but the csv file is not getting downloaded.

I want the csv file to be 'Tab' delimited like below:

```<code> Supplier     Campaign    Disposition
sup-value1   cam-value1    dis-value1
sup-value2   cam-value2    dis-value2
sup-value3   cam-value3    dis-value3
</code>```

My input as array is :

```<code>$results =
Array
(
[0] => Array
    (
        [Supplier] => Avikmithran
        [Campaign] => krisha
        [Disposition] => testing purpose
    )
[1] => Array
    (
        [Supplier] => Avikmithran
        [Campaign] => testscaseqwe
        [Disposition] => this is the disposition
    )
[2] => Array
    (
        [Supplier] => Avikmitra
        [Campaign] => KrishnaL
        [Disposition] => this is testing
    )
[3] => Array
    (
        [Supplier] => Sonali
        [Campaign] => starslab
        [Disposition] => this is the disposiiton
    )
)
</code>```

CSV file download code is:

```<code>Excel::create('Statistics', function($excel) use($results) {

            $excel->sheet('Statistics', function($sheet) use($results) {

                $sheet->with($results);

            });

})->export('csv');
</code>```

It is driving the nuts, I have wasted 2 days on this already. Can anyone please tell me what is my mistake? Thanks.

答:
You need to use the fromArray method and also pass $results by reference:

```<code>Excel::create('Statistics', function($excel) use(&$results)
{
    $excel->sheet('Statistics', function($sheet) use(&$results)
    {
        $sheet->fromArray($results);
    });

})->export('csv');
</code>```

Body:
I have written code for exporting the data(which is from Query builder) and downloading that sheet immediately to user's browser. I am using Laravel-Excel package for this, but the csv file is not getting downloaded.

I want the csv file to be 'Tab' delimited like below:

 Supplier     Campaign    Disposition
sup-value1   cam-value1    dis-value1
sup-value2   cam-value2    dis-value2
sup-value3   cam-value3    dis-value3

My input as array is :

$results =
Array
(
[0] => Array
    (
        [Supplier] => Avikmithran
        [Campaign] => krisha
        [Disposition] => testing purpose
    )
[1] => Array
    (
        [Supplier] => Avikmithran
        [Campaign] => testscaseqwe
        [Disposition] => this is the disposition
    )
[2] => Array
    (
        [Supplier] => Avikmitra
        [Campaign] => KrishnaL
        [Disposition] => this is testing
    )
[3] => Array
    (
        [Supplier] => Sonali
        [Campaign] => starslab
        [Disposition] => this is the disposiiton
    )
)

CSV file download code is:

Excel::create('Statistics', function($excel) use($results) {

            $excel->sheet('Statistics', function($sheet) use($results) {

                $sheet->with($results);

            });

})->export('csv');

It is driving the nuts, I have wasted 2 days on this already. Can anyone please tell me what is my mistake? Thanks.

Body:
You need to use the fromArray method and also pass $results by reference:

Excel::create('Statistics', function($excel) use(&$results)
{
    $excel->sheet('Statistics', function($sheet) use(&$results)
    {
        $sheet->fromArray($results);
    });

})->export('csv');


问:
find size of union of two sets?
Is there any way to find size of union of two sets.
I know can do this

```<code>vector < int > s3( s1.size() , s2.size() );
auto it=set_union( s1.begin() , s1.end() , s2.begin() ,s2.end(), s3.begin());
int size = it - s3.begin();
</code>```

print size

example

```<code>s1 = {2 4 5 6}   size 4

s2 = {1 4 5 9 10}  size 5

s3 = {1 2 4 5 6 9 10}  size 7

complexity of set_union is 2*(s1 size + s2 size)-1
</code>```

Is there any other method to get size of union of two sets faster method, I just need the size do not  want the values of new union set formed.
If you know a faster method please suggest.

答:
One obvious way is to perform the same iteration set_union does but instead of copying the elements, just bump up a counter. That leaves the time complexity unchanged but eshews space usage completely.

Theoretically, one could devise an OutputIterator that just counts the elements so that set_union algorithm could be reused. Whether that is worth the hassle of making your iterator quack exactly the way STL expects it to is a different question... Reimplementing set_union to do just counting might be easier.

Title: find size of union of two sets?

Body:
Is there any way to find size of union of two sets.
I know can do this

vector < int > s3( s1.size() , s2.size() );
auto it=set_union( s1.begin() , s1.end() , s2.begin() ,s2.end(), s3.begin());
int size = it - s3.begin();

print size

example

s1 = {2 4 5 6}   size 4

s2 = {1 4 5 9 10}  size 5

s3 = {1 2 4 5 6 9 10}  size 7

complexity of set_union is 2*(s1 size + s2 size)-1

Is there any other method to get size of union of two sets faster method, I just need the size do not  want the values of new union set formed.
If you know a faster method please suggest.


问:
Google play store can't upload apk
I can't find any reason why the store doesn't accept any apks on new apps and others, it every time return please upload another apk

1.0, app code 1 brand new app returns same error with 2 different dev accounts on 4 different vpn(Netherlands/germanmy/singapur..) and 2 different browsers?(opera/safari) also I have deleted cookies etc

my signin in that project is react native

```<code>  signingConfigs {
        release {
            storeFile file("key.jks")
            storePassword "dosa"
            keyAlias "dsa"
            keyPassword "dsa"
            v2SigningEnabled true
        }
    }
</code>```

答:
You will have to set

```<code> android:debuggable="false"
</code>```

in application tag of the manifest file. This is important for uploading your apk.
and if this already set properly and Google Playstore still rejects your APK, then modify your build.gradle

```<code>signingConfigs {
    debug {
       storeFile file("my-keystore-file.jks")
       storePassword "my-password"
       keyAlias "my-alias"
       keyPassword "my-password"
     }
 }
</code>```

This will set your own key for debugging.

If your problem still exists then I would suggest reading the documentation, you can read it here it's given properly.

Title: Google play store can't upload apk

Body:
I can't find any reason why the store doesn't accept any apks on new apps and others, it every time return please upload another apk

1.0, app code 1 brand new app returns same error with 2 different dev accounts on 4 different vpn(Netherlands/germanmy/singapur..) and 2 different browsers?(opera/safari) also I have deleted cookies etc

my signin in that project is react native

  signingConfigs {
        release {
            storeFile file("key.jks")
            storePassword "dosa"
            keyAlias "dsa"
            keyPassword "dsa"
            v2SigningEnabled true
        }
    }

Body:
You will have to set

 android:debuggable="false"

in application tag of the manifest file. This is important for uploading your apk.
and if this already set properly and Google Playstore still rejects your APK, then modify your build.gradle

signingConfigs {
    debug {
       storeFile file("my-keystore-file.jks")
       storePassword "my-password"
       keyAlias "my-alias"
       keyPassword "my-password"
     }
 }

This will set your own key for debugging.

If your problem still exists then I would suggest reading the documentation, you can read it here it's given properly.


问:
How to find a standard text within a SapScript or SmartForm?
I need to track down where within a large number of custom sapscripts and smartforms a specific standard text (SO10) is being used.

Apart from the equivalent of "check the code for each print script", I've not found a workable solution online. Any suggestions?

答:
What concerns SmartForms, you cannot. You cannot just find it like you want it.

Unfortunately, in such  ̶g̶o̶o̶d̶ ̶o̶l̶'̶  legacy technology as SmartForms everything is working legacy way, and standard texts are simply hard-coded. Yes, it looks awkward but they are really hard-coded, and these names are written out to SmartForm FM code every time it is re-generated.

So the only workaround here is to analyze the code.

Find all FMs for existing Smart Forms in system

There is a D010INC table containing all forms with their includes. The main point here is that all SmartForm FMs start with /1BCDWB/ prefix.

The main logic is in the includes, so we need to find correspondent INCLUDE for the target form.

Fetch SF include source code

It can be done in a several ways: via CL_RECA_RS_SERVICES class, via table REPOSRC, but the simplest way is ABAP statement READ REPORT.

Search SO10 text element name in the source code

Get Smart Form names for the FMs from hit list. It can be done via STXFADMI table, like in below snippet, but the more correct way is SSF_FUNCTION_MODULE_NAME FM

Bingo!

Sample solution could look like this:

```<code>DATA: lt_source     TYPE TABLE OF string,
      lt_smartforms TYPE TABLE OF d010inc,
      so_text       TYPE char50,
      fs_form       TYPE string,
      used_in       TYPE TABLE OF string,
      len           TYPE i.

* populating the list of SmartForm FMs
SELECT * FROM d010inc AS d
    INTO TABLE lt_smartforms
  WHERE master LIKE '/1BCDWB/%'
      AND include LIKE '/1BCDWB/%'.

so_text = '85XX_FOOTER'. " <- our SO10 text element name

LOOP AT lt_smartforms  ASSIGNING FIELD-SYMBOL(<fs_fm_name>).

* reading FM source code
  READ REPORT <fs_fm_name>-include INTO lt_source.
* checking if SO11 exists in source code
  FIND FIRST OCCURRENCE OF so_text  IN TABLE lt_source.

  IF sy-subrc = 0.
    len = strlen( <fs_fm_name>-include ) - 7.
* searching for SmartForm related to the target FM
    SELECT SINGLE formname
      FROM stxfadmi
      INTO fs_form
      WHERE fmnumb = <fs_fm_name>-include+len(4).

    IF sy-subrc = 0.
      APPEND fs_form TO used_in.
    ENDIF.
  ENDIF.

ENDLOOP.
</code>```

Yes, it is junky, not elegant and awkward, but who said it should be so?

ContentLicense: CC BY-SA 4.0

Body:
What concerns SmartForms, you cannot. You cannot just find it like you want it.

Unfortunately, in such  ̶g̶o̶o̶d̶ ̶o̶l̶'̶  legacy technology as SmartForms everything is working legacy way, and standard texts are simply hard-coded. Yes, it looks awkward but they are really hard-coded, and these names are written out to SmartForm FM code every time it is re-generated.

So the only workaround here is to analyze the code.

Find all FMs for existing Smart Forms in system

There is a D010INC table containing all forms with their includes. The main point here is that all SmartForm FMs start with /1BCDWB/ prefix.

The main logic is in the includes, so we need to find correspondent INCLUDE for the target form.

Fetch SF include source code

It can be done in a several ways: via CL_RECA_RS_SERVICES class, via table REPOSRC, but the simplest way is ABAP statement READ REPORT.

Search SO10 text element name in the source code

Get Smart Form names for the FMs from hit list. It can be done via STXFADMI table, like in below snippet, but the more correct way is SSF_FUNCTION_MODULE_NAME FM

Bingo!

Sample solution could look like this:

DATA: lt_source     TYPE TABLE OF string,
      lt_smartforms TYPE TABLE OF d010inc,
      so_text       TYPE char50,
      fs_form       TYPE string,
      used_in       TYPE TABLE OF string,
      len           TYPE i.

* populating the list of SmartForm FMs
SELECT * FROM d010inc AS d
    INTO TABLE lt_smartforms
  WHERE master LIKE '/1BCDWB/%'
      AND include LIKE '/1BCDWB/%'.

so_text = '85XX_FOOTER'. " <- our SO10 text element name

LOOP AT lt_smartforms  ASSIGNING FIELD-SYMBOL(<fs_fm_name>).

* reading FM source code
  READ REPORT <fs_fm_name>-include INTO lt_source.
* checking if SO11 exists in source code
  FIND FIRST OCCURRENCE OF so_text  IN TABLE lt_source.

  IF sy-subrc = 0.
    len = strlen( <fs_fm_name>-include ) - 7.
* searching for SmartForm related to the target FM
    SELECT SINGLE formname
      FROM stxfadmi
      INTO fs_form
      WHERE fmnumb = <fs_fm_name>-include+len(4).

    IF sy-subrc = 0.
      APPEND fs_form TO used_in.
    ENDIF.
  ENDIF.

ENDLOOP.

Yes, it is junky, not elegant and awkward, but who said it should be so?