问:
div display as square and then becomes circle when loading page on iPad
When I load the page on iPad it first shows ".dial" in square then after loading the page it becomes circle.

I have already use border-radius 50%. So I want to do like when I load this page ".dial" should be circle from beginning not square at all. This only happens in iPad browser.

Here's my JSFiddle

and

Snippet:

.container {
  width: 600px;
  height: 600px;
  margin: 0 auto;
  background-color: black;
}

.dial {
  position: relative;
  width: 300px;
  height: 300px;
  border-radius: 50%;
  left: 25%;
  top: calc((100% - 500px) / 2);
  border: 5px solid @white;
  overflow: hidden;
  background: white;
  transition: width ease-out 0.4s, left ease-out 0.4s;
}

.score-wrapper {
  position: absolute;
  font-size: 5em;
  top: 100px;
  z-index: 1;
  color: white;
}

.gradient {
  background: #ff3232;
  /* Old browsers */
  background: linear-gradient(to right, #ff3232 0%, #f97d2f 30%, #c9c90a 70%, #23e030 100%);
}

.dial-gradient {
  position: absolute;
  //overflow: hidden;
  width: 3000px;
  height: 500px;
  padding-left: 150px;
  li {
    position: relative;
    display: inline-block;
    vertical-align: middle;
    width: 4px;
    height: 40px;
    background: rgba(255, 255, 255, 0.2);
    margin-top: 110px;
    margin-bottom: 20px;
    margin-right: 3px;
    bottom: 0;
    z-index: 1;
  }
  .big {
    height: 80px;
    width: 4px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="dial">
    <span class="score-wrapper" style="transform: matrix(1, 0, 0, 1, 65, 0);">80%</span>
    <div class="dial-gradient gradient" style="width: 3300px; transform: matrix(1, 0, 0, 1, -2400, 0);">
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li style="margin-right: 26px;"></li>
      <li class="big" style="margin-right: 26px;"></li>
    </div>
  </div>
</div></code>```

答:
Some browsers do not read percentage in border-radius, because your dial is a fixed height and width adding 300px to border-radius instead of 50% will correct it across all browsers.</p>

```<code>.dial {
        position: relative;
        width: 300px;
        height: 300px;
        border-radius:300px;
        left: 25%;
        top: calc((100% - 500px) / 2);
        border: 5px solid @white;
        overflow: hidden;
        background: white;
        transition: width ease-out 0.4s, left ease-out 0.4s;
    }
</code>```

Body:
When I load the page on iPad it first shows ".dial" in square then after loading the page it becomes circle.

I have already use border-radius 50%. So I want to do like when I load this page ".dial" should be circle from beginning not square at all. This only happens in iPad browser.

Here's my JSFiddle

and

Snippet:

.container {
  width: 600px;
  height: 600px;
  margin: 0 auto;
  background-color: black;
}

.dial {
  position: relative;
  width: 300px;
  height: 300px;
  border-radius: 50%;
  left: 25%;
  top: calc((100% - 500px) / 2);
  border: 5px solid @white;
  overflow: hidden;
  background: white;
  transition: width ease-out 0.4s, left ease-out 0.4s;
}

.score-wrapper {
  position: absolute;
  font-size: 5em;
  top: 100px;
  z-index: 1;
  color: white;
}

.gradient {
  background: #ff3232;
  /* Old browsers */
  background: linear-gradient(to right, #ff3232 0%, #f97d2f 30%, #c9c90a 70%, #23e030 100%);
}

.dial-gradient {
  position: absolute;
  //overflow: hidden;
  width: 3000px;
  height: 500px;
  padding-left: 150px;
  li {
    position: relative;
    display: inline-block;
    vertical-align: middle;
    width: 4px;
    height: 40px;
    background: rgba(255, 255, 255, 0.2);
    margin-top: 110px;
    margin-bottom: 20px;
    margin-right: 3px;
    bottom: 0;
    z-index: 1;
  }
  .big {
    height: 80px;
    width: 4px;
  }

    80%

Body:
Some browsers do not read percentage in border-radius, because your dial is a fixed height and width adding 300px to border-radius instead of 50% will correct it across all browsers.

.dial {
        position: relative;
        width: 300px;
        height: 300px;
        border-radius:300px;
        left: 25%;
        top: calc((100% - 500px) / 2);
        border: 5px solid @white;
        overflow: hidden;
        background: white;
        transition: width ease-out 0.4s, left ease-out 0.4s;
    }


来源: stackexchange

问:
One should choose recursion over iteration?
Why should one choose recursion over iteration, when a solution has the same time complexity for both cases but better space complexity for iterative?</p>

答:
Iteration is more difficult to understand in some algorithms. An algorithm that can naturally be expressed recursively may not be as easy to understand if expressed iteratively. It can also be difficult to convert a recursive algorithm into an iterative algorithm, and verifying that the algorithms are equivalent can also be difficult.

Recursion allows you to allocate additional automatic objects at each function call. The iterative alternative is to repeatedly dynamically allocate or resize memory blocks. On many platforms automatic allocation is much faster, to the point that its speed bonus outweighs the speed penalty and storage cost of recursive calls. (But some platforms don't support allocation of large amounts of automatic data, as mentioned above; it's a trade-off.)

recursion is very beneficial when the iterative solutions requires that you simulate recursion with a stack. Recursion acknowledges that the compiler already manages a stack to accomplish precisely what you need. When you start managing your own, not only are you likely re-introducing the function call overhead you intended to avoid; but you're re-inventing a wheel (with plenty of room for bugs) that already exists in a pretty bug-free form.

ContentLicense: CC BY-SA 3.0


问:
Is it possible to do systems programming in J or something close to it?
just wondering if this is possible? if so id like to see some online texts about it b/c I googled and couldnt find any haha, thanks</p>

答:
I'm tempted to say no. While technically anything is possible, J will need its interpreter, so you've got at least that much to consider. J also has sluggish memory access time, making it not the ideal platform to do system programming.

So the real answer would be yes, it can, but it's far from ideal.

ContentLicense: CC BY-SA 2.5


问:
After SSL installation "Page Not Found" Errors on every page except homepage on Apache using Symfony2
My .htaccess file code is

```<code># Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex index.php

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Determine the RewriteBase automatically and set it as environment variable.
    # If you are using Apache aliases to do mass virtual hosting or installed the
    # project in a subdirectory, the base path will be prepended to allow proper
    # resolution of the app.php file and to redirect to the correct URI. It will
    # work in environments without path prefix as well, providing a safe, one-size
    # fits all solution. But as you do not need it in this case, you can comment
    # the following 2 lines to eliminate the overhead.
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]

    # Redirect to URI without front controller to prevent duplicate content
    # (with and without `/app.php`). Only do this redirect on the initial
    # rewrite by Apache and not on subsequent cycles. Otherwise we would get an
    # endless redirect loop (request -> rewrite to front controller ->
    # redirect -> request -> ...).
    # So in case you get a "too many redirects" error or you always get redirected
    # to the start page because your Apache does not expose the REDIRECT_STATUS
    # environment variable, you have 2 choices:
    # - disable this feature by commenting the following 2 lines or
    # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
    #   following RewriteCond (best solution)
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^index\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]

    # Rewrite all other queries to the front controller.
    RewriteRule .? %{ENV:BASE}/index.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        # When mod_rewrite is not available, we instruct a temporary redirect of
        # the start page to the front controller explicitly so that the website
        # and the generated links can still be used.
        RedirectMatch 302 ^/$ /index.php/
        # RedirectTemp cannot be used instead
    </IfModule>
</IfModule>
</code>```

My domain link https://www.spectrumdialogues.com/

But when I hit link it is showing homepage properly, but in every page inside menu it is showing Not Found error. Because all menu URL's generated dynamically using Symfony2 route.

What is the .htaccess configuration if URL's generated dynamically like news website article's URL's?

Please guys help me!!!!

答:
Try to change you Apache config file:

```<code><VirtualHost *:80>
    ServerAdmin admin@yoursite.com
    ServerName yoursitename.com
    ServerAlias www.yoursitename.com
    DocumentRoot /home/admin/projects/yoursite
    <Directory "/home/admin/projects/yoursite/web/">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/yousite_error.log
    CustomLog ${APACHE_LOG_DIR}/yousite_access.log combined
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
</code>```

If this is not work, you have to see you Apache2 error file. For example /var/log/apache2/yousite_error.log

Body:
My .htaccess file code is

# Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex index.php

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Determine the RewriteBase automatically and set it as environment variable.
    # If you are using Apache aliases to do mass virtual hosting or installed the
    # project in a subdirectory, the base path will be prepended to allow proper
    # resolution of the app.php file and to redirect to the correct URI. It will
    # work in environments without path prefix as well, providing a safe, one-size
    # fits all solution. But as you do not need it in this case, you can comment
    # the following 2 lines to eliminate the overhead.
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]

    # Redirect to URI without front controller to prevent duplicate content
    # (with and without `/app.php`). Only do this redirect on the initial
    # rewrite by Apache and not on subsequent cycles. Otherwise we would get an
    # endless redirect loop (request -> rewrite to front controller ->
    # redirect -> request -> ...).
    # So in case you get a "too many redirects" error or you always get redirected
    # to the start page because your Apache does not expose the REDIRECT_STATUS
    # environment variable, you have 2 choices:
    # - disable this feature by commenting the following 2 lines or
    # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
    #   following RewriteCond (best solution)
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^index\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]

    # Rewrite all other queries to the front controller.
    RewriteRule .? %{ENV:BASE}/index.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        # When mod_rewrite is not available, we instruct a temporary redirect of
        # the start page to the front controller explicitly so that the website
        # and the generated links can still be used.
        RedirectMatch 302 ^/$ /index.php/
        # RedirectTemp cannot be used instead
    </IfModule>
</IfModule>

My domain link https://www.spectrumdialogues.com/

But when I hit link it is showing homepage properly, but in every page inside menu it is showing Not Found error. Because all menu URL's generated dynamically using Symfony2 route.

What is the .htaccess configuration if URL's generated dynamically like news website article's URL's?

Please guys help me!!!!

Body:
Try to change you Apache config file:

<VirtualHost *:80>
    ServerAdmin admin@yoursite.com
    ServerName yoursitename.com
    ServerAlias www.yoursitename.com
    DocumentRoot /home/admin/projects/yoursite
    <Directory "/home/admin/projects/yoursite/web/">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/yousite_error.log
    CustomLog ${APACHE_LOG_DIR}/yousite_access.log combined
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

If this is not work, you have to see you Apache2 error file. For example /var/log/apache2/yousite_error.log


问:
Proper handling of request_uri in double nginx reverse proxy?
So, essentially I am running Joomla in a Docker php7-fpm container, then I have an nginx container where a joomla.conf file is defined as follows:

```<code>#https://docs.joomla.org/nginx

server {
  listen 8081;

  error_log  /var/log/nginx/error.log;
  access_log /var/log/nginx/access.log;

  server_name php-docker.local;

  root /usr/src/joomla;
  index index.php index.html index.htm default.html default.htm;

  location / {
    try_files $uri $uri/ /index.php?$args;
  }

  # deny running scripts inside writable directories
  location ~* /(images|cache|media|logs|tmp)/.*\.(php|pl|py|jsp|asp|sh|cgi)$ {
    return 403;
    error_page 403 /403_error.html;
  }

  location ~ \.php$ {
    fastcgi_pass  joomla:9000;
    fastcgi_index index.php;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;

    include fastcgi_params;
    #include /etc/nginx/fastcgi.conf;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
  }
}
</code>```

And this works as expected... going to http://:8081 loads everything correctly.

Now, 8081 is just temporarily exposed in the nginx container, what I essentially want to do is setup a reverse proxy such that http:///joomla will be the final endpoint.

For this, I am struggling with the following conf file:

```<code>server{

  listen 80;
  server_name _;

  location /joomla/ {
    proxy_pass          http://localhost:8081/;

    proxy_set_header    Referer           $http_referer;
    proxy_set_header    X-Forwarded-Port  $server_port;
    proxy_set_header    X-Forwarded-Proto $http_x_forwarded_proto;
    proxy_set_header    Host              $host;
    proxy_set_header    X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Host  $host;
  }

}
</code>```

What happens is that the HTML is served correctly, however, none of the assets are. This is because the URLs in Joomla are generated by a JURI class, which seems to rely on $request_uri, which by when it appears to arrive to Joomla is already lost.

https://github.com/joomla/joomla-cms/blob/6ab2a6e9010e7e04c260b9eba17dc76e866dd3e6/libraries/joomla/uri/uri.php#L87

So every link or reference to a file, script, or css renders like this:

http://localhost/login

http://localhost/images/headers/maple.jpg

Instead of:

http://localhost/joomla/login

http://localhost/joomla/images/headers/maple.jpg

However, when I access the second set of URL, I can access the link/asset without a problem... but of course once again, no images, templates, js or links being rendered correctly.

I prefer not to touch joomla.conf unless something is wrong, as for site.conf I would only like to translate URI segments to map requests to other applications, e.g.:

```<code>/joomla -> localhost:8081
/phpbb -> localhost:8082
/someapp -> localhost:8083
</code>```

答:
As Rinos said, you need to configurate the $live_site var in configuration.php, as this:

```<code>public $live_site = '/joomla/';
</code>```

I've made a complete example in Github that works well after editing that file, and it uses your configs.

 Becomes:

Body:
So, essentially I am running Joomla in a Docker php7-fpm container, then I have an nginx container where a joomla.conf file is defined as follows:

#https://docs.joomla.org/nginx

server {
  listen 8081;

  error_log  /var/log/nginx/error.log;
  access_log /var/log/nginx/access.log;

  server_name php-docker.local;

  root /usr/src/joomla;
  index index.php index.html index.htm default.html default.htm;

  location / {
    try_files $uri $uri/ /index.php?$args;
  }

  # deny running scripts inside writable directories
  location ~* /(images|cache|media|logs|tmp)/.*\.(php|pl|py|jsp|asp|sh|cgi)$ {
    return 403;
    error_page 403 /403_error.html;
  }

  location ~ \.php$ {
    fastcgi_pass  joomla:9000;
    fastcgi_index index.php;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;

    include fastcgi_params;
    #include /etc/nginx/fastcgi.conf;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
  }
}

And this works as expected... going to http://:8081 loads everything correctly.

Now, 8081 is just temporarily exposed in the nginx container, what I essentially want to do is setup a reverse proxy such that http:///joomla will be the final endpoint.

For this, I am struggling with the following conf file:

server{

  listen 80;
  server_name _;

  location /joomla/ {
    proxy_pass          http://localhost:8081/;

    proxy_set_header    Referer           $http_referer;
    proxy_set_header    X-Forwarded-Port  $server_port;
    proxy_set_header    X-Forwarded-Proto $http_x_forwarded_proto;
    proxy_set_header    Host              $host;
    proxy_set_header    X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Host  $host;
  }

}

What happens is that the HTML is served correctly, however, none of the assets are. This is because the URLs in Joomla are generated by a JURI class, which seems to rely on $request_uri, which by when it appears to arrive to Joomla is already lost.

https://github.com/joomla/joomla-cms/blob/6ab2a6e9010e7e04c260b9eba17dc76e866dd3e6/libraries/joomla/uri/uri.php#L87

So every link or reference to a file, script, or css renders like this:

http://localhost/login

http://localhost/images/headers/maple.jpg

Instead of:

http://localhost/joomla/login

http://localhost/joomla/images/headers/maple.jpg

However, when I access the second set of URL, I can access the link/asset without a problem... but of course once again, no images, templates, js or links being rendered correctly.

I prefer not to touch joomla.conf unless something is wrong, as for site.conf I would only like to translate URI segments to map requests to other applications, e.g.:

/joomla -> localhost:8081
/phpbb -> localhost:8082
/someapp -> localhost:8083

Body:
As Rinos said, you need to configurate the $live_site var in configuration.php, as this:

public $live_site = '/joomla/';

I've made a complete example in Github that works well after editing that file, and it uses your configs.

 Becomes:


问:
Database schema for a tinder like app
I have a database of million of Objects (simply say lot of objects). Everyday i will present to my users 3 selected objects, and like with tinder they can swipe left to say they don't like or swipe right to say they like it.

I select each objects based on their location (more closest to the user are selected first) and also based on few user settings.

I m under mongoDB.

now the problem, how to implement the database in the way it's can provide fastly everyday a selection of object to show to the end user (and skip all the object he already swipe).

答:
Well, considering you have made your choice of using MongoDB, you will have to maintain multiple collections. One is your main collection, and you will have to maintain user specific collections which hold user data, say the document ids the user has swiped. Then, when you want to fetch data, you might want to do a setDifference aggregation. SetDifference does this:

Takes two sets and returns an array containing the elements that only
  exist in the first set; i.e. performs a relative complement of the
  second set relative to the first.

Now how performant this is would depend on the size of your sets and the overall scale.

EDIT

I agree with your comment that this is not a scalable solution.

Solution 2:

One solution I could think of is to use a graph based solution, like Neo4j. You could represent all your 1M objects and all your user objects as nodes and have relationships between users and objects that he has swiped. Your query would be to return a list of all objects the user is not connected to.

You cannot shard a graph, which brings up scaling challenges. Graph based solutions require that the entire graph be in memory. So the feasibility of this solution depends on you.

Solution 3:

Use MySQL. Have 2 tables, one being the objects table and the other being (uid-viewed_object) mapping. A join would solve your problem. Joins work well for the longest time, till you hit a scale. So I don't think is a bad starting point.

Solution 4:

Use Bloom filters. Your problem eventually boils down to a set membership problem. Give a set of ids, check if its part of another set. A Bloom filter is a probabilistic data structure which answers set membership. They are super small and super efficient. But ya, its probabilistic though, false negatives will never happen, but false positives can. So thats a trade off. Check out this for how its used : http://blog.vawter.com/2016/03/17/Using-Bloomfilters-to-Avoid-Repetition/

Ill update the answer if I can think of something else.

Title: Database schema for a tinder like app


问:
How to compile multiple java source files in command line
I know running javac file1.java produces file1.class if file1.java is the only source file, then I can just say java file1 to run it.

However, if I have 2 source files, file1.java and file2.java, then how  do I build the program?

答: OR you could just use javac file1.java and then also use javac file2.java afterwards.

ContentLicense: CC BY-SA 4.0


问:
Abstract types and type inference
Suppose I have a module that hides some type:

```<code>module Test : sig
  type t
  val make_t : unit -> t
end = struct
  type t = int option
  let make_t () = Some 42
end
</code>```

And I also have a function that operates on optioms:

```<code>let do_work : 'a option -> unit = function
  | Some x -> Printf.printf "Some\n"
  | None   -> Printf.printf "None\n"
</code>```

Not surprisingly, when I call do_work on t instance I get a type error:

```<code>let () =
  do_work @@ Test.make_t ()
</code>```

Error: This expression has type Test.t but an expression was expected of type 'a option

In my application I have t more complex than just int option and I don't want to expose its internals outward. However, I want to tell the compiler that t is actually something option. How can I achieve that?

答:
The most direct way is to make only the contents type of the option abstract:</p>

```<code>module Test :
sig
  type t'
  type t = t' option
  val make_t : unit -> t
end =
struct
  type t' = int
  type t = t' option
  let make_t () = Some 42
end
</code>```

Title: Abstract types and type inference

Body:
Suppose I have a module that hides some type:

module Test : sig
  type t
  val make_t : unit -> t
end = struct
  type t = int option
  let make_t () = Some 42
end

And I also have a function that operates on optioms:

let do_work : 'a option -> unit = function
  | Some x -> Printf.printf "Some\n"
  | None   -> Printf.printf "None\n"

Not surprisingly, when I call do_work on t instance I get a type error:

let () =
  do_work @@ Test.make_t ()

Error: This expression has type Test.t but an expression was expected of type 'a option

In my application I have t more complex than just int option and I don't want to expose its internals outward. However, I want to tell the compiler that t is actually something option. How can I achieve that?

Body:
The most direct way is to make only the contents type of the option abstract:

module Test :
sig
  type t'
  type t = t' option
  val make_t : unit -> t
end =
struct
  type t' = int
  type t = t' option
  let make_t () = Some 42
end


问:
Webservice publisher moving to TLS1.1
We are consuming a web-service from a publisher.
Our current configuration for Java is version 1.6.
So, we have generated stubs using Axis2 and our application is hosted on tomcat7.

Now, the publisher of that webservice says that it would be moving to TLS1.1 and would stop disable the SSLv3 and TLS1.0 security protocols.

How do I ensure, that we, as a client, are compliant to this new protocol.
And, if not, what steps are needed for that.

答:
Support for TLS 1.1 is included in the update 111 and higher for Java 1.6. See this for reference: TLS & Java

You should recompile your app against the newer update and see if that works.

Also, there are issues with TLS 1.0 & TLS 1.1, so you may need to consider to upgrade to Java 8 and start using TLS 1.2. But again, this is not a simple decision if you are supporting legacy SSL/TLS clients.

Title: Webservice publisher moving to TLS1.1


问:
How to hide View after a given time of inactivity
Basically I have a volume button that shows a hidden SeekBar when clicked, how to make the SeekBar go hidden again after 2 or 3 seconds of inactivity?

I just wanna know how can I check for how much time been spent since the SeekBar became visible without changing its progress!?

答:
You could create a Runnable that sets the visibility of the SeekBar to invisible:

```<code>private final Runnable hideSeekBarRunnable = new Runnable() {
    @Override
    public void run() {
        seekBar.setVisibility(View.INVISIBLE);
    }
};
</code>```

When the volume button is clicked, show the SeekBar and post the Runnable with a 2-3 sec delay:

```<code>seekBar.setVisibility(View.VISIBLE);
seekBar.postDelayed(hideSeekBarRunnable, 3000);
</code>```

And if the SeekBar is interacted with (its progress changes), remove the pending Runnable and re-post it to reset the counter:

```<code>seekBar.removeCallbacks(hideSeekBarRunnable);
seekBar.postDelayed(hideSeekBarRunnable, 3000);
</code>```

Body:
You could create a Runnable that sets the visibility of the SeekBar to invisible:

private final Runnable hideSeekBarRunnable = new Runnable() {
    @Override
    public void run() {
        seekBar.setVisibility(View.INVISIBLE);
    }
};

When the volume button is clicked, show the SeekBar and post the Runnable with a 2-3 sec delay:

seekBar.setVisibility(View.VISIBLE);
seekBar.postDelayed(hideSeekBarRunnable, 3000);

And if the SeekBar is interacted with (its progress changes), remove the pending Runnable and re-post it to reset the counter:

seekBar.removeCallbacks(hideSeekBarRunnable);
seekBar.postDelayed(hideSeekBarRunnable, 3000);


问:
What is the difference between visibility: hidden and transform: scale(0,0)?
Is there any difference between visibility: hidden and transform: scale(0,0)? Both give same results?

答:
Yes they both work same

Visiblity: hidden The element is invisible (but still takes up space).

transform: scale(0,0) It will changes the appearance visually; the actual dimensions of the original object are maintained.


问:
Memcache eviction policy
As per my understanding.

In Memcache whole memory is divided in fixed size pages and each page belongs to a particulate slab class.Each page is further divided into fixed size chunk,size of chunk is decided as per slab class.Data is stored in chunk that best suit for it(To minimise internal fragmentation).

Memcache uses LRU strategy for eviction.

somewhere I have read that LRU strategy is applied on frame instead of whole data.So,there can be case where a frame (of different class) is free but still eviction is happening on a frame.

Is this the way memcache behaves?Instead of eviction, Should not a vacant frame's chucks be resized?

答:
As you have mentioned, memory is divided in fixed size pages (1MB or Max item configured size) and each page belongs to a particulate slab class. In the begining these pages are not actually assigned to any particular slab class. As and when requests are coming, slab classes are created per size range and pages are attached to them.

Identifying the optimal slab class is the key thing. The algorithm of it roughly looks like:

Check the tail page (the most recently allocated page in this slab class) to see if it has open/free chunks.

If found, store this object in that page and return.

Else, find an unassigned page and assign it to this slab class.

If no unassigned pages are available(this doesn't mean that all the memory is completely full), do the LRU logic to free up a chunk that hasn't been used in a while (or is expired).

Store this object on either the just freed chunk (from step 4) or on the empty page (from step 3).

Now, to answer your question.

Evictions will only occur, when all the pages are allocated to some slab classes. Since, all the pages are binded with some slab classes and are ready to accept objects/items in that size range. The remaining free memory cannot be used for other sized objects. i.e. they cannot be resized. This is implemented for simplicity I guess. This method works great for many web applications, where object sizes are nearly the same size like query results, rendered html pages. In that case, Memcache will allocate all of the pages it has to very few classes you use.

I remember reading somewhere, Redis is more flexible in this aspect of resize of memory.

Hope it helps!

Title: Memcache eviction policy


问:
Difference between Java EE and Spring framework
I am striving to know the difference between Java EE and Spring Framework. Could anyone please help me on this.</p>

答:
Java EE is an standard, official, specification for a full featured Enterprise Application Framework stack. Includes stuff like Object-Relational Mapping, Security, Web Applications, database connectivity, transactions...

On top of Java EE specifications there are JavaEE implementations/application servers like: JBoss, Glassfish, WebSphere, Weblogic.

Spring on the other hand, is a framework doing lots of the stuff on the Java EE specifications, but in its own form. They don't follow Java EE specifications and APIs for that. But they do include a Web Framework, transaction management, security and several other solutions Java EE offers.


答:
If you set the visibility of an element to hidden it is hidden but still takes up space.

If you set the visiblity to collapse it will not take up space and will behave the same as display:none. But collapse can only be used on table elements.

transform: scale(0,0) will just set the size to 0,0 meaning css properties like float or clear will still take affect on other elements.

Title: What is the difference between visibility: hidden and transform: scale(0,0)?

Body: Is there any difference between visibility: hidden and transform: scale(0,0)? Both give same results?


问:
c# inheritance need simple solution
I hope you can help me with this c# question.
I have some classes like:

```<code>public abstract class Animal
{
  public abstract void Walk(int param1,int param2);
}
public class Cat : Animal
{
  public override void Walk(int param1,int param2){}
}
public class SmallCat : Cat
{
  public override void Walk(int param1,int param2){}
}
public class Dog : Animal
{
  public override void Walk(int param1,int  param2){}
}
</code>```

And I have a controller class for all animals.

```<code>someAnimal.Walk(a,b);
</code>```

My question is : I dont want base class to know all details about moving but I need more parameters or different parameters for different animals on Walk function.
What is good way to solve this?

By the way the changing parameters are only needed when the different user (controller) takes control of the animal.

After reading your comments I've decided to use a simple UserController class which has all user(changing parameters) details, and send this to Animal class when it takes control of it.

答: I would think that universal parameters for walking that may change each time the method is called, might be length and velocity. Any other parameters, specific to a concrete instance, could be provided to the instance at either the time of construction or through a mutator.</p>

Title: c# inheritance need simple solution

Body:
I hope you can help me with this c# question.
I have some classes like:

public abstract class Animal
{
  public abstract void Walk(int param1,int param2);
}
public class Cat : Animal
{
  public override void Walk(int param1,int param2){}
}
public class SmallCat : Cat
{
  public override void Walk(int param1,int param2){}
}
public class Dog : Animal
{
  public override void Walk(int param1,int  param2){}
}

And I have a controller class for all animals.

someAnimal.Walk(a,b);

My question is : I dont want base class to know all details about moving but I need more parameters or different parameters for different animals on Walk function.
What is good way to solve this?

By the way the changing parameters are only needed when the different user (controller) takes control of the animal.

After reading your comments I've decided to use a simple UserController class which has all user(changing parameters) details, and send this to Animal class when it takes control of it.


问:
Connection to IBM message hub using C# and Confluent
I'm trying to create producer and consumer apps using IBM message hub. For the producer i'm using the following code:

```<code>var config = new Dictionary<string, object> {
                { "bootstrap.servers", brokerList },
                { "group.id", "simple-csharp-producer" },
                { "client.id", "some string for id such as FR45fHth..." },
                {"api.version.request","true" },
                {"sasl.mechanisms","PLAIN" },
                {"sasl.username","the first 16 charachters of the client.id" },
                {"sasl.password","the other characters left" }
            };

            using (var producer = new Producer<Null, string>(config, null, new StringSerializer(Encoding.UTF8)))
            {
              ....
            }
</code>```

for the consumer i'm using similar config properties.

the rest of the code for the consumer:

```<code>using (var consumer = new Consumer<Null, string>(config, null, new StringDeserializer(Encoding.UTF8)))
            {
                consumer.Assign(new List<TopicPartitionOffset> { new TopicPartitionOffset(topics, 0, 0) });

                while (true)
                {
                    Message<Null, string> msg;
                    if (consumer.Consume(out msg, TimeSpan.FromSeconds(1)))
                    {
                        Console.WriteLine($"Topic: {msg.Topic} Partition: {msg.Partition} Offset: {msg.Offset} {msg.Value}");
                    }
                }
            }
</code>```

and for the producer:

```<code>using (var producer = new Producer<Null, string>(config, null, new StringSerializer(Encoding.UTF8)))
            {
                Console.WriteLine($"{producer.Name} producing on {topicName}. q to exit.");

                string text;
                while ((text = Console.ReadLine()) != "q")
                {
                    var deliveryReport = producer.ProduceAsync(topicName, null, text);
                    deliveryReport.ContinueWith(task =>
                    {
                        Console.WriteLine($"Partition: {task.Result.Partition}, Offset: {task.Result.Offset}");
                    });
                }

                // Tasks are not waited on synchronously (ContinueWith is not synchronous),
                // so it's possible they may still in progress here.
                producer.Flush(Convert.ToInt32(TimeSpan.FromSeconds(10)));
</code>```

Anyhow, it didn't work, there is no sign for sending of getting anything...
what is missing?
or what can i use for it to work?

The Logs i get:

*sasl_ssl://kafka03-prod02.messagehub.services.eu-gb.bluemix.net:9093/bootstrap:
  Failed to initialize SASL authentication: SASL mechanism "PLAIN" not
  supported on platform

*1/1 brokers are down

答:
I've not used the Confluent C# client myself, but as far as I know it's based on librdkakfa, so you'll at least need a few more configurations to connect to Message Hub:

security.protocol set to SASL_SSL

ssl.ca.location set to the path of your CA certificates

Body:
I'm trying to create producer and consumer apps using IBM message hub. For the producer i'm using the following code:

var config = new Dictionary<string, object> {
                { "bootstrap.servers", brokerList },
                { "group.id", "simple-csharp-producer" },
                { "client.id", "some string for id such as FR45fHth..." },
                {"api.version.request","true" },
                {"sasl.mechanisms","PLAIN" },
                {"sasl.username","the first 16 charachters of the client.id" },
                {"sasl.password","the other characters left" }
            };

            using (var producer = new Producer<Null, string>(config, null, new StringSerializer(Encoding.UTF8)))
            {
              ....
            }

for the consumer i'm using similar config properties.

the rest of the code for the consumer:

using (var consumer = new Consumer<Null, string>(config, null, new StringDeserializer(Encoding.UTF8)))
            {
                consumer.Assign(new List<TopicPartitionOffset> { new TopicPartitionOffset(topics, 0, 0) });

                while (true)
                {
                    Message<Null, string> msg;
                    if (consumer.Consume(out msg, TimeSpan.FromSeconds(1)))
                    {
                        Console.WriteLine($"Topic: {msg.Topic} Partition: {msg.Partition} Offset: {msg.Offset} {msg.Value}");
                    }
                }
            }

and for the producer:

using (var producer = new Producer<Null, string>(config, null, new StringSerializer(Encoding.UTF8)))
            {
                Console.WriteLine($"{producer.Name} producing on {topicName}. q to exit.");

                string text;
                while ((text = Console.ReadLine()) != "q")
                {
                    var deliveryReport = producer.ProduceAsync(topicName, null, text);
                    deliveryReport.ContinueWith(task =>
                    {
                        Console.WriteLine($"Partition: {task.Result.Partition}, Offset: {task.Result.Offset}");
                    });
                }

                // Tasks are not waited on synchronously (ContinueWith is not synchronous),
                // so it's possible they may still in progress here.
                producer.Flush(Convert.ToInt32(TimeSpan.FromSeconds(10)));

Anyhow, it didn't work, there is no sign for sending of getting anything...
what is missing?
or what can i use for it to work?

The Logs i get:

*sasl_ssl://kafka03-prod02.messagehub.services.eu-gb.bluemix.net:9093/bootstrap:
  Failed to initialize SASL authentication: SASL mechanism "PLAIN" not
  supported on platform

*1/1 brokers are down


问:
typescript error: TS2304: Cannot find name '$'
The statement

```<code> x = $('#msgBox_' + scope.boxId).position().left;
</code>```

generates an

error TS2304: Cannot find name '$'

although jquery and @types are installed in the node_modules folder.

My tsconfig.json looks like that:

```<code>{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "moduleResolution": "node",
    "declaration": true
  },
  "exclude": [
    "node_modules"
  ]
}
</code>```

How can I fix that?

答: Turns out I was missing the "@types/jquery" node module, which contains a definition of "$". Once I added "@types/jquery": "^3.2.5" to the list of  "devDependencies" in my package.json and reinstalled via "npm install", everything worked fine. </p>

Body:
The statement

 x = $('#msgBox_' + scope.boxId).position().left;

generates an

error TS2304: Cannot find name '$'

although jquery and @types are installed in the node_modules folder.

My tsconfig.json looks like that:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "moduleResolution": "node",
    "declaration": true
  },
  "exclude": [
    "node_modules"
  ]
}

How can I fix that?


问:
Create a big table with huge number of columns?
How can I create a table with 1000 row and at least 64000 columns. As I know, SQL database and Microsoft Excel suppot only 30000 and 16384 columns per table, respectively. How can I create such a table? Is there any solution? I want to use this table as an input for RapidMiner studio!</p>

答:
If you are determined to create this beast it would require a work around the column limit.

My suggestion would be 10x~6401 column tables with an ID/Key to link each row.

Join together the ten tables like so:

```<code> select * from
 Table1
 join Table2 on Table1.ID = Table2.ID
 join Table3 on Table1.ID = Table3.ID
</code>```

etc etc

Whether this would work as a singular input for RapiMiner, I'm not sure

Body:
If you are determined to create this beast it would require a work around the column limit.

My suggestion would be 10x~6401 column tables with an ID/Key to link each row.

Join together the ten tables like so:

 select * from
 Table1
 join Table2 on Table1.ID = Table2.ID
 join Table3 on Table1.ID = Table3.ID

etc etc

Whether this would work as a singular input for RapiMiner, I'm not sure


问:
Send variable together with message in camunda
I have a receiving process which has an intermediate message event waiting for a message send by a sending process.

I am already able to trigger the intermediate message event by the following delegate code in my sending process:

```<code>RuntimeService runtimeService = ProcessEngines
        .getDefaultProcessEngine()
        .getRuntimeService();
MessageCorrelationResult result = runtimeService
        .createMessageCorrelation("my-message-name")
        .setVariable("customer", customer)    //trigger instance where customer matches
        .correlateWithResult();
</code>```

My question is: How can I send a variable from the sending process to the receiving process combined with the message? Are there any best practices?

This is what I haved tried so far:

```<code>// Set the variable after the correlation
runtimeService.setVariable(result.getProcessInstance().getId(),
    "variableToSend", variableToSend);
</code>```

I try to retrieve the variable in a JavaDelegate like this:

```<code>// Access the sent variable
Double sendByOtherProcess = (Double) delegate.getVariable("variableToSend");
// sendByOtherProcess == null
</code>```

Interestingly enough, it is possible to retrieve variableToSend in an embedded form via JavaScript in the receiving process.

I read that it might be an isse due to synchron/asynchron behavior?

Any help appreciated.

答:
You had already set a variable on the MessageCorrelationBuilder, with MessageCorrelationBuilder#setVariable. For more information see the JavaDoc or the MessageCorrelationBuilder

As you mentioned you want to correlate the message to a process which matches with the given variable. For that you have to use the #processInstanceVariableEquals method.

Body:
I have a receiving process which has an intermediate message event waiting for a message send by a sending process.

I am already able to trigger the intermediate message event by the following delegate code in my sending process:

RuntimeService runtimeService = ProcessEngines
        .getDefaultProcessEngine()
        .getRuntimeService();
MessageCorrelationResult result = runtimeService
        .createMessageCorrelation("my-message-name")
        .setVariable("customer", customer)    //trigger instance where customer matches
        .correlateWithResult();

My question is: How can I send a variable from the sending process to the receiving process combined with the message? Are there any best practices?

This is what I haved tried so far:

// Set the variable after the correlation
runtimeService.setVariable(result.getProcessInstance().getId(),
    "variableToSend", variableToSend);

I try to retrieve the variable in a JavaDelegate like this:

// Access the sent variable
Double sendByOtherProcess = (Double) delegate.getVariable("variableToSend");
// sendByOtherProcess == null

Interestingly enough, it is possible to retrieve variableToSend in an embedded form via JavaScript in the receiving process.

I read that it might be an isse due to synchron/asynchron behavior?

Any help appreciated.


问:
jvmti agent deadlock
When I run my jvmti agent with a java program, it seems that jvm encounters a deadlock.
In my jvmti agent, I create a single raw monitor in Agent_OnLoad() and enter that lock at the beginning of every callback function and exit that lock at the end of every callback functions.
I don't know the reason of this deadlock. Is there any other possibilities of deadlocks in jvmti agents?

thanks.

答:
I hit the same problem when a number of threads call the JVMTI agent concurrently. One thread successfully calls RawMonitorEnter and proceeds. After this a number of other threads call RawMonitorEnter and block, as expected. The thread holding the raw monitor then calls RawMonitorExit, but it appears that this function does not return, which results in the deadlock.

A workaround was to wrap the RawMonitorEnter/Exit and the logic between them in a mutex. This ensured that only one thread at a time would attempt to acquire the raw monitor. The workaround may also negate the need for a raw monitor altogether.

Title: jvmti agent deadlock


问:
Issue in self updating sql query
I am trying to update a table according to values from an inner join on the same table and another table.

Below is the query :-

```<code>update coin_txn_normalization  cn
SET cn.is_merchant_pay_rel='H'
where cn.coin_txn_id IN(
   SELECT ctn.coin_txn_id
   FROM hold  h
   INNER JOIN coin_txn_normalization ctn
   ON h.txn_id = ctn.coin_txn_id
);
</code>```

I am getting the following error

```<code>SQL Error (1093): Table 'cn' is specified twice, both as a target
for 'UPDATE' and as a separate source for data
Affected rows: 0  Found rows: 0  Warnings: 0  Duration for 0 of 1 query: 0.000 sec.
</code>```

How should I solve this error. Let Me know if anything else is needed.

答:
As you have learned, MySQL doesn't all the table being updated (or deleted) to be referenced in the where or set clauses.

In your case, this is easily fixed:

```<code>update coin_txn_normalization  cn
    set cn.is_merchant_pay_rel = 'H'
    where cn.coin_txn_id in (select h.txn_id from hold);
</code>```

This is a much simpler version anyway.  If there are not multiple matches in hold, then a join is also appropriate:

```<code>update coin_txn_normalization cn join
       hold h
       on h.txn_id = cn.coin_txn_id
    set cn.is_merchant_pay_rel = 'H' ;
</code>```

Title: Issue in self updating sql query

Body:
I am trying to update a table according to values from an inner join on the same table and another table.

Below is the query :-

update coin_txn_normalization  cn
SET cn.is_merchant_pay_rel='H'
where cn.coin_txn_id IN(
   SELECT ctn.coin_txn_id
   FROM hold  h
   INNER JOIN coin_txn_normalization ctn
   ON h.txn_id = ctn.coin_txn_id
);

I am getting the following error

SQL Error (1093): Table 'cn' is specified twice, both as a target
for 'UPDATE' and as a separate source for data
Affected rows: 0  Found rows: 0  Warnings: 0  Duration for 0 of 1 query: 0.000 sec.

How should I solve this error. Let Me know if anything else is needed.

Body:
As you have learned, MySQL doesn't all the table being updated (or deleted) to be referenced in the where or set clauses.

In your case, this is easily fixed:

update coin_txn_normalization  cn
    set cn.is_merchant_pay_rel = 'H'
    where cn.coin_txn_id in (select h.txn_id from hold);

This is a much simpler version anyway.  If there are not multiple matches in hold, then a join is also appropriate:

update coin_txn_normalization cn join
       hold h
       on h.txn_id = cn.coin_txn_id
    set cn.is_merchant_pay_rel = 'H' ;


问:
Angular on Internet Explorer
I am developing an angular app that shows fine on Chrome but does non work at all on IE. Is there a way to configure IE to correctly show the app or to change the app so to show fin on IE?
While this is the image on Chrome:

答:
Many thanks to Alex3683 for the button, it all just boils down to configuring IE for using Edge instead of 7 compatibility. As for the table IE does not support Object.values so I found and used a manual implementation working everywhere:</p>

```<code>function objectValues(obj) {
    var res = [];
    for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
            res.push(obj[i]);
        }
    }
    return res;
}
</code>```

Title: Angular on Internet Explorer

Body:
Many thanks to Alex3683 for the button, it all just boils down to configuring IE for using Edge instead of 7 compatibility. As for the table IE does not support Object.values so I found and used a manual implementation working everywhere:

function objectValues(obj) {
    var res = [];
    for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
            res.push(obj[i]);
        }
    }
    return res;
}


问:
How can I make my cells selectable when there is an UIView below the UICollectionView?
I have a collection view, and added a UIView below it. The cells shows up on top of it, but they aren't selectable. How can I make them selectable again?

What I have tried so far:

UIView has zPosition -1 and my cells have +1
UIView.isUserInteractionEnabled = true

I have tried to add the UIView both as view.addSubview and collectionView?.addSubview

collectionView?.insertSubview(UIView, belowSubview: collectionView!)

This guy has the same problem, with no solution provided: Inserting Subview Below UICollectionView

Edit: I'm using this code to determine what cells are selected

```<code>override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    //Code here...
}
</code>```

It all works when there is no UIView below. But I want to have a visible "container" for my collectionview content insets, so I created an UIView.
Problem is the above code doesn't get fired at all when clicking on the cells with the UIView below.

答:
Why dont you do the selection manually at the moment when the view is tapped:

```<code>func selectItem(at: IndexPath?, animated: Bool, scrollPosition: UICollectionViewScrollPosition)
</code>```

Can you show more in code?

Body:
I have a collection view, and added a UIView below it. The cells shows up on top of it, but they aren't selectable. How can I make them selectable again?

What I have tried so far:

UIView has zPosition -1 and my cells have +1
UIView.isUserInteractionEnabled = true

I have tried to add the UIView both as view.addSubview and collectionView?.addSubview

collectionView?.insertSubview(UIView, belowSubview: collectionView!)

This guy has the same problem, with no solution provided: Inserting Subview Below UICollectionView

Edit: I'm using this code to determine what cells are selected

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    //Code here...
}

It all works when there is no UIView below. But I want to have a visible "container" for my collectionview content insets, so I created an UIView.
Problem is the above code doesn't get fired at all when clicking on the cells with the UIView below.

Body:
Why dont you do the selection manually at the moment when the view is tapped:

func selectItem(at: IndexPath?, animated: Bool, scrollPosition: UICollectionViewScrollPosition)

Can you show more in code?


问:
Tool to detect non-dotted relative imports in Python?
It's considered bad Python to use imports like this:

```<code>import my_module
</code>```

When you are doing a relative import and this would work:

```<code>from . import my_module
</code>```

Is there a tool that can detect these non-dotted relative imports in my code and warn me so I could update them to the dotted syntax? My project has hundreds of Python modules and I would like to do this automatically. (Possibly such a tool would override __import__ and detect the bad imports as they happen when I run the program.)

Does anyone know of such tool?

答: pylint gives warnings about relative imports, along with tons of other stuff that's considered, for one reason or another, "bad Python".</p>

Body:
It's considered bad Python to use imports like this:

import my_module

When you are doing a relative import and this would work:

from . import my_module

Is there a tool that can detect these non-dotted relative imports in my code and warn me so I could update them to the dotted syntax? My project has hundreds of Python modules and I would like to do this automatically. (Possibly such a tool would override __import__ and detect the bad imports as they happen when I run the program.)

Does anyone know of such tool?


问:
Retrofit2 Deserialize response body even if response is not 200
I want to be able to deserialize network response to the same Java object even if response is not succesfull. Currently when I get an error response like 403, the response body is null, and I'm expected to use the response.errorBody() method to read whatever has been sent back, which is ok. However I want to avoid having alot of code in the retrofit callbacks just for deserializing errorBody. Instead I want to have an interceptor that sets the content of errorBody into body.

The reason for this is that I have a response object that has fields for both error and non error responses and depending on the status of the response some fields are expected to be left null e.g

Error Response JSON

```<code>{
"locked":true,
"remaining_attempts": 2
}
</code>```

Success Response JSON

```<code>{
"name":"kev"
"token":"abcdefghijklmnopq"
}
</code>```

I have created a single Java object that captures both scenarios:

```<code>class LoginResponse{
    @Expose
    private String name;
    @Expose
    private String token;
    @Expose
    private Boolean locked;
    @Expose
    private Integer remaining_attempts;
}
</code>```

Is there way to do this in an interceptor?

答:
You can do something like following in response directly...

```<code>    LoginResponse errorResponse = gson.fromJson(response.errorBody().string(), LoginResponse.class);
</code>```

...or using interceptor

```<code>addInterceptor(getMyErrorResponseInterceptor())

protected Interceptor getMyErrorResponseInterceptor() {
    return new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            if (response.code() >= 400) {

                // handle error
            }

            return response;
        }
    };
}
</code>```

Body:
I want to be able to deserialize network response to the same Java object even if response is not succesfull. Currently when I get an error response like 403, the response body is null, and I'm expected to use the response.errorBody() method to read whatever has been sent back, which is ok. However I want to avoid having alot of code in the retrofit callbacks just for deserializing errorBody. Instead I want to have an interceptor that sets the content of errorBody into body.

The reason for this is that I have a response object that has fields for both error and non error responses and depending on the status of the response some fields are expected to be left null e.g

Error Response JSON

{
"locked":true,
"remaining_attempts": 2
}

Success Response JSON

{
"name":"kev"
"token":"abcdefghijklmnopq"
}

I have created a single Java object that captures both scenarios:

class LoginResponse{
    @Expose
    private String name;
    @Expose
    private String token;
    @Expose
    private Boolean locked;
    @Expose
    private Integer remaining_attempts;
}

Is there way to do this in an interceptor?

Body:
You can do something like following in response directly...

    LoginResponse errorResponse = gson.fromJson(response.errorBody().string(), LoginResponse.class);

...or using interceptor

addInterceptor(getMyErrorResponseInterceptor())

protected Interceptor getMyErrorResponseInterceptor() {
    return new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            if (response.code() >= 400) {

                // handle error
            }

            return response;
        }
    };
}


问:
Repeatedly scrape data from same url with a time delay
I am trying to consistently scrape a single webpage over a period of time to monitor some values and how they are changing within that period

I have no experience in web-scraping and I'm a little confused as to why my scrapy spider runs once and hangs.

I am attempting to run the spider through a 'main.py' script as follows:

```<code>timecheck = timeit.default_timer()

while (timecheck) < 30:
    if __name__ == "__main__":
        settings = get_project_settings()
        crawler = CrawlerProcess(settings)
        crawler.crawl(mySpider())
        crawler.start(stop_after_crawl=False)
    time.sleep(5)

print("Finished crawl, time elapsed: %s" % str(timecheck))
</code>```

My spider script is as follows:

```<code>class poeSpider(scrapy.Spider):
    name = "spidername"

    def start_requests(self):
        urls = ["myurl.com/page1"]
        allowed_domains = ["myurl.com"]

        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse, dont_filter=True)

    def parse(self,response):

        datavar = response.xpath("/mydata").extract()
        print(datavar[:3])
</code>```

PS: A different issue, but related:

I'm also looking to store the data in a list or variable of some kind between scrapes so that I am able to compare the values while the program is running, ideally without any file I/O, which is my reasoning for using a 'main.py' though I'm also at a loss for how to pass the data in the parse function of the spider to anywhere where I can make such comparisons.

答:
You should keep the logic in spider itself:

```<code>import scrapy
import logging
import time
from scrapy import signals, Request

class MySpider(scrapy.Spider):
    start_urls = ['first_url']

    @classmethod
    def from_crawler(cls, crawler, *args, **kwargs):
        spider = super(MySpider, cls).from_crawler(crawler, *args, **kwargs)
        crawler.signals.connect(spider.spider_idle, signals.spider_idle)
        return spider

    def parse(self, response):
        # parse page
        pass

    def spider_idle(self, spider):
        time.sleep(30)
        # after 30 seconds crawl the same page again
        logging.info('starting a crawl again!')
        self.crawler.engine.schedule(Request(self.start_urls[0], dont_filter=True), spider)
        raise DontCloseSpider
</code>```

In this example when spider goes idle after it will chill out for 30 seconds and then crawl start url again, and keep repeating this untill it's killed or stopped.

Body:
I am trying to consistently scrape a single webpage over a period of time to monitor some values and how they are changing within that period

I have no experience in web-scraping and I'm a little confused as to why my scrapy spider runs once and hangs.

I am attempting to run the spider through a 'main.py' script as follows:

timecheck = timeit.default_timer()

while (timecheck) < 30:
    if __name__ == "__main__":
        settings = get_project_settings()
        crawler = CrawlerProcess(settings)
        crawler.crawl(mySpider())
        crawler.start(stop_after_crawl=False)
    time.sleep(5)

print("Finished crawl, time elapsed: %s" % str(timecheck))

My spider script is as follows:

class poeSpider(scrapy.Spider):
    name = "spidername"

    def start_requests(self):
        urls = ["myurl.com/page1"]
        allowed_domains = ["myurl.com"]

        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse, dont_filter=True)

    def parse(self,response):

        datavar = response.xpath("/mydata").extract()
        print(datavar[:3])

PS: A different issue, but related:

I'm also looking to store the data in a list or variable of some kind between scrapes so that I am able to compare the values while the program is running, ideally without any file I/O, which is my reasoning for using a 'main.py' though I'm also at a loss for how to pass the data in the parse function of the spider to anywhere where I can make such comparisons.

Body:
You should keep the logic in spider itself:

import scrapy
import logging
import time
from scrapy import signals, Request

class MySpider(scrapy.Spider):
    start_urls = ['first_url']

    @classmethod
    def from_crawler(cls, crawler, *args, **kwargs):
        spider = super(MySpider, cls).from_crawler(crawler, *args, **kwargs)
        crawler.signals.connect(spider.spider_idle, signals.spider_idle)
        return spider

    def parse(self, response):
        # parse page
        pass

    def spider_idle(self, spider):
        time.sleep(30)
        # after 30 seconds crawl the same page again
        logging.info('starting a crawl again!')
        self.crawler.engine.schedule(Request(self.start_urls[0], dont_filter=True), spider)
        raise DontCloseSpider

In this example when spider goes idle after it will chill out for 30 seconds and then crawl start url again, and keep repeating this untill it's killed or stopped.


问:
Redirect with RewriteRule apache
I want to make an internal redirect with this result:

My old link is like: http://www.example.com/en/some-other-things

My new link should be: http://www.example.com/some-other-things

Basically I want to 'remove' the /en/ and get all the rest of the url in the new url. I've tried this rules in the .htaccess without success:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule "^/en/(.+)" "/$1" [R=301,L]
</IfModule>
</code>```

答:
Make leading slash optional so that rule works both in Apache config as well in .htaccess files. Use .* instead of .+ to ensure you match example.com/en/ as well. Also there is no need to quote the pattern or target.

```<code>RewriteEngine On

RewriteRule ^/?en/(.*)$ /$1 [R=301,L,NC,NE]
</code>```

Title: Redirect with RewriteRule apache

Body:
I want to make an internal redirect with this result:

My old link is like: http://www.example.com/en/some-other-things

My new link should be: http://www.example.com/some-other-things

Basically I want to 'remove' the /en/ and get all the rest of the url in the new url. I've tried this rules in the .htaccess without success:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule "^/en/(.+)" "/$1" [R=301,L]
</IfModule>

Body:
Make leading slash optional so that rule works both in Apache config as well in .htaccess files. Use .* instead of .+ to ensure you match example.com/en/ as well. Also there is no need to quote the pattern or target.

RewriteEngine On

RewriteRule ^/?en/(.*)$ /$1 [R=301,L,NC,NE]


问:
Null pointer exception in suggestions popup window on Samsung Galaxy Android 7
I'm seeing an unusual crash occur regularly in my app, but only on Samsung Galaxy devices running Android 7. Since my app's code doesn't feature in the stacktrace, I'm finding it very hard to track down short of going out and buying one of these expensive devices. Are there any clues to follow here?

It appears to be an internal bug happening inside the suggestions popup associated with an input control, presumably the EditText that features on my app's primary screen. That EditText should not be presenting suggestions, since I'm also using

```<code>searchBox.setImeOptions(EditorInfo.IME_ACTION_SEARCH | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        searchBox.setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
</code>```

The stacktrace follows:

```<code>java.lang.NullPointerException:
    at android.widget.Editor$SuggestionsPopupWindow.initContentView(Editor.java:3729)
    at android.widget.Editor$PinnedPopupWindow.<init>(Editor.java:3390)
    at android.widget.Editor$SuggestionsPopupWindow.<init>(Editor.java:3675)
    at android.widget.Editor.replace(Editor.java:431)
    at android.widget.Editor$3.run(Editor.java:2354)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6776)
    at java.lang.reflect.Method.invoke(Native Method:0)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
</code>```

答:
It seems like a bug in Samsung devices.
Look here:
http://developer.samsung.com/forum/thread/android-app-crash-because-of-null-pointer-exception-on-setting-onclick-listener-in-editor-class/201/309993?boardName=SDK&startId=zzzzz~</p>

Body:
I'm seeing an unusual crash occur regularly in my app, but only on Samsung Galaxy devices running Android 7. Since my app's code doesn't feature in the stacktrace, I'm finding it very hard to track down short of going out and buying one of these expensive devices. Are there any clues to follow here?

It appears to be an internal bug happening inside the suggestions popup associated with an input control, presumably the EditText that features on my app's primary screen. That EditText should not be presenting suggestions, since I'm also using

searchBox.setImeOptions(EditorInfo.IME_ACTION_SEARCH | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        searchBox.setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

The stacktrace follows:

java.lang.NullPointerException:
    at android.widget.Editor$SuggestionsPopupWindow.initContentView(Editor.java:3729)
    at android.widget.Editor$PinnedPopupWindow.<init>(Editor.java:3390)
    at android.widget.Editor$SuggestionsPopupWindow.<init>(Editor.java:3675)
    at android.widget.Editor.replace(Editor.java:431)
    at android.widget.Editor$3.run(Editor.java:2354)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6776)
    at java.lang.reflect.Method.invoke(Native Method:0)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)


问:
If TRUE in one column, change value in other column
I have a character vector: (shortened version shown)

```<code>Unit <- c("e10", "e11", "10e10", "10e11")
</code>```

I want to apply the following condition: if the value start with 'e', replace 'e' with '10e' so that the final vector will look something like this:

```<code>"10e10" "10e11" "10e10" "10e11"
</code>```

I used startsWith() to create a TRUE/FALSE vector:

```<code>startsWith.e <- startsWith(Unit, "e")
</code>```

This gives TRUE TRUE FALSE FALSE.

Lastly, I want to run a for or while loop (or some kind of conditional), so that when startsWith.e is TRUE, values 'e' in Unit are replaced with '10e'.

```<code>while(startsWith.e){
grep("e", "10e", Unit) }
</code>```

However, I get stuck in an infinite loop and using an if statement says it will only evaluate the first statement (and therefore change all cases because it will evaluate TRUE).

Hope someone can help!

答:
(My answer is redundant... @akrun already solved it with sub )

Why not use gsub..?

```<code>Unit <- c("e10", "e11", "10e10", "10e11")
gsub("^e","10e",Unit)
[1] "10e10" "10e11" "10e10" "10e11"
</code>```

Body:
I have a character vector: (shortened version shown)

Unit <- c("e10", "e11", "10e10", "10e11")

I want to apply the following condition: if the value start with 'e', replace 'e' with '10e' so that the final vector will look something like this:

"10e10" "10e11" "10e10" "10e11"

I used startsWith() to create a TRUE/FALSE vector:

startsWith.e <- startsWith(Unit, "e")

This gives TRUE TRUE FALSE FALSE.

Lastly, I want to run a for or while loop (or some kind of conditional), so that when startsWith.e is TRUE, values 'e' in Unit are replaced with '10e'.

while(startsWith.e){
grep("e", "10e", Unit) }

However, I get stuck in an infinite loop and using an if statement says it will only evaluate the first statement (and therefore change all cases because it will evaluate TRUE).

Hope someone can help!

Body:
(My answer is redundant... @akrun already solved it with sub )

Why not use gsub..?

Unit <- c("e10", "e11", "10e10", "10e11")
gsub("^e","10e",Unit)
[1] "10e10" "10e11" "10e10" "10e11"


问:
Infinite Loops and Early Return Statements
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

```<code>int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}
</code>```

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

```<code>int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}
</code>```

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

答:
Technically, there's not much in it, as long as there's no code you're skipping over via the use of the return.

However, your teacher's suggestion is more readable, if only because of the obvious meaning of "ShouldExit".

Body:
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?


问:
PhotoPicker discovery error: Error Domain=PlugInKit Code=13
I'm trying to display an image from the photo library in a UIImageView

The full error is:

2017-06-09 21:55:59.063307+0200 firstapp2.0[12873:1120778] PhotoPicker
  discovery error: Error Domain=PlugInKit Code=13 "query cancelled"
  UserInfo={NSLocalizedDescription=query cancelled}

My code is included below:

```<code>import UIKit

class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    @IBOutlet weak var pic: UIImageView!
    @IBOutlet weak var text: UILabel!

    var chosenImage : UIImage!

    override func viewDidLoad() {
        super.viewDidLoad()
        pic.isUserInteractionEnabled = true;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [AnyHashable: Any]) {
        var chosenImage = info[UIImagePickerControllerEditedImage]
        self.pic!.image = chosenImage as! UIImage
        picker.dismiss(animated: true, completion: nil)
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }

    @IBAction func tap(_ sender: Any) {
        self.text.text = "Kreason"
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    }
}
</code>```

答:
You need to make explicit Objective-C reference: @objc

```<code>@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
    image = chosenImage
    self.performSegue(withIdentifier: "ShowEditView", sender: self)
    dismiss(animated: true, completion: nil)
}
</code>```

Body:
I'm trying to display an image from the photo library in a UIImageView

The full error is:

2017-06-09 21:55:59.063307+0200 firstapp2.0[12873:1120778] PhotoPicker
  discovery error: Error Domain=PlugInKit Code=13 "query cancelled"
  UserInfo={NSLocalizedDescription=query cancelled}

My code is included below:

import UIKit

class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    @IBOutlet weak var pic: UIImageView!
    @IBOutlet weak var text: UILabel!

    var chosenImage : UIImage!

    override func viewDidLoad() {
        super.viewDidLoad()
        pic.isUserInteractionEnabled = true;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [AnyHashable: Any]) {
        var chosenImage = info[UIImagePickerControllerEditedImage]
        self.pic!.image = chosenImage as! UIImage
        picker.dismiss(animated: true, completion: nil)
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }

    @IBAction func tap(_ sender: Any) {
        self.text.text = "Kreason"
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    }
}

Body:
You need to make explicit Objective-C reference: @objc

@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
    image = chosenImage
    self.performSegue(withIdentifier: "ShowEditView", sender: self)
    dismiss(animated: true, completion: nil)
}


问:
url with multiple optional arguments
right now I have a view to show info about some tickets and I'm trying to add a functionality to filter those tickets.

Say I will have 4 filters:

Date

Owner

Category

Status

Category  Status

I want to give the option to use some of those filters, all or none, the thing is I'm kinda lost in how can I make it work in the urls. So far I found that you can add some optional arguments but they appear in some sort of succession like:

/May/Jack/Gas/Accepted

But if I only select 2 filters like /Jack/Accepted/ it grabs the filters incorrectly.

Is there a way I can achieve this? Or some other method I can use instead of this. Ty

答:
Don't try and do this with URL arguments. Instead, use querystring arguments. The URL should be in the form:

```<code>my_path/?date=May&owner=Jack&category=Gas&status=accepted
</code>```

and the URL pattern is just:

```<code>url(r'^my_path/$', views.my_view, 'my_url'),
</code>```

and in the view you can access request.GET['date'] etc.

Title: url with multiple optional arguments

Body:
Don't try and do this with URL arguments. Instead, use querystring arguments. The URL should be in the form:

my_path/?date=May&owner=Jack&category=Gas&status=accepted

and the URL pattern is just:

url(r'^my_path/$', views.my_view, 'my_url'),

and in the view you can access request.GET['date'] etc.


问:
Getting error "The package appears to be corrupt" in Fabric Beta on Android 6
All my beta testers with Android 6 get this error when installing my app from Beta:

App not installed. The package appears to be corrupt

No problems for users with Android 7+. The APK can be dirrectly installed on all devices, including those with error in Beta. The problem appeared a few days ago, configuration of project did not change.

All my users uses latest 1.7.0 Beta app. Project dependencies:

```<code>dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
}

compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
    transitive = true
}
compile('com.crashlytics.sdk.android:crashlytics-ndk:1.1.6@aar') {
    transitive = true
}
</code>```

Any help?

UPD.
I removed android:extractNativeLibs="false" from AndroidManifest.xml and now it works.

答:
I solved the problem removing

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

from the AndroidManifest, until Fabric fixes the issue.

Body:
All my beta testers with Android 6 get this error when installing my app from Beta:

App not installed. The package appears to be corrupt

No problems for users with Android 7+. The APK can be dirrectly installed on all devices, including those with error in Beta. The problem appeared a few days ago, configuration of project did not change.

All my users uses latest 1.7.0 Beta app. Project dependencies:

dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
}

compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
    transitive = true
}
compile('com.crashlytics.sdk.android:crashlytics-ndk:1.1.6@aar') {
    transitive = true
}

Any help?

UPD.
I removed android:extractNativeLibs="false" from AndroidManifest.xml and now it works.

Body:
I solved the problem removing

android:extractNativeLibs="false"

from the AndroidManifest, until Fabric fixes the issue.


问:
Vertically align fixed element which is rotated?
I'm using the position property to position a button which triggers the menu on the left side, I also want it in the center of the page on the y-axis, the problem is that the element is rotated -90deg and there is a whitespace on the left now. I dont want to position it dirty left: -24px; or something. Do someone know why there is a whitespace and if yes, how can I prevent this to happend and solve my issue?

Here is my code, which you can also find in a codepen I've made:

```<code><div class="content-wrapper bg--secondary">
    <div class="menu__button">
        <span class="menu__button__link">
            menu
        </span>
    </div>
</div>

// CSS starts here

.content-wrapper{
    width: 100%;
    height: 100vh;
}

.menu__button{
    width: 150px;
    height: 100px;
    background-color: #000;
    color: #fff;
    position: fixed;
    top: 50%;
    left: 0%;
    transform: translate(0%, -50%) rotate(-90deg);
}

.bg--primary{
    background-color: #2d2d2d;
}
</code>```

Click here to visit the codepen, I think it's easier to understand in the environment.

答:
The easiest way to fix your problem is to adjust the transform-origin of your menu button.

```<code>.menu-button {
    transform: translate(-50%, -50%) rotate(-90deg);
    transform-origin: 100px 25px; //the height of the element and the height - the center position (explanation below);
}
</code>```

I've adjusted it inside your codepen as an example.

As a further explanation as to why this is happening to your menu, your transform-origin is always center center so if your element is 150px wide, it's center is 75px away from the left of the screen.

After you rotate the element, the center is still 75px away from the screen, even though your "new width" is the height of your menu button, which in this case is 100px, with a center of 50px, which leaves 25px of space between your element and the side of the screen.

Body:
I'm using the position property to position a button which triggers the menu on the left side, I also want it in the center of the page on the y-axis, the problem is that the element is rotated -90deg and there is a whitespace on the left now. I dont want to position it dirty left: -24px; or something. Do someone know why there is a whitespace and if yes, how can I prevent this to happend and solve my issue?

Here is my code, which you can also find in a codepen I've made:

            menu

// CSS starts here

.content-wrapper{
    width: 100%;
    height: 100vh;
}

.menu__button{
    width: 150px;
    height: 100px;
    background-color: #000;
    color: #fff;
    position: fixed;
    top: 50%;
    left: 0%;
    transform: translate(0%, -50%) rotate(-90deg);
}

.bg--primary{
    background-color: #2d2d2d;
}

Click here to visit the codepen, I think it's easier to understand in the environment.

Body:
The easiest way to fix your problem is to adjust the transform-origin of your menu button.

.menu-button {
    transform: translate(-50%, -50%) rotate(-90deg);
    transform-origin: 100px 25px; //the height of the element and the height - the center position (explanation below);
}

I've adjusted it inside your codepen as an example.

As a further explanation as to why this is happening to your menu, your transform-origin is always center center so if your element is 150px wide, it's center is 75px away from the left of the screen.

After you rotate the element, the center is still 75px away from the screen, even though your "new width" is the height of your menu button, which in this case is 100px, with a center of 50px, which leaves 25px of space between your element and the side of the screen.


问:
Create a figure of figures with matplotlib
I would like to know if there is a way to combined several figures created with matplotlib in one unique figure.

Most of the existing topics are related to multiple plots within one figure. But here, I have several functions which all create one elaborated figure (not just a plot, the figure itself is a multiple plot with texts, title, legends,...)

So instead of just doing the layout of those several figures using a software like Word, is there a way to directly combined all my figures in one unique figure under python ?

Thank you in advance !

答:
After additional researches, it seems my problem has no easy solution within Matplotlib itself. Multiple figures layout needs external post-processing of plots.

For those having the same problem, here is an interesting link :
Publication-quality figures with matplotlib and svgutils


问:
Option to ignore extra keywords in an sqlalchemy Mapped Class constructor?
Per below, I am trying initialize a sqlalchemy Mapped Class from a python dictionary that has extra keys.  Is it possible to have the Mapped Class automatically ignore the extra keys instead of throwing an error?  Likewise, can the Mapped Class have default values if the keys are not present?

```<code>from sqlalchemy import Column, Integer, String
class User(Base):
     __tablename__ = 'users'

     id = Column(Integer, primary_key=True)
     name = Column(String)
</code>```

And here is the init part:

```<code>my_example_user = {'id'=1, 'name'='john', 'extra_key'= 1234}
User(**my_example_user)
</code>```

Which throws an invalid key error

Thoughts?

答:
Are we guaranteed that the __init__ of the superclass which is in place will never have other desired effects than setting the __dict__ entries? I didn't feel quite comfortable bypassing the superclass call completely, so my attempt at solving this was as follows, passing on only the entries which correspond to column names:

```<code>class User(Base):

    # ...

    def __init__(self, **entries):
        '''Override to avoid TypeError when passed spurious column names'''
        col_names = set([col.name for col in self.__table__.columns])
        superentries = {k : entries[k] for k in col_names.intersection(entries.keys())}
        super().__init__(**superentries)
</code>```

Body:
Per below, I am trying initialize a sqlalchemy Mapped Class from a python dictionary that has extra keys.  Is it possible to have the Mapped Class automatically ignore the extra keys instead of throwing an error?  Likewise, can the Mapped Class have default values if the keys are not present?

from sqlalchemy import Column, Integer, String
class User(Base):
     __tablename__ = 'users'

     id = Column(Integer, primary_key=True)
     name = Column(String)

And here is the init part:

my_example_user = {'id'=1, 'name'='john', 'extra_key'= 1234}
User(**my_example_user)

Which throws an invalid key error

Thoughts?

Body:
Are we guaranteed that the __init__ of the superclass which is in place will never have other desired effects than setting the __dict__ entries? I didn't feel quite comfortable bypassing the superclass call completely, so my attempt at solving this was as follows, passing on only the entries which correspond to column names:

class User(Base):

    # ...

    def __init__(self, **entries):
        '''Override to avoid TypeError when passed spurious column names'''
        col_names = set([col.name for col in self.__table__.columns])
        superentries = {k : entries[k] for k in col_names.intersection(entries.keys())}
        super().__init__(**superentries)


问:
How to remove all but the last 3 parts of FQDN?
I have a list of IP lookups and I wish to remove all but the last 3 parts, so:
98.254.237.114.broad.lyg.js.dynamic.163data.com.cn
would become
163data.com.cn

I have spent hours searching for clues, including parameter substitution, but the closest I got was:

```<code>$ string="98.254.237.114.broad.lyg.js.dynamic.163data.com.cn"
$ string1=${string%.*.*.*}
$ echo $string1
</code>```

Which gives me the inverted answer of:
98.254.237.114.broad.lyg.js.dynamic
which is everything but the last 3 parts.

A script to do a list would be better than just the static example I have here.
Using CentOS 6, I don't mind if it by using sed, cut, awk, whatever.
Any help appreciated.

Thanks, now that I have working answers, may I ask as a follow up to then process the resulting list and if the last part (after last '.') is 3 characters - eg .com .net etc, then to just keep the last 2 parts.

If this is against protocol, please advise how to do a follow up question.

答:
It sounds like this is what you need:

```<code>awk -F'.' '{sub("([^.]+[.]){"NF-3"}","")}1'
</code>```

e.g.

```<code>$ echo "$string" | awk -F'.' '{sub("([^.]+[.]){"NF-3"}","")}1'
163data.com.cn
</code>```

but with just 1 sample input/output it's just a guess.

wrt your followup question, this might be what you're asking for:

```<code>$ echo "$string" | awk -F'.' '{n=(length($NF)==3?2:3); sub("([^.]+[.]){"NF-n"}","")}1'
163data.com.cn

$ echo 'www.google.com' | awk -F'.' '{n=(length($NF)==3?2:3); sub("([^.]+[.]){"NF-n"}","")}1'
google.com
</code>```

Body:
I have a list of IP lookups and I wish to remove all but the last 3 parts, so:
98.254.237.114.broad.lyg.js.dynamic.163data.com.cn
would become
163data.com.cn

I have spent hours searching for clues, including parameter substitution, but the closest I got was:

$ string="98.254.237.114.broad.lyg.js.dynamic.163data.com.cn"
$ string1=${string%.*.*.*}
$ echo $string1

Which gives me the inverted answer of:
98.254.237.114.broad.lyg.js.dynamic
which is everything but the last 3 parts.

A script to do a list would be better than just the static example I have here.
Using CentOS 6, I don't mind if it by using sed, cut, awk, whatever.
Any help appreciated.

Thanks, now that I have working answers, may I ask as a follow up to then process the resulting list and if the last part (after last '.') is 3 characters - eg .com .net etc, then to just keep the last 2 parts.

If this is against protocol, please advise how to do a follow up question.

Body:
It sounds like this is what you need:

awk -F'.' '{sub("([^.]+[.]){"NF-3"}","")}1'

e.g.

$ echo "$string" | awk -F'.' '{sub("([^.]+[.]){"NF-3"}","")}1'
163data.com.cn

but with just 1 sample input/output it's just a guess.

wrt your followup question, this might be what you're asking for:

$ echo "$string" | awk -F'.' '{n=(length($NF)==3?2:3); sub("([^.]+[.]){"NF-n"}","")}1'
163data.com.cn

$ echo 'www.google.com' | awk -F'.' '{n=(length($NF)==3?2:3); sub("([^.]+[.]){"NF-n"}","")}1'
google.com


问:
how to use laravel's validation rule in custom validation rule?
I have input $data =['identifier' = 'xxxxxxxxxx'];, and want to save the encrypt($data['identifier']) to the table info primary id column.

I've to validate before save it. Rule unique:info, id isn't suitable here, so I want to write a custom validation rule. And in the custom validation rule, I encrypt() the value first, then use the unique validation rule.

I know how to write a custom validation rule, but how to use the unique validation rule in my custom validation rule?

答:
Rules "unique" and "exists" use the DatabasePresenceVerifier class. So, you don't need to really extend the unique rule, just access this presence verifier. For instance:

```<code>Validator::extend('encrypted_unique', function ($attribute, $value, $parameters, $validator) {
    list ($table, $column, $ignore_id) = $parameters; // or hard-coded if fixed
    $count = $validator->getPresenceVerifier()->getCount($table, $column, encrypt($value), $ignore_id);
    return $count === 0;
});
</code>```

Then you can use it as usual:

```<code>'identifier' => "encrypted_unique:table,column,$this_id"
</code>```

Body:
Rules "unique" and "exists" use the DatabasePresenceVerifier class. So, you don't need to really extend the unique rule, just access this presence verifier. For instance:

Validator::extend('encrypted_unique', function ($attribute, $value, $parameters, $validator) {
    list ($table, $column, $ignore_id) = $parameters; // or hard-coded if fixed
    $count = $validator->getPresenceVerifier()->getCount($table, $column, encrypt($value), $ignore_id);
    return $count === 0;
});

Then you can use it as usual:

'identifier' => "encrypted_unique:table,column,$this_id"


问:
Multiple $scope.$watch not working in Angular JS
Can anyone explain why only the first $watch below is firing within the same controller? Both the inputs are text boxes with each ng-model assigned. (thanks in advance)</p>

```<code>$scope.$watch('search', function() {
   if ($scope.watch !== ""){
       var filter = "{'name':{'$regex':'(?i).*"+$scope.search+".*'}}";
       fetch(filter);
      };
});

$scope.$watch('id', function() {
    if ($scope.id !== ""){
        var filter = "{'id':{'$regex':'(?i).*"+$scope.id+".*'}}";
        fetch2(filter);
    };
});
</code>```

答:
```<code>//Try this
var deregWatchGroup = $scope.$watchGroup(['1stmodelValue', '2ndmodelvalue'], function (newValues, oldValues) {
         console.log(newValues[0], oldValues[0]); //for 1st model value
         console.log(newValues[1], oldValues[1]); //for 2nd model value
         // here you can handle your stuff
 });
  //destroying watch
 $scope.$on('$destroy', deregWatchGroup);
</code>```

Body:
Can anyone explain why only the first $watch below is firing within the same controller? Both the inputs are text boxes with each ng-model assigned. (thanks in advance)

$scope.$watch('search', function() {
   if ($scope.watch !== ""){
       var filter = "{'name':{'$regex':'(?i).*"+$scope.search+".*'}}";
       fetch(filter);
      };
});

$scope.$watch('id', function() {
    if ($scope.id !== ""){
        var filter = "{'id':{'$regex':'(?i).*"+$scope.id+".*'}}";
        fetch2(filter);
    };
});