问:
Cassandra gossipinfo severity explained
I was unable to find a good documentation/explanation as to what severity indicates in nodetool gossipinfo. was looking for a detailed explanation but could not find a suitable one.

答:
The severity is a value added to the latency in the dynamic snitch to determine which replica a coordinator will send the read's DATA and DIGEST requests to.

Its value would depend on the IO used in compaction and also it would try to read /proc/stat (same as the iostat utility) to get actual disk statistics as its weight. In post 3.10 versions of cassandra this is removed in https://issues.apache.org/jira/browse/CASSANDRA-11738. In pervious versions you can disable it by setting -Dcassandra.ignore_dynamic_snitch_severity in jvm options. The issue is that it weighting the io use the same as the latency. So if a node is GC thrashing and not doing much IO because of  it, it could end up being treated as the target of most reads even though its the worst possible node to send requests to.

Now you can still use JMX to set the value still (to 1) if you want to exclude it from being used for reads. A example use case is using nodetool disablebinary so application wont query it directly, then setting the severity to 1. That node would then only be queried by cluster if theres a CL.ALL request or a read repair. Its a way to take a node "offline" for maintenance from a read perspective but still allow it to get mutations so it doesn't fall behind.

Title: Cassandra gossipinfo severity explained


来源: stackexchange

问:
How to add an emoji font to Heroku and replace the dejavu defaults?
I'm trying to use emojione-apple.ttf from https://github.com/emojione/emojione/tree/master/extras/fonts on Heroku because the default font on Heroku (dejavu) doesn't have all the emoji.

I added the fonts on the ~/.fonts folder with this buildpack : https://github.com/GautierT/puppeteer-heroku-buildpack

When i render an HTML page to PDF with https://github.com/GoogleChrome/puppeteer it's seems that it's still dejavu fonts and not the emojione.

(Very low quality, weird "glasses" and "gear" emoji)

Thank you for your help.

答: I've used the android variant of emojione's font with degrees of success for browserless. I'm not sure what linux distro Heroku uses for their service, but you might have to consider an alternative provider if it's limited (Firebase functions and AWS Lambdas have similar constraints).</p>

ContentLicense: CC BY-SA 3.0


问:
Is there a query which selects columns from only one table which would give incorrect results if grouped by only the primary key of that table?
For example, a bookpub database contains the following tables (pseudocode):

```<code>book (key: isbn)
bookauthor (key:author_id, isbn)
author (key: author_id)
</code>```

The following query returns the number of books by each author:

```<code>select lastname, firstname, count(isbn)
from author
join bookauthor using (author_id)
group by lastname, firstname;
</code>```

However, the following query also produces identical results in MySQL without complaint:

```<code>select lastname, firstname, count(isbn)
from author
join bookauthor using (author_id)
group by author_id;
</code>```

So why shouldn't author_id be used instead of lastname, firstname?

I might add that the formal SQL spec contains the following:

```<code>All non-aggregate groups in a SELECT expression list or HAVING expression list must be included in the GROUP BY clause.
</code>```

Can somebody please interpret this? What is a "non-aggregate group"? Why not just say "columns"? Furthermore, what is an "expression list"? Does an expression in this case always evaluate to a column?

答:
In the group by clause you list fields and expressions whose values will partition your result set. For those groups you can calculate aggregate functions like count sum etc.
MySQL lets you select non aggregate expressions or fields, not present in the group by clause, but it's non standard SQL. The result will be non deterministic if those fields have more than one value for a group.

If you group by the primary key the result will be deterministic because there's only one row for each key.

Body:
For example, a bookpub database contains the following tables (pseudocode):

book (key: isbn)
bookauthor (key:author_id, isbn)
author (key: author_id)

The following query returns the number of books by each author:

select lastname, firstname, count(isbn)
from author
join bookauthor using (author_id)
group by lastname, firstname;

However, the following query also produces identical results in MySQL without complaint:

select lastname, firstname, count(isbn)
from author
join bookauthor using (author_id)
group by author_id;

So why shouldn't author_id be used instead of lastname, firstname?

I might add that the formal SQL spec contains the following:

All non-aggregate groups in a SELECT expression list or HAVING expression list must be included in the GROUP BY clause.

Can somebody please interpret this? What is a "non-aggregate group"? Why not just say "columns"? Furthermore, what is an "expression list"? Does an expression in this case always evaluate to a column?


问:
Passing by reference and value in Go to functions
I am a bit confused about passing by reference and value in Go.

I've seen this explained of the * in front of a type.

in front of a type name, means that the declared variable will store an address of another variable of that type (not a value of that
  type).

This just doesn't make sense to me.

In Java if I was passing a Database instance into a function I would do

```<code> databaseFunction(DatabaseType db) {
      // do something
}
</code>```

However in the go example I have it's passed like so.

```<code>func PutTasks(db *sql.DB) echo.HandlerFunc {

}
</code>```

Why do we need to have the asterisk in front of the type?

According to this cheat sheet, I found.

func PrintPerson(p *Person)   ONLY receives the pointer address
  (reference)

I don't understand why I would only want to send a pointer address as a parameter.

答:
The purpose of reference semantics is to allow a function to manipulate data outside its own scope. Compare:

```<code>func BrokenSwap(a int, b int) {
  a, b = b, a
}

func RealSwap(a *int, b *int) {
  *a, *b = *b, *a
}
</code>```

When you call BrokenSwap(x, y), there is no effect, because the function receives and manipulates a private copy of the data. By contrast, when you call RealSwap(&x, &y), you actually exchange the values of the caller's x and y. Taking the address of the variables explicitly at the call site informs the reader that those variables may be mutated.

Body:
I am a bit confused about passing by reference and value in Go.

I've seen this explained of the * in front of a type.

in front of a type name, means that the declared variable will store an address of another variable of that type (not a value of that
  type).

This just doesn't make sense to me.

In Java if I was passing a Database instance into a function I would do

 databaseFunction(DatabaseType db) {
      // do something
}

However in the go example I have it's passed like so.

func PutTasks(db *sql.DB) echo.HandlerFunc {

}

Why do we need to have the asterisk in front of the type?

According to this cheat sheet, I found.

func PrintPerson(p *Person)   ONLY receives the pointer address
  (reference)

I don't understand why I would only want to send a pointer address as a parameter.

Body:
The purpose of reference semantics is to allow a function to manipulate data outside its own scope. Compare:

func BrokenSwap(a int, b int) {
  a, b = b, a
}

func RealSwap(a *int, b *int) {
  *a, *b = *b, *a
}

When you call BrokenSwap(x, y), there is no effect, because the function receives and manipulates a private copy of the data. By contrast, when you call RealSwap(&x, &y), you actually exchange the values of the caller's x and y. Taking the address of the variables explicitly at the call site informs the reader that those variables may be mutated.


问:
Overriding an object prototype and disallowing any further overrides
I'm trying to write a library that intercepts all XMLHttpRequest calls and do something before eventually sending out the request, by overriding its prototype, for example:

```<code>var original_open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
    // my own override logic here before running the original function
    original_open.apply(this, arguments);
};
</code>```

The problem is, I want to guarantee that when someone uses this library, it is impossible for any other code on the web page to re-override this effect.

Because otherwise, the website using this library can dynamically load another piece of JS code which simply overrides the XMLHttpRequest.prototype.open again, and the whole purpose of this library is to disallow that.

I thought about freezing the prototype using Object.freeze() right after the override, so that no other code can override my own override. The code would look something like this:

```<code>var original_open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
    // my own override logic here before running the original function
    original_open.apply(this, arguments);
};
Object.freeze(XMLHttpRequest.prototype);
</code>```

My expectation is that, if another piece of code on the same page tries to re-override my own override, it will fail because the prototype has been frozen.

My question:

Is this the correct solution for this problem?

Is this truly secure? (No loopholes)?

答:
Do not freeze the prototype. This will lead to developer frustration, unexplainable bugs, and no one using your library. You have no way of knowing what other libraries will modify that method, and how they will do it, which leads to you coding for an endless amount of edge cases. Stick to a best practice, and assume that developers are making wise, compatible library selections.

Due to the nature of client side code, you're going to have to assume that other professional libraries will follow best practices. If 5 libraries all modify the prototypical method using the convention you used, all 5 libraries will work together.

For example, these two overrides simply work together:

var old1 = Document.prototype.querySelector;
Document.prototype.querySelector = function(...args) {
  console.log('Override 1');
  return old1.call(this, ...args);
};

var old2 = Document.prototype.querySelector;
Document.prototype.querySelector = function(...args) {
  console.log('Override 2');
  return old2.call(this, ...args);
};

let p = document.querySelector('body');

console.log(p);```

Body:
I'm trying to write a library that intercepts all XMLHttpRequest calls and do something before eventually sending out the request, by overriding its prototype, for example:

var original_open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
    // my own override logic here before running the original function
    original_open.apply(this, arguments);
};

The problem is, I want to guarantee that when someone uses this library, it is impossible for any other code on the web page to re-override this effect.

Because otherwise, the website using this library can dynamically load another piece of JS code which simply overrides the XMLHttpRequest.prototype.open again, and the whole purpose of this library is to disallow that.

I thought about freezing the prototype using Object.freeze() right after the override, so that no other code can override my own override. The code would look something like this:

var original_open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
    // my own override logic here before running the original function
    original_open.apply(this, arguments);
};
Object.freeze(XMLHttpRequest.prototype);

My expectation is that, if another piece of code on the same page tries to re-override my own override, it will fail because the prototype has been frozen.

My question:

Is this the correct solution for this problem?

Is this truly secure? (No loopholes)?


问:
Excel Formula with OFFSET Fails When Copied to Different Sheet
I've been struggling with this longer than I care to admit, but I have a fairly simple OFFSET function call which works on one sheet, but if I copy it to a different sheet it gives a #VALUE error.

On a sheet named "Deliverable" I have this formula in a cell:

```<code>=OFFSET(Deliverable!$B$72,1,0,,3)
</code>```

and it works fine.

If I go to any other sheet and use the same exact formula, or use it in the Name Manager, it gives a #VALUE error.

If I leave off the final parameter indicated the number of columns I want, it does work:

```<code>=OFFSET(Deliverable!$B$72,1,0)
</code>```

but of course isn't giving me the range I need.

Any idea what's going on with this?

I'm using Excel 2016 on Windows 7.

-- Updated Info --
In a nutshell, my spreadsheet has two cells which I'm using as dropdown lists, where the 2nd cell's list feeds off the selection in the first.  The data they are based on has this format:

```<code>OptionA     A     B     C     D
OptionB     A     B
OptionC     D     E     F
</code>```

So the first dropdown uses a simple Data Validation source pointing to the column with OptionA, OptionB, etc.  Once that's chosen, the second dropdown list should contain the appropriate options for the one selected.  So if OptionB is selected, then the 2nd dropdown list should show A and B.

When I initially wrote this, the data validation source was just a simple VLOOKUP entry, but the lists often had blanks since the number of options varies for each entry.  Wanting to fix it up a bit, I ended up with this formula:
    =OFFSET(Deliverable!B72,Deliverable!B87,0,1,COUNTA(OFFSET(Deliverable!B72,Deliverable!B87,0,1,5)))

There won't be any more than 5 options, and there are no empty cells in the middle of the data to filter out.

In one spreadsheet I have I used this as a named range definition, then specified the named range for the cells data validation source and it worked.  In this other spreadsheet however, it gave me the error described earlier.

However, it looks like when I enter the statement directly into the data validation source field and not in the name manager, it works as expected.

Am I taking the totally wrong approach?

答:
This sounds like an array equation. Try hitting Ctrl+Shift+Enter in the other sheets to validate it as an array equation.

Whenever you need to reference ranges instead of single cells, Excel needs to know that you are working with arrays.

Body:
I've been struggling with this longer than I care to admit, but I have a fairly simple OFFSET function call which works on one sheet, but if I copy it to a different sheet it gives a #VALUE error.

On a sheet named "Deliverable" I have this formula in a cell:

=OFFSET(Deliverable!$B$72,1,0,,3)

and it works fine.

If I go to any other sheet and use the same exact formula, or use it in the Name Manager, it gives a #VALUE error.

If I leave off the final parameter indicated the number of columns I want, it does work:

=OFFSET(Deliverable!$B$72,1,0)

but of course isn't giving me the range I need.

Any idea what's going on with this?

I'm using Excel 2016 on Windows 7.

-- Updated Info --
In a nutshell, my spreadsheet has two cells which I'm using as dropdown lists, where the 2nd cell's list feeds off the selection in the first.  The data they are based on has this format:

OptionA     A     B     C     D
OptionB     A     B
OptionC     D     E     F

So the first dropdown uses a simple Data Validation source pointing to the column with OptionA, OptionB, etc.  Once that's chosen, the second dropdown list should contain the appropriate options for the one selected.  So if OptionB is selected, then the 2nd dropdown list should show A and B.

When I initially wrote this, the data validation source was just a simple VLOOKUP entry, but the lists often had blanks since the number of options varies for each entry.  Wanting to fix it up a bit, I ended up with this formula:
    =OFFSET(Deliverable!B72,Deliverable!B87,0,1,COUNTA(OFFSET(Deliverable!B72,Deliverable!B87,0,1,5)))

There won't be any more than 5 options, and there are no empty cells in the middle of the data to filter out.

In one spreadsheet I have I used this as a named range definition, then specified the named range for the cells data validation source and it worked.  In this other spreadsheet however, it gave me the error described earlier.

However, it looks like when I enter the statement directly into the data validation source field and not in the name manager, it works as expected.

Am I taking the totally wrong approach?


问:
Installing a package (conda) results in ImportError: Library not loaded
I installed seaborn package through conda:

```<code>~user: conda install seaborn

The following NEW packages will be INSTALLED:
seaborn:     0.8-py27_0
The following packages will be UPDATED:
conda:       4.3.8-py27_0     --> 4.3.30-py27h407ed3a_0
matplotlib:  1.4.3-np19py27_2 --> 1.5.3-np111py27_1
statsmodels: 0.6.1-np19py27_0 --> 0.8.0-np111py27_0
</code>```

And it messed up my matplotlib installation, now when I run my python script, it raises an error when importing matplotlib:

```<code>ImportError: dlopen(/Users/.../anaconda/lib/python2.7/site-packages/matplotlib/_png.so, 2): Library not loaded: @rpath/libpng16.16.dylib
Referenced from: /Users/.../anaconda/lib/python2.7/site-packages/matplotlib/_png.so
Reason: Incompatible library version: _png.so requires version 39.0.0 or later, but libpng16.16.dylib provides version 34.0.0
</code>```

答:
Try this from your conda command prompt:

conda install -c anaconda seaborn

Body:
I installed seaborn package through conda:

~user: conda install seaborn

The following NEW packages will be INSTALLED:
seaborn:     0.8-py27_0
The following packages will be UPDATED:
conda:       4.3.8-py27_0     --> 4.3.30-py27h407ed3a_0
matplotlib:  1.4.3-np19py27_2 --> 1.5.3-np111py27_1
statsmodels: 0.6.1-np19py27_0 --> 0.8.0-np111py27_0

And it messed up my matplotlib installation, now when I run my python script, it raises an error when importing matplotlib:

ImportError: dlopen(/Users/.../anaconda/lib/python2.7/site-packages/matplotlib/_png.so, 2): Library not loaded: @rpath/libpng16.16.dylib
Referenced from: /Users/.../anaconda/lib/python2.7/site-packages/matplotlib/_png.so
Reason: Incompatible library version: _png.so requires version 39.0.0 or later, but libpng16.16.dylib provides version 34.0.0


问:
How to get console.log line numbers shown in Nodejs?
Got an old application, that prints out quite a lot of messages using console.log, but I just can not find in which files and lines console.log is called.

Is there a way to hook into the app and show file name and line numbers?

答:
Having full stack trace for each call is a bit noisy. I've just improved the @noppa's solution to print only the initiator:

```<code>['log', 'warn', 'error'].forEach((methodName) => {
  const originalMethod = console[methodName];
  console[methodName] = (...args) => {
    let initiator = 'unknown place';
    try {
      throw new Error();
    } catch (e) {
      if (typeof e.stack === 'string') {
        let isFirst = true;
        for (const line of e.stack.split('\n')) {
          const matches = line.match(/^\s+at\s+(.*)/);
          if (matches) {
            if (!isFirst) { // first line - current function
                            // second line - caller (what we are looking for)
              initiator = matches[1];
              break;
            }
            isFirst = false;
          }
        }
      }
    }
    originalMethod.apply(console, [...args, '\n', `  at ${initiator}`]);
  };
});
</code>```

It also patches other methods (useful for Nodejs, since warn and error don't come with a stack trace as in Chrome).

So your console would look something like:

Loading settings.json
   at fs.readdirSync.filter.forEach (.../settings.js:21:13)
Server is running on http://localhost:3000 or http://127.0.0.1:3000
   at Server.app.listen (.../index.js:67:11)
```

Body:
Having full stack trace for each call is a bit noisy. I've just improved the @noppa's solution to print only the initiator:

['log', 'warn', 'error'].forEach((methodName) => {
  const originalMethod = console[methodName];
  console[methodName] = (...args) => {
    let initiator = 'unknown place';
    try {
      throw new Error();
    } catch (e) {
      if (typeof e.stack === 'string') {
        let isFirst = true;
        for (const line of e.stack.split('\n')) {
          const matches = line.match(/^\s+at\s+(.*)/);
          if (matches) {
            if (!isFirst) { // first line - current function
                            // second line - caller (what we are looking for)
              initiator = matches[1];
              break;
            }
            isFirst = false;
          }
        }
      }
    }
    originalMethod.apply(console, [...args, '\n', `  at ${initiator}`]);
  };
});

It also patches other methods (useful for Nodejs, since warn and error don't come with a stack trace as in Chrome).

So your console would look something like:

Loading settings.json
   at fs.readdirSync.filter.forEach (.../settings.js:21:13)
Server is running on http://localhost:3000 or http://127.0.0.1:3000
   at Server.app.listen (.../index.js:67:11)


问:
javax.net.ssl.SSLException: Certificate doesn't match any of the subject alternative names
I recently added LetsEncrypt certificates to my server and my java applet is having problems connecting using TLS.

My applet uses Apache HttpClient.

My web server is Apache 2,4, and I have a few virtual hosts set up as subdomains of my main domain (foo.com - not my real domain name).

When I run my applet on the staging subdomain (e.g. it runs off https://staging.foo.com), I get the following error:

```<code>javax.net.ssl.SSLException: Certificate for <staging.foo.com> doesn't match any of the subject alternative names: [developer.foo.com]
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:165)
at org.apache.http.conn.ssl.BrowserCompatHostnameVerifier.verify(BrowserCompatHostnameVerifier.java:61)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:141)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:114)
at org.apache.http.conn.ssl.SSLSocketFactory.verifyHostname(SSLSocketFactory.java:580)
at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:554)
at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:412)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:179)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:328)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:612)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:447)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:884)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
...(cut)
at javax.swing.SwingWorker$1.call(SwingWorker.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at javax.swing.SwingWorker.run(SwingWorker.java:334)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>```

I have no idea what's going on.

First of all, I have no idea how Java knows that developer.foo.bar is one of my virtual hosts (although this virtual host is the first one, alphabetically, that has SSL turned on).

I've looked at the certificate detail for staging.foo.com, and the only name listed under the "Subject Alternative Name" field is staging.foo.com.

So where is it getting developer.foo.com from?

And how do I fix this problem?

I'm using Firefox on OS X El Capitan 10.11.6 with the following Java plugin version info:

```<code>Java Plug-in 11.102.2.14 x86_64
Using JRE version 1.8.0_102-b14 Java HotSpot(TM) 64-Bit Server VM
</code>```

This is the Apache conf file for staging.foo.com:

```<code><IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName staging.foo.com
    ServerAlias www.staging.foo.com

    # Turn on HTTP Strict Transport Security (HSTS). This tells the
    # client that it should only communicate with this site using
    # HTTPS. See
    # https://raymii.org/s/tutorials/HTTP_Strict_Transport_Security_for_Apache_NGINX_and_Lighttpd.html
    Header always set Strict-Transport-Security "max-age=31536000; includeSubdomains;"

    # The following is used to tunnel websocket requests to daphne, so
    # that Django Channels can do its thing
    ProxyPass "/ws/" "ws://localhost:8001/ws/"
    ProxyPassReverse "/ws/" "ws://localhost:8001/ws/"

    # The following is used during deployment. Every page request is
    # served from one static html file.
    RewriteEngine       on
    RewriteCond         /home/www-mm/staging.foo.com/apache/in_maintenance -f
    RewriteRule .*      /home/www-mm/staging.foo.com/static/maintenance/maintenance.html

    # Use Apache to serve protected (non-static) files. This is so that
    # Apache can deal with ranges
    XSendFile on
    XSendFilePath /home/www-mm/staging.foo.com/user_assets

    # Limit uploads - 200MB
    LimitRequestBody 209715200

    Alias /static/ /home/www-mm/staging.foo.com/serve_static/
    Alias /robots.txt /home/www-mm/staging.foo.com/apache/serve-at-root/robots.txt

    <Directory /home/www-mm/staging.foo.com/serve_static>
        AddOutputFilterByType DEFLATE text/html text/css text/javascript application/javascript application/json
        Order deny,allow
        Require all granted
    </Directory>

    # Videos uploaded via staff to home page should never cache,
    # because they can change at any time (and we don't know if the
    # URLs will change or not). Etags are used and only headers are
    # sent if the files in question aren't modified (we get a 304
    # back)
    <Directory /home/www-mm/staging.foo.com/serve_static/video>
        ExpiresActive On
        # Expire immediately
        ExpiresDefault A0
    </Directory>

    # The following ensures that the maintenance page is never cached.
    <Directory /home/www-mm/staging.foo.com/static/maintenance>
        ExpiresActive On
        # Expire immediately
        ExpiresDefault A0
        Require all granted
    </Directory>

    # Hide uncompressed code from prying eyes. Python needs access to this code for the css compressor
    <Directory /home/www-mm/staging.foo.com/serve_static/js/muso>
        <Files ~ "\.js$">
            Deny from all
        </Files>
        # Order deny,allow
        # Deny from all
    </Directory>

    # Hide uncompressed code from prying eyes. Python needs access to this code for the css compressor
    <DirectoryMatch "/home/www-mm/staging.foo.com/serve_static/js/dist/.*/muso">
        Order deny,allow
        Deny from all
    </DirectoryMatch>

    <Directory /home/www-mm/staging.foo.com/apache>
        <Files django.wsgi>
            Order deny,allow
            Require all granted
        </Files>
    </Directory>

    WSGIScriptAlias / /home/www-mm/staging.foo.com/apache/django.wsgi
    WSGIDaemonProcess staging.foo.com user=www-mm group=www-mm
    WSGIProcessGroup staging.foo.com

    ErrorLog /var/log/apache2/staging.foo.com-error.log
    CustomLog /var/log/apache2/staging.foo.com-access.log combined

    SSLCertificateFile /etc/letsencrypt/live/staging.foo.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/staging.foo.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>
</code>```

The SSL sections were added by certbot, the LetsEncrypt CLI tool.

I should add that accessing each of these subdomains in a modern browser (such as Chrome) is fine.

答:
I was getting the same error when I was using methods from org.apache.http.* for making my http requests. From your stack trace I assume that even you are using the same.

This error disappeared when I used java.net.HttpURLConnection and I was able to connect successfully.

```<code>import java.net.HttpURLConnection;

public static HttpURLConnection connectToWeb(String uri) {
    HttpURLConnection connection = null;
    try {
        URL url = new URL(uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return connection;
}
</code>```

Body:
I recently added LetsEncrypt certificates to my server and my java applet is having problems connecting using TLS.

My applet uses Apache HttpClient.

My web server is Apache 2,4, and I have a few virtual hosts set up as subdomains of my main domain (foo.com - not my real domain name).

When I run my applet on the staging subdomain (e.g. it runs off https://staging.foo.com), I get the following error:

javax.net.ssl.SSLException: Certificate for <staging.foo.com> doesn't match any of the subject alternative names: [developer.foo.com]
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:165)
at org.apache.http.conn.ssl.BrowserCompatHostnameVerifier.verify(BrowserCompatHostnameVerifier.java:61)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:141)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:114)
at org.apache.http.conn.ssl.SSLSocketFactory.verifyHostname(SSLSocketFactory.java:580)
at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:554)
at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:412)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:179)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:328)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:612)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:447)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:884)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
...(cut)
at javax.swing.SwingWorker$1.call(SwingWorker.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at javax.swing.SwingWorker.run(SwingWorker.java:334)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

I have no idea what's going on.

First of all, I have no idea how Java knows that developer.foo.bar is one of my virtual hosts (although this virtual host is the first one, alphabetically, that has SSL turned on).

I've looked at the certificate detail for staging.foo.com, and the only name listed under the "Subject Alternative Name" field is staging.foo.com.

So where is it getting developer.foo.com from?

And how do I fix this problem?

I'm using Firefox on OS X El Capitan 10.11.6 with the following Java plugin version info:

Java Plug-in 11.102.2.14 x86_64
Using JRE version 1.8.0_102-b14 Java HotSpot(TM) 64-Bit Server VM

This is the Apache conf file for staging.foo.com:

<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName staging.foo.com
    ServerAlias www.staging.foo.com

    # Turn on HTTP Strict Transport Security (HSTS). This tells the
    # client that it should only communicate with this site using
    # HTTPS. See
    # https://raymii.org/s/tutorials/HTTP_Strict_Transport_Security_for_Apache_NGINX_and_Lighttpd.html
    Header always set Strict-Transport-Security "max-age=31536000; includeSubdomains;"

    # The following is used to tunnel websocket requests to daphne, so
    # that Django Channels can do its thing
    ProxyPass "/ws/" "ws://localhost:8001/ws/"
    ProxyPassReverse "/ws/" "ws://localhost:8001/ws/"

    # The following is used during deployment. Every page request is
    # served from one static html file.
    RewriteEngine       on
    RewriteCond         /home/www-mm/staging.foo.com/apache/in_maintenance -f
    RewriteRule .*      /home/www-mm/staging.foo.com/static/maintenance/maintenance.html

    # Use Apache to serve protected (non-static) files. This is so that
    # Apache can deal with ranges
    XSendFile on
    XSendFilePath /home/www-mm/staging.foo.com/user_assets

    # Limit uploads - 200MB
    LimitRequestBody 209715200

    Alias /static/ /home/www-mm/staging.foo.com/serve_static/
    Alias /robots.txt /home/www-mm/staging.foo.com/apache/serve-at-root/robots.txt

    <Directory /home/www-mm/staging.foo.com/serve_static>
        AddOutputFilterByType DEFLATE text/html text/css text/javascript application/javascript application/json
        Order deny,allow
        Require all granted
    </Directory>

    # Videos uploaded via staff to home page should never cache,
    # because they can change at any time (and we don't know if the
    # URLs will change or not). Etags are used and only headers are
    # sent if the files in question aren't modified (we get a 304
    # back)
    <Directory /home/www-mm/staging.foo.com/serve_static/video>
        ExpiresActive On
        # Expire immediately
        ExpiresDefault A0
    </Directory>

    # The following ensures that the maintenance page is never cached.
    <Directory /home/www-mm/staging.foo.com/static/maintenance>
        ExpiresActive On
        # Expire immediately
        ExpiresDefault A0
        Require all granted
    </Directory>

    # Hide uncompressed code from prying eyes. Python needs access to this code for the css compressor
    <Directory /home/www-mm/staging.foo.com/serve_static/js/muso>
        <Files ~ "\.js$">
            Deny from all
        </Files>
        # Order deny,allow
        # Deny from all
    </Directory>

    # Hide uncompressed code from prying eyes. Python needs access to this code for the css compressor
    <DirectoryMatch "/home/www-mm/staging.foo.com/serve_static/js/dist/.*/muso">
        Order deny,allow
        Deny from all
    </DirectoryMatch>

    <Directory /home/www-mm/staging.foo.com/apache>
        <Files django.wsgi>
            Order deny,allow
            Require all granted
        </Files>
    </Directory>

    WSGIScriptAlias / /home/www-mm/staging.foo.com/apache/django.wsgi
    WSGIDaemonProcess staging.foo.com user=www-mm group=www-mm
    WSGIProcessGroup staging.foo.com

    ErrorLog /var/log/apache2/staging.foo.com-error.log
    CustomLog /var/log/apache2/staging.foo.com-access.log combined

    SSLCertificateFile /etc/letsencrypt/live/staging.foo.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/staging.foo.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>

The SSL sections were added by certbot, the LetsEncrypt CLI tool.

I should add that accessing each of these subdomains in a modern browser (such as Chrome) is fine.

Body:
I was getting the same error when I was using methods from org.apache.http.* for making my http requests. From your stack trace I assume that even you are using the same.

This error disappeared when I used java.net.HttpURLConnection and I was able to connect successfully.

import java.net.HttpURLConnection;

public static HttpURLConnection connectToWeb(String uri) {
    HttpURLConnection connection = null;
    try {
        URL url = new URL(uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return connection;
}


答:
First, Go technically has only pass-by-value. When passing a pointer to an object, you're passing a pointer by value, not passing an object by reference. The difference is subtle but occasionally relevant. For example, you can overwrite the pointer value which has no impact on the caller, as opposed to dereferencing it and overwriting the memory it points to.

```<code>// *int means you *must* pass a *int (pointer to int), NOT just an int!
func someFunc(x *int) {
    *x = 2 // Whatever variable caller passed in will now be 2
    y := 7
    x = &y // has no impact on the caller because we overwrote the pointer value!
}
</code>```

As to your question "Why do we need to have the asterisk in front of the type?": The asterisk indicates that the value is of type pointer to sql.DB, rather than a value of type sql.DB. These are not interchangeable!

Why would you want to send a pointer address? So that you can share the value between the caller of a function and the function body, with changes made inside the function reflected in the caller (for example, a pointer is the only way that a "setter" method can work on an object). While Java passes objects by reference always, Go passes by value always (i.e. it creates a copy of the value in the function); if you pass something to a function, and that function modifies that value, the caller won't see those changes. If you want changes to propogate outside the function, you must pass a pointer.

See also: the Go tour section on Pointers, the Go spec section on pointers, the Go spec section on the address operators

Title: Passing by reference and value in Go to functions

Body:
First, Go technically has only pass-by-value. When passing a pointer to an object, you're passing a pointer by value, not passing an object by reference. The difference is subtle but occasionally relevant. For example, you can overwrite the pointer value which has no impact on the caller, as opposed to dereferencing it and overwriting the memory it points to.

// *int means you *must* pass a *int (pointer to int), NOT just an int!
func someFunc(x *int) {
    *x = 2 // Whatever variable caller passed in will now be 2
    y := 7
    x = &y // has no impact on the caller because we overwrote the pointer value!
}

As to your question "Why do we need to have the asterisk in front of the type?": The asterisk indicates that the value is of type pointer to sql.DB, rather than a value of type sql.DB. These are not interchangeable!

Why would you want to send a pointer address? So that you can share the value between the caller of a function and the function body, with changes made inside the function reflected in the caller (for example, a pointer is the only way that a "setter" method can work on an object). While Java passes objects by reference always, Go passes by value always (i.e. it creates a copy of the value in the function); if you pass something to a function, and that function modifies that value, the caller won't see those changes. If you want changes to propogate outside the function, you must pass a pointer.

See also: the Go tour section on Pointers, the Go spec section on pointers, the Go spec section on the address operators


问:
What is the reason behind Pinterests use of bit-manipulation to create global IDs for sharding of their data on MySQL, and how does it work?
I am reading an article on how Pinterest managed to scale with MySQL, by sharding their data across multiple servers and databases within those servers.

The one part I am struggling with is how they create their global ID with bit-manipulation.

I understand how operators like & and | works. And I understand how left shift << and right shift >> work. But I don't understand how they all work together in this example.

From the article it says:

https://medium.com/@Pinterest_Engineering/sharding-pinterest-how-we-scaled-our-mysql-fleet-3f341e96ca6f

We created a 64 bit ID that contains the shard ID, the type of the
  containing data, and where this data is in the table (local ID). The
  shard ID is 16 bits, type ID is 10 bits and local ID is 36 bits. The
  savvy additionology experts out there will notice that only adds to 62
  bits. My past in compiler and chip design has taught me that reserve
  bits are worth their weight in gold. So we have two (set to zero).

So the shard ID is 16 bit, max 65536 - 1, type ID is 10 bit, max value 1024 - 1, and local ID is 36 bit, max value 68719476736 - 1.

What does he mean by the last statement?

My past in compiler and chip design has taught me that reserve bits
  are worth their weight in gold. So we have two (set to zero).

Next line shows us a way to get a 64 bit ID:

```<code>ID = (shard ID << 46) | (type ID << 36) | (local ID<<0)
</code>```

I am struggling to understand this. Why is the shard ID left shifted by 46? And why is the type ID left shifted by 36 and why is the local ID left shifted by 0, and why do we have an OR between all of these?

Next part is they where they are extracting the local ID, type ID and local ID from a global ID of 241294492511762325:

```<code>Shard ID = (241294492511762325 >> 46) & 0xFFFF = 3429
Type ID  = (241294492511762325 >> 36) & 0x3FF = 1
Local ID = (241294492511762325 >>  0) & 0xFFFFFFFFF = 7075733
</code>```

So here they do the opposite, they shift to the right, the same amount as the original left shift, I don't know why exactly shifting by those amounts but I can see the pattern. But now they are doing & with some hexadecimal numbers, and this I also do not understand.

I am trying to learn how to shard data manually in MySQL, and would be nice if I could understand the logic of why they are doing it like this, and how it works. I do understand how simple & and | and << and >> operators work, I learned it by reading this article:

https://code.tutsplus.com/articles/understanding-bitwise-operators--active-11301

But I don't understand how it all works together, and I don't understand why they use those shifting numbers, and why they do & with hexadecimal numbers at the end.

Would be awesome if I could understand this.

答:
Next line shows us a way to get a 64 bit ID:

```<code>ID = (shard ID << 46) | (type ID << 36) | (local ID<<0)
</code>```

I am struggling to understand this. Why is the shard ID left shifted by 46? And why is the type ID left shifted by 36 and why is the local ID left shifted by 0, and why do we have an OR between all of these?

So to reiterate:

local ID: 36 bits

type ID: 10 bits

shard ID: 16 bits

The full ID contains the IDs in order "shard, type, local". Since, local ID has 36 bits, you have to shift type ID by 36 bits. Type ID has 10 bits, so you have to shift type ID by an additional 10 bits (36 bits from local ID + 10 bits from type ID).

A bitwise OR (|) will set all the bits to 1 which are set to 1 in at least one of the operands.

For instance:

```<code>shard ID = 0b                         1011_1100_1001_0010
type ID  = 0b                                11_1010_0110
local ID = 0b1010_0100_1111_1101_1110_0011_1000_0000_0111
</code>```

if you shift those values by the specified bits, that gives you:

```<code>shard ID << 46 = 0b10_1111_0010_0100_1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000
type ID  << 36 = 0b                    11_1010_0110_0000_0000_0000_0000_0000_0000_0000_0000_0000
local ID <<  0 = 0b                                 1010_0100_1111_1101_1110_0011_1000_0000_0111
</code>```

and if you OR that, you get the result:

```<code>  0b10_1111_0010_0100_1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000
| 0b                    11_1010_0110_0000_0000_0000_0000_0000_0000_0000_0000_0000
| 0b                                 1010_0100_1111_1101_1110_0011_1000_0000_0111
= 0b10_1111_0010_0100_1011_1010_0110_1010_0100_1111_1101_1110_0011_1000_0000_0111
</code>```

To extract the IDs again, you have to apply bit masks with the bitwise AND (&) operator. It is the opposite of the OR operator: it will only set bits to 1 when both operands have that bit set. So to take your example:

Type ID  = (241294492511762325 >> 36) & 0x3FF = 1

Let's convert to binary first, so that dependencies of the operators and their operands become clear:

```<code>0b11_0101_1001_0100_0000_0001_0000_0000_0000_0110_1011_1111_0111_1001_0101
</code>```

Right shift by 36 bits:

```<code>0b                                             11_0101_1001_0100_0000_0001
</code>```

Apply bit mask (0x3FF = 0b11_1111_1111) of 10 bits:

```<code>  0b11_0101_1001_0100_0000_0001
& 0b               11_1111_1111
= 0b               00_0000_0001
</code>```

Which, in decimal notation, is also 1.

Body:
I am reading an article on how Pinterest managed to scale with MySQL, by sharding their data across multiple servers and databases within those servers.

The one part I am struggling with is how they create their global ID with bit-manipulation.

I understand how operators like & and | works. And I understand how left shift << and right shift >> work. But I don't understand how they all work together in this example.

From the article it says:

https://medium.com/@Pinterest_Engineering/sharding-pinterest-how-we-scaled-our-mysql-fleet-3f341e96ca6f

We created a 64 bit ID that contains the shard ID, the type of the
  containing data, and where this data is in the table (local ID). The
  shard ID is 16 bits, type ID is 10 bits and local ID is 36 bits. The
  savvy additionology experts out there will notice that only adds to 62
  bits. My past in compiler and chip design has taught me that reserve
  bits are worth their weight in gold. So we have two (set to zero).

So the shard ID is 16 bit, max 65536 - 1, type ID is 10 bit, max value 1024 - 1, and local ID is 36 bit, max value 68719476736 - 1.

What does he mean by the last statement?

My past in compiler and chip design has taught me that reserve bits
  are worth their weight in gold. So we have two (set to zero).

Next line shows us a way to get a 64 bit ID:

ID = (shard ID << 46) | (type ID << 36) | (local ID<<0)

I am struggling to understand this. Why is the shard ID left shifted by 46? And why is the type ID left shifted by 36 and why is the local ID left shifted by 0, and why do we have an OR between all of these?

Next part is they where they are extracting the local ID, type ID and local ID from a global ID of 241294492511762325:

Shard ID = (241294492511762325 >> 46) & 0xFFFF = 3429
Type ID  = (241294492511762325 >> 36) & 0x3FF = 1
Local ID = (241294492511762325 >>  0) & 0xFFFFFFFFF = 7075733

So here they do the opposite, they shift to the right, the same amount as the original left shift, I don't know why exactly shifting by those amounts but I can see the pattern. But now they are doing & with some hexadecimal numbers, and this I also do not understand.

I am trying to learn how to shard data manually in MySQL, and would be nice if I could understand the logic of why they are doing it like this, and how it works. I do understand how simple & and | and << and >> operators work, I learned it by reading this article:

https://code.tutsplus.com/articles/understanding-bitwise-operators--active-11301

But I don't understand how it all works together, and I don't understand why they use those shifting numbers, and why they do & with hexadecimal numbers at the end.

Would be awesome if I could understand this.

Body:
Next line shows us a way to get a 64 bit ID:

ID = (shard ID << 46) | (type ID << 36) | (local ID<<0)

I am struggling to understand this. Why is the shard ID left shifted by 46? And why is the type ID left shifted by 36 and why is the local ID left shifted by 0, and why do we have an OR between all of these?

So to reiterate:

local ID: 36 bits

type ID: 10 bits

shard ID: 16 bits

The full ID contains the IDs in order "shard, type, local". Since, local ID has 36 bits, you have to shift type ID by 36 bits. Type ID has 10 bits, so you have to shift type ID by an additional 10 bits (36 bits from local ID + 10 bits from type ID).

A bitwise OR (|) will set all the bits to 1 which are set to 1 in at least one of the operands.

For instance:

shard ID = 0b                         1011_1100_1001_0010
type ID  = 0b                                11_1010_0110
local ID = 0b1010_0100_1111_1101_1110_0011_1000_0000_0111

if you shift those values by the specified bits, that gives you:

shard ID << 46 = 0b10_1111_0010_0100_1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000
type ID  << 36 = 0b                    11_1010_0110_0000_0000_0000_0000_0000_0000_0000_0000_0000
local ID <<  0 = 0b                                 1010_0100_1111_1101_1110_0011_1000_0000_0111

and if you OR that, you get the result:

  0b10_1111_0010_0100_1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000
| 0b                    11_1010_0110_0000_0000_0000_0000_0000_0000_0000_0000_0000
| 0b                                 1010_0100_1111_1101_1110_0011_1000_0000_0111
= 0b10_1111_0010_0100_1011_1010_0110_1010_0100_1111_1101_1110_0011_1000_0000_0111

To extract the IDs again, you have to apply bit masks with the bitwise AND (&) operator. It is the opposite of the OR operator: it will only set bits to 1 when both operands have that bit set. So to take your example:

Type ID  = (241294492511762325 >> 36) & 0x3FF = 1

Let's convert to binary first, so that dependencies of the operators and their operands become clear:

0b11_0101_1001_0100_0000_0001_0000_0000_0000_0110_1011_1111_0111_1001_0101

Right shift by 36 bits:

0b                                             11_0101_1001_0100_0000_0001

Apply bit mask (0x3FF = 0b11_1111_1111) of 10 bits:

  0b11_0101_1001_0100_0000_0001
& 0b               11_1111_1111
= 0b               00_0000_0001

Which, in decimal notation, is also 1.


问:
VS 2013 Error-"No exports were found that match the constraint:"
I am using Visual Studio 2013 on Windows 10, Today I am getting error "No exports were found that match the constraint:"

I did following but still having same issue:

Solution giving in link
Error message "No exports were found that match the constraint contract name"

by removing/renaming "ComponentModelCache" folder, but still problem.

Run VS Repair, but still having same problem.

Finally, I Uninstalled Visual Studio 2013 and reinstalled, but still having
same problem.

Please suggest what do do now?

答: Apologies for contributing to an old "answered" thread. however for me, using Win 10, VS 2013. I had to remove the 'ComponentModelCache' folder from each version of VS that I had installed before this issue was resolved.</p>


问:
Get OS system and relative path to a folder in java
I write my test on my local Windows, and I create webdriver like this:

```<code>@BeforeMethod
@Parameters("browser")
public void setUp(String browser) throws Exception {
    if (browser.equalsIgnoreCase("chrome")) {
        System.out.println("Chrome test starting ...");
        System.setProperty("webdriver.chrome.driver", "src/test/resources/drivers/chromedriver_win.exe");
        webDriver = new ChromeDriver();
    }
    else {
        throw new Exception("Browser is not supported");
    }
</code>```

For the setProperty, I use a hard path to Chrome Driver, but I would like change the path to relative by checking the OS to use appropriate driver for Windows and Mac. Can someone give me a hint. Thanks

答:
The below code should work,</p>

```<code>if(type.equalsIgnoreCase("CHROME"))
{
  log.info("Executing Operating System = "+System.getProperty("os.name").toLowerCase());
  String osname =System.getProperty("os.name");
  if(osname.toLowerCase().contains("windows")) System.setProperty("webdriver.chrome.driver","src/test/resources/chromedriver.exe" );
  else if(osname.toLowerCase().contains("linux"))
  {
    String filepathtoset = System.getProperty("user.dir")+"/src/test/resources/chromedriver";
    System.setProperty("webdriver.chrome.driver",filepathtoset );
  }
  else System.setProperty("webdriver.chrome.driver","src/test/resources/chromedrivermac");
</code>```

Body:
I write my test on my local Windows, and I create webdriver like this:

@BeforeMethod
@Parameters("browser")
public void setUp(String browser) throws Exception {
    if (browser.equalsIgnoreCase("chrome")) {
        System.out.println("Chrome test starting ...");
        System.setProperty("webdriver.chrome.driver", "src/test/resources/drivers/chromedriver_win.exe");
        webDriver = new ChromeDriver();
    }
    else {
        throw new Exception("Browser is not supported");
    }

For the setProperty, I use a hard path to Chrome Driver, but I would like change the path to relative by checking the OS to use appropriate driver for Windows and Mac. Can someone give me a hint. Thanks

Body:
The below code should work,

if(type.equalsIgnoreCase("CHROME"))
{
  log.info("Executing Operating System = "+System.getProperty("os.name").toLowerCase());
  String osname =System.getProperty("os.name");
  if(osname.toLowerCase().contains("windows")) System.setProperty("webdriver.chrome.driver","src/test/resources/chromedriver.exe" );
  else if(osname.toLowerCase().contains("linux"))
  {
    String filepathtoset = System.getProperty("user.dir")+"/src/test/resources/chromedriver";
    System.setProperty("webdriver.chrome.driver",filepathtoset );
  }
  else System.setProperty("webdriver.chrome.driver","src/test/resources/chromedrivermac");


问:
How to install wkhtmltopdf with patched qt?
I want to convert html to pdf, and I use wkhtmltopdf.

But print size is smaller than I supposed.
I want to try --disable-smart-shrinking option but error occured like

```<code>$ xvfb-run -- /usr/bin/wkhtmltopdf --disable-smart-shrinking $INPUT $OUTPUT
The switch --disable-smart-shrinking, is not support using unpatched qt, and will be ignored.Loading page (1/2)
Printing pages (2/2)
Done
</code>```

Maybe I have to install wkhtmltopdf with patched qt, but I don't know how to install.

I saw following size, but gitorious.org doesn't work.

wkhtmltopdf patched qt?

My OS is Ubuntu14.04, and wkhtmltopdf version is 0.12.2.1

If you know other reason to be printed smaller, tell me please. thanks.

答:
Steps to Install Version 0.12.3 on Ubuntu 16.04.

Because I wasted way too much time tracking this down, here it is for others stumbling on this:

```<code>cd ~
wget https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.3/wkhtmltox-0.12.3_linux-generic-amd64.tar.xz
tar vxf wkhtmltox-0.12.3_linux-generic-amd64.tar.xz
cp wkhtmltox/bin/wk* /usr/local/bin/
</code>```

And you can confirm with:

```<code>$ wkhtmltopdf --version
wkhtmltopdf 0.12.3 (with patched qt)
</code>```

Btw, I chose 0.12.3 instead of 0.12.4 because of a strange page sizing issue, discussed here.

Body:
I want to convert html to pdf, and I use wkhtmltopdf.

But print size is smaller than I supposed.
I want to try --disable-smart-shrinking option but error occured like

$ xvfb-run -- /usr/bin/wkhtmltopdf --disable-smart-shrinking $INPUT $OUTPUT
The switch --disable-smart-shrinking, is not support using unpatched qt, and will be ignored.Loading page (1/2)
Printing pages (2/2)
Done

Maybe I have to install wkhtmltopdf with patched qt, but I don't know how to install.

I saw following size, but gitorious.org doesn't work.

wkhtmltopdf patched qt?

My OS is Ubuntu14.04, and wkhtmltopdf version is 0.12.2.1

If you know other reason to be printed smaller, tell me please. thanks.

Body:
Steps to Install Version 0.12.3 on Ubuntu 16.04.

Because I wasted way too much time tracking this down, here it is for others stumbling on this:

cd ~
wget https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.3/wkhtmltox-0.12.3_linux-generic-amd64.tar.xz
tar vxf wkhtmltox-0.12.3_linux-generic-amd64.tar.xz
cp wkhtmltox/bin/wk* /usr/local/bin/

And you can confirm with:

$ wkhtmltopdf --version
wkhtmltopdf 0.12.3 (with patched qt)

Btw, I chose 0.12.3 instead of 0.12.4 because of a strange page sizing issue, discussed here.


问:
Error in Zero inflated model (ziP) with bam
I am trying to use bam to run the following generalized additive model:

```<code>m <- bam(result ~ factor(city) + factor(year) + lnpopulation + s(lnincome), data=full_df, na.action=na.omit, family=ziP(theta = NULL, link = "identity",b=0))
</code>```

But getting the following error:

Error in bam(result :   extended families not supported by bam

The documentation for bam mentions the following:

This is a family object specifying the distribution and link to use in
  fitting etc. See glm and family for more details. The extended
  families listed in family.mgcv can also be used.

The family.mgcv does include ziP. What am I doing wrong? Any guidance will be appreciated. Thank you!

Re-posting from r-help.

Sincerely,

Milu

答:
The error message indicates that the version of mgcv you are using does not support these extended families that are otherwise supported by mgcv's gam() function.

Thankfully, the solution to your problem is trivial as Simon Wood has now implemented this feature (extended families within bam()) from version 1.8-19 as noted in the ChangeLog:

1.8-19

** bam() now accepts extended families (i.e. nb, tw, ocat etc)

The current version is 1.8-22 which fixes some bugs related to the functionality you are looking for, so make sure you update to the latest version.

Here is an example modified from ?ziP

```<code> ## function to simulated zip data

 rzip <- function(gamma,theta= c(-2,.3)) {
 ## generate zero inflated Poisson random variables, where
 ## lambda = exp(gamma), eta = theta[1] + exp(theta[2])*gamma
 ## and 1-p = exp(-exp(eta)).
   y <- gamma; n <- length(y)
   lambda <- exp(gamma)
   eta <- theta[1] + exp(theta[2])*gamma
   p <- 1- exp(-exp(eta))
   ind <- p > runif(n)
   y[!ind] <- 0
   np <- sum(ind)
   ## generate from zero truncated Poisson, given presence...
   y[ind] <- qpois(runif(np,dpois(0,lambda[ind]),1),lambda[ind])
   y
 }

 library('mgcv')

 ## Simulate some ziP data...
 set.seed(1);n<-400
 dat <- gamSim(1,n=n)
 dat$y <- rzip(dat$f/4-1)

 b <- bam(y ~ s(x0) + s(x1) + s(x2) + s(x3),
          family = ziP(), data = dat)
</code>```

Which gives for me, the following fitted model:

```<code>> summary(b)

Family: Zero inflated Poisson(-1.855,1.244)
Link function: identity

Formula:
y ~ s(x0) + s(x1) + s(x2) + s(x3)

Parametric coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.97426    0.04988   19.53   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Approximate significance of smooth terms:
        edf Ref.df      F p-value
s(x0) 2.396  2.989  2.336  0.0759 .
s(x1) 2.784  3.464 77.217  <2e-16 ***
s(x2) 7.397  8.317 59.364  <2e-16 ***
s(x3) 1.235  1.428  0.269  0.5888
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Deviance explained =   69%
fREML = 593.94  Scale est. = 1         n = 400
</code>```

Body:
I am trying to use bam to run the following generalized additive model:

m <- bam(result ~ factor(city) + factor(year) + lnpopulation + s(lnincome), data=full_df, na.action=na.omit, family=ziP(theta = NULL, link = "identity",b=0))

But getting the following error:

Error in bam(result :   extended families not supported by bam

The documentation for bam mentions the following:

This is a family object specifying the distribution and link to use in
  fitting etc. See glm and family for more details. The extended
  families listed in family.mgcv can also be used.

The family.mgcv does include ziP. What am I doing wrong? Any guidance will be appreciated. Thank you!

Re-posting from r-help.

Sincerely,

Milu

Body:
The error message indicates that the version of mgcv you are using does not support these extended families that are otherwise supported by mgcv's gam() function.

Thankfully, the solution to your problem is trivial as Simon Wood has now implemented this feature (extended families within bam()) from version 1.8-19 as noted in the ChangeLog:

1.8-19

** bam() now accepts extended families (i.e. nb, tw, ocat etc)

The current version is 1.8-22 which fixes some bugs related to the functionality you are looking for, so make sure you update to the latest version.

Here is an example modified from ?ziP

 ## function to simulated zip data

 rzip <- function(gamma,theta= c(-2,.3)) {
 ## generate zero inflated Poisson random variables, where
 ## lambda = exp(gamma), eta = theta[1] + exp(theta[2])*gamma
 ## and 1-p = exp(-exp(eta)).
   y <- gamma; n <- length(y)
   lambda <- exp(gamma)
   eta <- theta[1] + exp(theta[2])*gamma
   p <- 1- exp(-exp(eta))
   ind <- p > runif(n)
   y[!ind] <- 0
   np <- sum(ind)
   ## generate from zero truncated Poisson, given presence...
   y[ind] <- qpois(runif(np,dpois(0,lambda[ind]),1),lambda[ind])
   y
 }

 library('mgcv')

 ## Simulate some ziP data...
 set.seed(1);n<-400
 dat <- gamSim(1,n=n)
 dat$y <- rzip(dat$f/4-1)

 b <- bam(y ~ s(x0) + s(x1) + s(x2) + s(x3),
          family = ziP(), data = dat)

Which gives for me, the following fitted model:

> summary(b)

Family: Zero inflated Poisson(-1.855,1.244)
Link function: identity

Formula:
y ~ s(x0) + s(x1) + s(x2) + s(x3)

Parametric coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.97426    0.04988   19.53   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Approximate significance of smooth terms:
        edf Ref.df      F p-value
s(x0) 2.396  2.989  2.336  0.0759 .
s(x1) 2.784  3.464 77.217  <2e-16 ***
s(x2) 7.397  8.317 59.364  <2e-16 ***
s(x3) 1.235  1.428  0.269  0.5888
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Deviance explained =   69%
fREML = 593.94  Scale est. = 1         n = 400


问:
How to search by element value in the list of Redis cache?
We are using the redis cache and below the sample type of data we are storing

```<code>LLPUSH mylist "abc" "xyx" "awe" "wwqw"
</code>```

Now I am want to search in the redis from Spring project. For example my Spring project class receives one element from some external client "abc". How can search the Redis list by value? Something like below:

```<code>ListOperations<String, Object> listOperations = redisTemplate.opsForList();

listOperations.get(key,"abc"); // returns abc
</code>```

Or at least I want confirmation that this element is present in the list of Redis cache:

```<code>listOperations.contains(key, "abc"); // returns either true or false, based on the value presence
</code>```

Can someone please suggest of this type of client lib is present for Redis from Java side and that we can use in the Spring boot project?

答:
Redis lists are implemented as linked lists.

Hence, you will either have to get all elements of the list using LRANGE and iterate to find a particular element.

If the list does not contain multiple entries and the order is not
relevant, we can use LREM to remove the particular element and if
there is a difference in list size, the element exists. Later, the
removed element can be re-inserted if exists.

```<code>Long initialSize = redisTemplate.opsForList().size(key);
redisTemplate.opsForList().remove(key,0, value);
Long finalSize = redisTemplate.opsForList().size(key);
if(finalSize - initialSize > 0){
    redisTemplate.opsForList().rightPush(key,value);
    return true;     //Element exists
}
return false;    //Does not exist
</code>```

Consider making the operations atomic.

You can get the other spring redis list operations from here.

ContentLicense: CC BY-SA 4.0

Body:
We are using the redis cache and below the sample type of data we are storing

LLPUSH mylist "abc" "xyx" "awe" "wwqw"

Now I am want to search in the redis from Spring project. For example my Spring project class receives one element from some external client "abc". How can search the Redis list by value? Something like below:

ListOperations<String, Object> listOperations = redisTemplate.opsForList();

listOperations.get(key,"abc"); // returns abc

Or at least I want confirmation that this element is present in the list of Redis cache:

listOperations.contains(key, "abc"); // returns either true or false, based on the value presence

Can someone please suggest of this type of client lib is present for Redis from Java side and that we can use in the Spring boot project?

Body:
Redis lists are implemented as linked lists.

Hence, you will either have to get all elements of the list using LRANGE and iterate to find a particular element.

If the list does not contain multiple entries and the order is not
relevant, we can use LREM to remove the particular element and if
there is a difference in list size, the element exists. Later, the
removed element can be re-inserted if exists.

Long initialSize = redisTemplate.opsForList().size(key);
redisTemplate.opsForList().remove(key,0, value);
Long finalSize = redisTemplate.opsForList().size(key);
if(finalSize - initialSize > 0){
    redisTemplate.opsForList().rightPush(key,value);
    return true;     //Element exists
}
return false;    //Does not exist

Consider making the operations atomic.

You can get the other spring redis list operations from here.


问:
constexpr and virtual
I've been thinking why constexr and virtual are mutually exclusive, and someone added:

... constexpr is all about execution at compile time; if we're executing the function at compile time, we obviously know the type of data upon which it's acting at compile time as well, so late binding clearly isn't relevant.

However, it's possible that the dynamic type is not identical to the static type even in compile-time, and there might be cases where the dynamic type is needed:

```<code>class A {
public:
    /* virtual */ constexpr int foo() {
        return 1;
    }
};

class B : public A {
public:
    constexpr int foo() {
        return 2;
    }
};

constexpr int foo(A &a) {
    // The static type is fixed here.
    // What if we want to call B::foo() ?
    return a.foo();
}

int main() {
    B b;
    constexpr int c = foo(b);
    return 0;
}
</code>```

That is, my question is

what's the (possible) rationale behind the standard prohibiting the combination of the two?

答:
Indeed, it is possible for compilers to know at compile time what is the dynamic type of a constant expression. This is a possibility, that is some time used by optimizer to devirtualize calls at compile time.

But the c++ language evolution take also in consideration how difficult it is to implement it in compilers. If such a consideration were not taken, then the c++ standard will be too far from the c++ coded so that it would be unusefull.

Maybe, it has been evaluated that keeping trac of the static type of every reference during constant expression evaluation would be too expensive to implement. This is where reality hurts!

Title: constexpr and virtual

Body:
I've been thinking why constexr and virtual are mutually exclusive, and someone added:

... constexpr is all about execution at compile time; if we're executing the function at compile time, we obviously know the type of data upon which it's acting at compile time as well, so late binding clearly isn't relevant.

However, it's possible that the dynamic type is not identical to the static type even in compile-time, and there might be cases where the dynamic type is needed:

class A {
public:
    /* virtual */ constexpr int foo() {
        return 1;
    }
};

class B : public A {
public:
    constexpr int foo() {
        return 2;
    }
};

constexpr int foo(A &a) {
    // The static type is fixed here.
    // What if we want to call B::foo() ?
    return a.foo();
}

int main() {
    B b;
    constexpr int c = foo(b);
    return 0;
}

That is, my question is

what's the (possible) rationale behind the standard prohibiting the combination of the two?


问:
Change Woocommerce Order Status based on Shipping Method
The idea here is that when an order comes in with an "express delivery" as Shipping Method, the order status is updated to On-Hold.

As there I have some different "express delivery" Shipping Method rates I thought that by using stristr() to see if the word 'express' appears anywhere in the formatted shipping method title. But I seem to be missing something as I don't get anything.

How can I check if the Order shipping method is an "express delivery" to be able to update the order status?

Here is the code that I have:

```<code>add_action( 'woocommerce_thankyou', 'express_orders_4865', 10, 1 );
function express_orders_4865( $order_id ) {
    global $woocommerce;

    $order = new WC_Order( $order_id );

    $shipping_method = $order->get_shipping_method();

    if (stristr($shipping_method, 'express') === TRUE) {
        $order->update_status('on-hold');
    } else {
        return;
    }
}
</code>```

EDIT-----------------------------------------------------------

For anyone using Woocommerce Table Rate Shipping the get_method_id returns the table rate id so i used get_method_title instead as below, if there is a better way please comment...

```<code>add_action( 'woocommerce_thankyou', 'express_shipping_update_order_status', 10, 1 );
function express_shipping_update_order_status( $order_id ) {
    if ( ! $order_id ) return;

    $search = 'Express'; // The needle to search in the shipping method ID

    // Get an instance of the WC_Order object
    $order = wc_get_order( $order_id );

    // Get the WC_Order_Item_Shipping object data
    foreach($order->get_shipping_methods() as $shipping_item ){
        // When "express delivery" method is used, we change the order to "on-hold" status

        if( strpos( $shipping_item->get_method_title(), $search ) !== false ){
            $order->update_status('on-hold');
            break;
        }
    }
}
</code>```

答:
I prefer to use the faster and less memory intensive function strpos() instead as the shipping method ID is alway in lowercase (like a kind of slug).

So is better the get the WC_Order_Item_Shipping object data for this case, using the available methods.

So the code should be:

```<code>add_action( 'woocommerce_thankyou', 'express_shipping_update_order_status', 10, 1 );
function express_shipping_update_order_status( $order_id ) {
    if ( ! $order_id ) return;

    $search = 'express'; // The needle to search in the shipping method ID

    // Get an instance of the WC_Order object
    $order = wc_get_order( $order_id );

    // Get the WC_Order_Item_Shipping object data
    foreach($order->get_shipping_methods() as $shipping_item ){
        // When "express delivery" method is used, we change the order to "on-hold" status
        if( strpos( $shipping_item->get_method_title(), $search ) !== false && ! $order->has_status('on-hold')){
            $order->update_status('on-hold');
            break;
        }
    }
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works…

Body:
The idea here is that when an order comes in with an "express delivery" as Shipping Method, the order status is updated to On-Hold.

As there I have some different "express delivery" Shipping Method rates I thought that by using stristr() to see if the word 'express' appears anywhere in the formatted shipping method title. But I seem to be missing something as I don't get anything.

How can I check if the Order shipping method is an "express delivery" to be able to update the order status?

Here is the code that I have:

add_action( 'woocommerce_thankyou', 'express_orders_4865', 10, 1 );
function express_orders_4865( $order_id ) {
    global $woocommerce;

    $order = new WC_Order( $order_id );

    $shipping_method = $order->get_shipping_method();

    if (stristr($shipping_method, 'express') === TRUE) {
        $order->update_status('on-hold');
    } else {
        return;
    }
}

EDIT-----------------------------------------------------------

For anyone using Woocommerce Table Rate Shipping the get_method_id returns the table rate id so i used get_method_title instead as below, if there is a better way please comment...

add_action( 'woocommerce_thankyou', 'express_shipping_update_order_status', 10, 1 );
function express_shipping_update_order_status( $order_id ) {
    if ( ! $order_id ) return;

    $search = 'Express'; // The needle to search in the shipping method ID

    // Get an instance of the WC_Order object
    $order = wc_get_order( $order_id );

    // Get the WC_Order_Item_Shipping object data
    foreach($order->get_shipping_methods() as $shipping_item ){
        // When "express delivery" method is used, we change the order to "on-hold" status

        if( strpos( $shipping_item->get_method_title(), $search ) !== false ){
            $order->update_status('on-hold');
            break;
        }
    }
}

Body:
I prefer to use the faster and less memory intensive function strpos() instead as the shipping method ID is alway in lowercase (like a kind of slug).

So is better the get the WC_Order_Item_Shipping object data for this case, using the available methods.

So the code should be:

add_action( 'woocommerce_thankyou', 'express_shipping_update_order_status', 10, 1 );
function express_shipping_update_order_status( $order_id ) {
    if ( ! $order_id ) return;

    $search = 'express'; // The needle to search in the shipping method ID

    // Get an instance of the WC_Order object
    $order = wc_get_order( $order_id );

    // Get the WC_Order_Item_Shipping object data
    foreach($order->get_shipping_methods() as $shipping_item ){
        // When "express delivery" method is used, we change the order to "on-hold" status
        if( strpos( $shipping_item->get_method_title(), $search ) !== false && ! $order->has_status('on-hold')){
            $order->update_status('on-hold');
            break;
        }
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works…


问:
Error when using Requests with python 3.5 recursively (GooglePlaces API)
I have been having a problem where I try to send a get request and if there is a next page token in the result it will then take that link and execute another request recursively until there is no next page token in the result.
The first request works fine but when there is a next page token in the response and it tries to execute the new request the result is an Invalid ReSponse but if I take the link that was given from the result and use it in postman or on my browser everything is fine.
I'm assuming it has something to requests running on different threads at the same time.

The second response from request using Python:

```<code>{'html_attributions': [], 'status': 'INVALID_REQUEST', 'results': []}
</code>```

Here is what I have:

```<code>import requests

def getPlaces(location,radius,type, APIKEY):

    url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+location+"&radius="+radius+"&type="+type+"&key="+APIKEY

    print('Getting results for type ' + type + '...')

    r = requests.get(url)

    response = r.json()

    results = []

    if response['status'] == 'ZERO_RESULTS':
        print("Did not find results for the type "+type)
    else:
        print("Results for type "+type)

        for result in response['results']:
            results.append(result)
            print(result)
    print('Printing results')
    print(results)

    if 'next_page_token' in response:
        print("There is a next page")
        page_token = response['next_page_token']
        print(page_token)
        next_results = getNextPlace(page_token,APIKEY)
        print(next_results)
        results.append(next_results)

    return results

    # Get the rest of the results

def getNextPlace(page_token,APIKEY):

    print('...')

    next_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='+location+'&radius='+radius+'&type='+type+'&pagetoken=' + page_token + '&key=' + APIKEY

    print(next_url)
    r = requests.get(next_url)
    response = r.json()
    results = []
    print(response)

    if response['status'] == 'ZERO_RESULTS':
        print("Did not find results")
    elif response['status'] == 'INVALID_REQUEST':
        print('Invalid response')
    else:
        for next_result in response['results']:
             results.append(next_result)
             print(next_result)

    if 'next_page_token' in response:
        new_page_token = response['next_page_token']
        getNext = getNextPlace(new_page_token,APIKEY)
        results.append(getNext)

    return results
</code>```

答:
What you are trying to do can be seen in one function like:</p>

```<code>def getPlaces(location,radius,API,i,type):
    url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+location+"&radius="+radius+"&key="+API+"&types="+type
    r = requests.get(url)
    response = r.json()
    results = []
    for result in response['results']:
        results.append(result)
    l=[]
    while True:
        if 'next_page_token' in response:
            page_token = response['next_page_token']
            l.append(page_token)
            next_url = url+'&pagetoken='+l[i]
            i=i+1
            time.sleep(3)
            r = requests.get(next_url)
            response = r.json()
            for next_result in response['results']:
                results.append(next_result)
        else:
            break
    return results
</code>```

Body:
I have been having a problem where I try to send a get request and if there is a next page token in the result it will then take that link and execute another request recursively until there is no next page token in the result.
The first request works fine but when there is a next page token in the response and it tries to execute the new request the result is an Invalid ReSponse but if I take the link that was given from the result and use it in postman or on my browser everything is fine.
I'm assuming it has something to requests running on different threads at the same time.

The second response from request using Python:

{'html_attributions': [], 'status': 'INVALID_REQUEST', 'results': []}

Here is what I have:

import requests

def getPlaces(location,radius,type, APIKEY):

    url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+location+"&radius="+radius+"&type="+type+"&key="+APIKEY

    print('Getting results for type ' + type + '...')

    r = requests.get(url)

    response = r.json()

    results = []

    if response['status'] == 'ZERO_RESULTS':
        print("Did not find results for the type "+type)
    else:
        print("Results for type "+type)

        for result in response['results']:
            results.append(result)
            print(result)
    print('Printing results')
    print(results)

    if 'next_page_token' in response:
        print("There is a next page")
        page_token = response['next_page_token']
        print(page_token)
        next_results = getNextPlace(page_token,APIKEY)
        print(next_results)
        results.append(next_results)

    return results

    # Get the rest of the results

def getNextPlace(page_token,APIKEY):

    print('...')

    next_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='+location+'&radius='+radius+'&type='+type+'&pagetoken=' + page_token + '&key=' + APIKEY

    print(next_url)
    r = requests.get(next_url)
    response = r.json()
    results = []
    print(response)

    if response['status'] == 'ZERO_RESULTS':
        print("Did not find results")
    elif response['status'] == 'INVALID_REQUEST':
        print('Invalid response')
    else:
        for next_result in response['results']:
             results.append(next_result)
             print(next_result)

    if 'next_page_token' in response:
        new_page_token = response['next_page_token']
        getNext = getNextPlace(new_page_token,APIKEY)
        results.append(getNext)

    return results

Body:
What you are trying to do can be seen in one function like:

def getPlaces(location,radius,API,i,type):
    url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+location+"&radius="+radius+"&key="+API+"&types="+type
    r = requests.get(url)
    response = r.json()
    results = []
    for result in response['results']:
        results.append(result)
    l=[]
    while True:
        if 'next_page_token' in response:
            page_token = response['next_page_token']
            l.append(page_token)
            next_url = url+'&pagetoken='+l[i]
            i=i+1
            time.sleep(3)
            r = requests.get(next_url)
            response = r.json()
            for next_result in response['results']:
                results.append(next_result)
        else:
            break
    return results


问:
What is the correct way to use classes in CSS?
I see people creating classes for each object, for example:

.content-wrapper {
  display: flex;
  justify-content: center;
  color: white;
}

.images-wrapper {
  display: flex;
  justify-content: center;
  border: 1px solid white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content-wrapper"></div>
<div class="images-wrapper"></div></code>```

But also, I see people creating classes by attributes, as for example in Bootstrap:

.centered-content {
  display: flex;
  justify-content: center;
}

.content-wrapper {
  color: blue;
}

.images-wrapper {
  border: 2px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="centered-content content-wrapper"></div>
<div class="centered-content images-wrapper"></div></code>```

答:
when you have style that's repeated in your html you maybe need create one class for all DOM thats use this style.

For example

```<code><style>
   .box1{
         width: 300px;
         background-color: blue;
   }
   .subbox2{
         width: 30px;
         background-color: green;
   }
  .center{
         margin: auto;
         position: absolute;
  }
</style>

<div class="center box1">
  <div class= "center subbox2"></div>
</div>
</code>```

Body:
I see people creating classes for each object, for example:

.content-wrapper {
  display: flex;
  justify-content: center;
  color: white;
}

.images-wrapper {
  display: flex;
  justify-content: center;
  border: 1px solid white;
}

But also, I see people creating classes by attributes, as for example in Bootstrap:

.centered-content {
  display: flex;
  justify-content: center;
}

.content-wrapper {
  color: blue;
}

.images-wrapper {
  border: 2px solid black;
}

Body:
when you have style that's repeated in your html you maybe need create one class for all DOM thats use this style.

For example

<style>
   .box1{
         width: 300px;
         background-color: blue;
   }
   .subbox2{
         width: 30px;
         background-color: green;
   }
  .center{
         margin: auto;
         position: absolute;
  }
</style>

<div class="center box1">
  <div class= "center subbox2"></div>
</div>


问:
How to avoid segfault after calling deleteLater on pointer?
I have a GraphicsScene:public QGraphicsScene inherited class with a single QGraphicsView looking at it and QTimer, ticking to call function

```<code>void GraphicsScene::adv()
{
if (actor)
    views().at(0)->ensureVisible(actor,200,100);
advance();
}
</code>```

advance() is an overriden method which is send to all QGraphicsItem objects on scene. The point of this function - I want to make sure actor is always visible.
actor is a unit:public QGraphicsPixmapItem object on GraphicsScene.

At some point in actor method I call deleteLater().

The next timer tick I receive SEGFAULT at views().at(0)->ensureVisible(actor,200,100); line

I wonder, why if (actor) passes as true after deleteLater() and what is the correct condition should I use?

答:
I have an object being asynchronically deleted by deleteLater()
  and wonder if there is a way to prevent accessing it from other
  objects?

Yes, there is a way to tell programmatically whether or not the object was already deleted by using QPointer<MyQObject> as described. But that way is somewhat slow and your application code should rather have better logic to avoid that. Like, before calling deleteLater your code removes the reference for that object from, say, views() and your code should check for the view still there.

Body:
I have a GraphicsScene:public QGraphicsScene inherited class with a single QGraphicsView looking at it and QTimer, ticking to call function

void GraphicsScene::adv()
{
if (actor)
    views().at(0)->ensureVisible(actor,200,100);
advance();
}

advance() is an overriden method which is send to all QGraphicsItem objects on scene. The point of this function - I want to make sure actor is always visible.
actor is a unit:public QGraphicsPixmapItem object on GraphicsScene.

At some point in actor method I call deleteLater().

The next timer tick I receive SEGFAULT at views().at(0)->ensureVisible(actor,200,100); line

I wonder, why if (actor) passes as true after deleteLater() and what is the correct condition should I use?


问:
How to merge instance with a namespace in a declaration file?
How can I create a .d.ts file that represents the following JavaScript API?

Loader is a class which is not exported globally

loader is exported globally, and is an instance of Loader

loader.Loader is the Loader class itself

Loader has a static method create, which creates an instance of Loader

So essentially loader behaves like a namespace that includes the class Loader, but is also a instance of Loader. The following doesn't work, because TypeScript won't merge a namespace with a value:

declare namespace loader {
    class Loader {
        id: number;
        name: string;
        load(url: string): any;

        static create(name: string, parent?: Loader): Loader;
    }
}

// This doesn't work, because a namespace cannot be merged with a value:
declare const loader: loader.Loader;
```

<p>Using this API from JavaScript looks like this:</p>

<pre class="lang-js prettyprint-override"><code>// Call load() on the default Loader instance
loader.load('/foo/index');

// loader.Loader is a class, and loader is an instance of it
if(loader instanceof loader.Loader) {
    console.log('Yes, loader is a Loader');
}

// Create a new Loader instance
var myLoader = loader.Loader.create('my-loader');

// Call load on this Loader instance
myLoader.load('/bar/something');

// myLoader is also an instance loader.Loader
if(myLoader instanceof loader.Loader) {
    console.log('Yes, myLoader is a Loader');
}
</code>```

答:
I don't quite understand what do you mean when you say "Loader is not exported globally" and "loader is exported globally". A thing can either be exported from module and available for importing in other modules, or not exported - there is no concept of "global export". On the other hand, a thing can be declared to exist in global namespace, like global variables do, to be available in every module without importing anything explicitly.

If you want loader with extra Loader property to be exported from a module, there is no need to declare a namespace - you can add Loader property using intersection type when declaring loader instance:

loader.d.ts

```<code>declare class Loader {
    id: number;
    name: string;
    load(url: string): any;

    static create(name: string, parent?: Loader): Loader;
}

declare const loader: Loader & { Loader: typeof Loader };

export {loader};  // Loader is not exported
</code>```

All your examples compile after importing loader like this:

```<code>import {loader} from './loader';

// Call load() on the default Loader instance
loader.load('/foo/index');

// loader.Loader is a class, and loader is an instance of it
if(loader instanceof loader.Loader) {
    console.log('Yes, loader is a Loader');
}

// Create a new Loader instance
var myLoader = loader.Loader.create('my-loader');

// Call load on this Loader instance
myLoader.load('/bar/something');

// myLoader is also an instance loader.Loader
if(myLoader instanceof loader.Loader) {
    console.log('Yes, myLoader is a Loader');
}
</code>```

Body:
How can I create a .d.ts file that represents the following JavaScript API?

Loader is a class which is not exported globally

loader is exported globally, and is an instance of Loader

loader.Loader is the Loader class itself

Loader has a static method create, which creates an instance of Loader

So essentially loader behaves like a namespace that includes the class Loader, but is also a instance of Loader. The following doesn't work, because TypeScript won't merge a namespace with a value:

declare namespace loader {
    class Loader {
        id: number;
        name: string;
        load(url: string): any;

        static create(name: string, parent?: Loader): Loader;
    }
}

// This doesn't work, because a namespace cannot be merged with a value:
declare const loader: loader.Loader;

Using this API from JavaScript looks like this:

// Call load() on the default Loader instance
loader.load('/foo/index');

// loader.Loader is a class, and loader is an instance of it
if(loader instanceof loader.Loader) {
    console.log('Yes, loader is a Loader');
}

// Create a new Loader instance
var myLoader = loader.Loader.create('my-loader');

// Call load on this Loader instance
myLoader.load('/bar/something');

// myLoader is also an instance loader.Loader
if(myLoader instanceof loader.Loader) {
    console.log('Yes, myLoader is a Loader');
}

Body:
I don't quite understand what do you mean when you say "Loader is not exported globally" and "loader is exported globally". A thing can either be exported from module and available for importing in other modules, or not exported - there is no concept of "global export". On the other hand, a thing can be declared to exist in global namespace, like global variables do, to be available in every module without importing anything explicitly.

If you want loader with extra Loader property to be exported from a module, there is no need to declare a namespace - you can add Loader property using intersection type when declaring loader instance:

loader.d.ts

declare class Loader {
    id: number;
    name: string;
    load(url: string): any;

    static create(name: string, parent?: Loader): Loader;
}

declare const loader: Loader & { Loader: typeof Loader };

export {loader};  // Loader is not exported

All your examples compile after importing loader like this:

import {loader} from './loader';

// Call load() on the default Loader instance
loader.load('/foo/index');

// loader.Loader is a class, and loader is an instance of it
if(loader instanceof loader.Loader) {
    console.log('Yes, loader is a Loader');
}

// Create a new Loader instance
var myLoader = loader.Loader.create('my-loader');

// Call load on this Loader instance
myLoader.load('/bar/something');

// myLoader is also an instance loader.Loader
if(myLoader instanceof loader.Loader) {
    console.log('Yes, myLoader is a Loader');
}


问:
Setting a property {get;} using reflection in C#
I have a class from a third-party library with a read-only property called Name. Here is the code for the class:

```<code>public class Person
{
    public string Name {get;}
}
</code>```

I want to set the value of the Name property using reflection or another suitable method, but I don't know how the property is implemented. Specifically, I don't know if it has a backing field like this:

```<code>private string m_name;
</code>```

or if it is implemented like this:

```<code>public string Name {get; private set;}
</code>```

How can I set the value of the Name property in this situation?

答:
You need to obtain a FieldInfo instance for the property's backing field and call the SetValue() method.

The Mono.Reflection library (available in Package Manager) will help you find the backing field.

If the Property is an auto-property, you can call the GetBackingField() extension method on the PropertyInfo instance.

Otherwise, you'll have to disassemble the IL of the MethodInfo of the getter like this:

```<code>var instructions = yourProp.GetGetMethod().GetInstructions();
</code>```

This will give you a list of the method's IL instructions. If they look like this:

```<code>Ldarg0
Ldfld    (Backing Field)
Ret
</code>```

Then the 2nd Instruction will give you the backing field. In code:

```<code>if (instructions.Count == 3 && instructions[0].OpCode == OpCodes.Ldarg_0 && instructions[1].OpCode == OpCodes.Ldfld && instructions[2].OpCode == OpCodes.Ret)
{
    FieldInfo backingField = (FieldInfo)instructions[1].Operand;
}
</code>```

Otherwise, the property is probably computed and has no backing field.

Body:
I have a class from a third-party library with a read-only property called Name. Here is the code for the class:

public class Person
{
    public string Name {get;}
}

I want to set the value of the Name property using reflection or another suitable method, but I don't know how the property is implemented. Specifically, I don't know if it has a backing field like this:

private string m_name;

or if it is implemented like this:

public string Name {get; private set;}

How can I set the value of the Name property in this situation?

Body:
You need to obtain a FieldInfo instance for the property's backing field and call the SetValue() method.

The Mono.Reflection library (available in Package Manager) will help you find the backing field.

If the Property is an auto-property, you can call the GetBackingField() extension method on the PropertyInfo instance.

Otherwise, you'll have to disassemble the IL of the MethodInfo of the getter like this:

var instructions = yourProp.GetGetMethod().GetInstructions();

This will give you a list of the method's IL instructions. If they look like this:

Ldarg0
Ldfld    (Backing Field)
Ret

Then the 2nd Instruction will give you the backing field. In code:

if (instructions.Count == 3 && instructions[0].OpCode == OpCodes.Ldarg_0 && instructions[1].OpCode == OpCodes.Ldfld && instructions[2].OpCode == OpCodes.Ret)
{
    FieldInfo backingField = (FieldInfo)instructions[1].Operand;
}

Otherwise, the property is probably computed and has no backing field.