问:
Debian 9 + PHP7.0-FPM + NGINX 1.10.3-1 path_info issue
I'm using DigitalOcean Debian 9 + PHP 7.0 + NGINX 1.10.3-1 and trying to install Joomla! CMS, but at the very first installation screen (example.com/installation/index.php) I've noticed a broken image (which is the Joomla logo), and it looks like this:

img src attribute for that image contains "/template/images/joomla.png", but the image is actually located at "/installation/template/images/joomla.png" which means I'm missing the "/installation/" part.

Here is my nginx conf part for the PHP:

```<code>location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
}
</code>```

The "cgi.fix_pathinfo" line at "/etc/php/7.0/fpm/php.ini" is uncommented and the value changed to 0.

And the "/snippets/fastcgi-php.conf" file contains the following:

```<code># regex to split $uri to $fastcgi_script_name and $fastcgi_path
fastcgi_split_path_info ^(.+\.php)(/.+)$;

# Check that the PHP script exists before passing it
try_files $fastcgi_script_name =404;

# Bypass the fact that try_files resets $fastcgi_path_info
# see: http://trac.nginx.org/nginx/ticket/321
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;

fastcgi_index index.php;
include fastcgi.conf;
</code>```

I've noticed that the image is loading once I comment the PATH_INFO part:

```<code>set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;
</code>```

But all my further attempts to figure out the root of the problem are unsuccessful, please help me to fix this.

答:
When you define locations, nginx processes them in order of appearance.
The first rules that matches a file get's executed and the others ignored.
This is how you put some security first, static assets next, and php in the end:</p>

```<code>server {
listen 80;
server_name  example.com;
root   /full/path/to/your/joomla/root/directory;

# allow letsencrypt
location ~ /.well-known/acme-challenge {
allow all;
access_log off;
log_not_found off;
}

# handle some security and logs
location = /favicon.ico {
access_log off;
log_not_found off;
}

location = /robots.txt {
allow all;
access_log off;
log_not_found off;
}

# Deny access to htaccess and other hidden files
location ~ /\. {
deny  all;
access_log off;
log_not_found off;
}

# handle static xml files
location ~* \.(xml)$ {
access_log off;
log_not_found off;
add_header Pragma no-cache;
add_header Cache-Control "no-cache, no-store, must-revalidate, post-check=0, pre-check=0";
gzip off;
}

# include in each host for static content to run with cache and without logs, with CORS enabled (for fonts)
location ~* \.(jpg|jpeg|gif|png|bmp|css|js|ico|txt|pdf|swf|flv|mp4|mp3|eot|ttf|svg|woff|woff2)$ {
add_header Access-Control-Allow-Origin *;
add_header  Cache-Control "public";
access_log off;
log_not_found off;
tcp_nopush on;
sendfile on;
expires   15d;

# Enable gzip
gzip on;
gzip_comp_level 6;
gzip_vary on;
gzip_types text/richtext text/plain text/css text/x-script text/x-component text/x-java-source application/javascript application/x-javascript text/javascript text/js image/x-icon application/x-perl application/x-httpd-cgi text/xml application/xml application/xml+rss application/json multipart/bag multipart/mixed application/xhtml+xml font/ttf font/otf image/svg+xml application/vnd.ms-fontobject application/ttf application/x-ttf application/otf application/x-otf application/truetype application/opentype application/x-opentype application/eot application/font application/font-sfnt;
}

# html
location ~* \.(html|htm|shtml)$ {
max_ranges 0;
etag off;
if_modified_since off;
add_header Last-Modified "";
gzip              on;
gzip_buffers      64 128k;
gzip_comp_level   9;
gzip_http_version 1.1;
gzip_min_length   0;
gzip_types       text/plain;
gzip_vary         off;
}

# allow wordpress, joomla, etc to work properly
location / {
try_files $uri $uri/ /index.php?q=$uri&$args;
}

# handle php
location ~ .php$ {
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
try_files $uri $uri/ /index.php?q=$uri&$args;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_index   index.php;
include fastcgi_params;
fastcgi_param PATH_INFO         $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED   $document_root$fastcgi_path_info;
fastcgi_param QUERY_STRING      $query_string;
fastcgi_param REQUEST_METHOD    $request_method;
fastcgi_param CONTENT_TYPE      $content_type;
fastcgi_param CONTENT_LENGTH    $content_length;
fastcgi_param SCRIPT_NAME       $fastcgi_script_name;
fastcgi_param REQUEST_URI       $request_uri;
fastcgi_param DOCUMENT_URI      $document_uri;
fastcgi_param DOCUMENT_ROOT     $document_root;
fastcgi_param SERVER_PROTOCOL   $server_protocol;
fastcgi_param REQUEST_SCHEME    $scheme;
fastcgi_param HTTPS             $https if_not_empty;
fastcgi_param HTTP_PROXY        "";
fastcgi_param REMOTE_ADDR       $remote_addr;
fastcgi_param REMOTE_PORT       $remote_port;
fastcgi_param SERVER_ADDR       $server_addr;
fastcgi_param HTTP_CF_IPCOUNTRY   $http_cf_ipcountry;
fastcgi_param SCRIPT_FILENAME $request_filename;
}

}
</code>```

Body:
I'm using DigitalOcean Debian 9 + PHP 7.0 + NGINX 1.10.3-1 and trying to install Joomla! CMS, but at the very first installation screen (example.com/installation/index.php) I've noticed a broken image (which is the Joomla logo), and it looks like this:

img src attribute for that image contains "/template/images/joomla.png", but the image is actually located at "/installation/template/images/joomla.png" which means I'm missing the "/installation/" part.

Here is my nginx conf part for the PHP:

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
}

The "cgi.fix_pathinfo" line at "/etc/php/7.0/fpm/php.ini" is uncommented and the value changed to 0.

And the "/snippets/fastcgi-php.conf" file contains the following:

# regex to split $uri to $fastcgi_script_name and $fastcgi_path
fastcgi_split_path_info ^(.+\.php)(/.+)$;

# Check that the PHP script exists before passing it
try_files $fastcgi_script_name =404;

# Bypass the fact that try_files resets $fastcgi_path_info
# see: http://trac.nginx.org/nginx/ticket/321
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;

fastcgi_index index.php;
include fastcgi.conf;

I've noticed that the image is loading once I comment the PATH_INFO part:

set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;

But all my further attempts to figure out the root of the problem are unsuccessful, please help me to fix this.

Body:
When you define locations, nginx processes them in order of appearance.
The first rules that matches a file get's executed and the others ignored.
This is how you put some security first, static assets next, and php in the end:

server {
listen 80;
server_name  example.com;
root   /full/path/to/your/joomla/root/directory;

# allow letsencrypt
location ~ /.well-known/acme-challenge {
allow all;
access_log off;
log_not_found off;
}

# handle some security and logs
location = /favicon.ico {
access_log off;
log_not_found off;
}

location = /robots.txt {
allow all;
access_log off;
log_not_found off;
}

# Deny access to htaccess and other hidden files
location ~ /\. {
deny  all;
access_log off;
log_not_found off;
}

# handle static xml files
location ~* \.(xml)$ {
access_log off;
log_not_found off;
add_header Pragma no-cache;
add_header Cache-Control "no-cache, no-store, must-revalidate, post-check=0, pre-check=0";
gzip off;
}

# include in each host for static content to run with cache and without logs, with CORS enabled (for fonts)
location ~* \.(jpg|jpeg|gif|png|bmp|css|js|ico|txt|pdf|swf|flv|mp4|mp3|eot|ttf|svg|woff|woff2)$ {
add_header Access-Control-Allow-Origin *;
add_header  Cache-Control "public";
access_log off;
log_not_found off;
tcp_nopush on;
sendfile on;
expires   15d;

# Enable gzip
gzip on;
gzip_comp_level 6;
gzip_vary on;
gzip_types text/richtext text/plain text/css text/x-script text/x-component text/x-java-source application/javascript application/x-javascript text/javascript text/js image/x-icon application/x-perl application/x-httpd-cgi text/xml application/xml application/xml+rss application/json multipart/bag multipart/mixed application/xhtml+xml font/ttf font/otf image/svg+xml application/vnd.ms-fontobject application/ttf application/x-ttf application/otf application/x-otf application/truetype application/opentype application/x-opentype application/eot application/font application/font-sfnt;
}

# html
location ~* \.(html|htm|shtml)$ {
max_ranges 0;
etag off;
if_modified_since off;
add_header Last-Modified "";
gzip              on;
gzip_buffers      64 128k;
gzip_comp_level   9;
gzip_http_version 1.1;
gzip_min_length   0;
gzip_types       text/plain;
gzip_vary         off;
}

# allow wordpress, joomla, etc to work properly
location / {
try_files $uri $uri/ /index.php?q=$uri&$args;
}

# handle php
location ~ .php$ {
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
try_files $uri $uri/ /index.php?q=$uri&$args;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_index   index.php;
include fastcgi_params;
fastcgi_param PATH_INFO         $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED   $document_root$fastcgi_path_info;
fastcgi_param QUERY_STRING      $query_string;
fastcgi_param REQUEST_METHOD    $request_method;
fastcgi_param CONTENT_TYPE      $content_type;
fastcgi_param CONTENT_LENGTH    $content_length;
fastcgi_param SCRIPT_NAME       $fastcgi_script_name;
fastcgi_param REQUEST_URI       $request_uri;
fastcgi_param DOCUMENT_URI      $document_uri;
fastcgi_param DOCUMENT_ROOT     $document_root;
fastcgi_param SERVER_PROTOCOL   $server_protocol;
fastcgi_param REQUEST_SCHEME    $scheme;
fastcgi_param HTTPS             $https if_not_empty;
fastcgi_param HTTP_PROXY        "";
fastcgi_param REMOTE_ADDR       $remote_addr;
fastcgi_param REMOTE_PORT       $remote_port;
fastcgi_param SERVER_ADDR       $server_addr;
fastcgi_param HTTP_CF_IPCOUNTRY   $http_cf_ipcountry;
fastcgi_param SCRIPT_FILENAME $request_filename;
}

}


来源: stackexchange

问:
How Can I Only Allow Uniform Resizing in a WPF Window?
I don't want my window to be resized either "only horizontally" or "only vertically." Is there a property I can set on my window that can enforce this, or is there a nifty code-behind trick I can use?</p>

答:
In the code sample:

```<code>if (sizeInfo.WidthChanged)
{
    this.Width = sizeInfo.NewSize.Height * aspectRatio;
}
else
{
    this.Height = sizeInfo.NewSize.Width * aspectRatio;
}
</code>```

I believe the second computation should be:

```<code>this.Height = sizeInfo.NewSize.Width * (1/aspectRatio);
</code>```

I made a variation of this work in a "SizeChanged" event handler.  Since I wanted the width to be the controlling dimension, I simply forced the height to match to it with a computation of the form:

```<code>if (aspectRatio > 0)
// enforce aspect ratio by restricting height to stay in sync with width.
this.Height = this.ActualWidth * (1 / aspectRatio);
</code>```

You may note the check for an aspectRatio > 0, ... I did this because I found that it was tending to call my handlers that did the resizing before the "Load" method had even assigned the aspectRatio.

OwnerDisplayName: Pwninstein

ContentLicense: CC BY-SA 2.5

Body:
In the code sample:

if (sizeInfo.WidthChanged)
{
    this.Width = sizeInfo.NewSize.Height * aspectRatio;
}
else
{
    this.Height = sizeInfo.NewSize.Width * aspectRatio;
}

I believe the second computation should be:

this.Height = sizeInfo.NewSize.Width * (1/aspectRatio);

I made a variation of this work in a "SizeChanged" event handler.  Since I wanted the width to be the controlling dimension, I simply forced the height to match to it with a computation of the form:

if (aspectRatio > 0)
// enforce aspect ratio by restricting height to stay in sync with width.
this.Height = this.ActualWidth * (1 / aspectRatio);

You may note the check for an aspectRatio > 0, ... I did this because I found that it was tending to call my handlers that did the resizing before the "Load" method had even assigned the aspectRatio.

ContentLicense: CC BY-SA 3.0


问:
Using callback for ajax
I want to prevent a function to execute before get a value from ajax, I'm trying using async:false it works but deprecated. So, I'm using callback like what I found on internet. It's works too, but the browser still tell me if the callback is not the function. Here's my code

function User() {
    this.nama;
    this.nis;
    this.pass;
    this.role;
    this.url = "http://localhost/elearning-web/";

    this.Login = function(call) {
        $.ajax({
            type:"POST",url:this.url+"dologin.php",data:"nis="+this.nis+"&pass="+this.pass,
            success:function(e){
                call(e);
            }
        });
    }
}```

When I check the console.log it's show what I want to display, but the browser tell me if the call (callback) is not a function. Thanks in advance

答:
The call argument, that you are passing to the method Login must be a function, for example:

```<code>var call = somethingFunction(){ return 'called!';}
var user = new User();
user.Login(call)
</code>```

Title: Using callback for ajax

Body:
I want to prevent a function to execute before get a value from ajax, I'm trying using async:false it works but deprecated. So, I'm using callback like what I found on internet. It's works too, but the browser still tell me if the callback is not the function. Here's my code

function User() {
    this.nama;
    this.nis;
    this.pass;
    this.role;
    this.url = "http://localhost/elearning-web/";

    this.Login = function(call) {
        $.ajax({
            type:"POST",url:this.url+"dologin.php",data:"nis="+this.nis+"&pass="+this.pass,
            success:function(e){
                call(e);
            }
        });
    }
}

When I check the console.log it's show what I want to display, but the browser tell me if the call (callback) is not a function. Thanks in advance

Body:
The call argument, that you are passing to the method Login must be a function, for example:

var call = somethingFunction(){ return 'called!';}
var user = new User();
user.Login(call)


问:
Broadcasting and Fetch Data On UART
I have a computer (that use as server) and several board with Atmega microcontroller Something like:

The computer connect to board on UART & RS485 (with a USB to RS485 converter)(I have limitation that lead to I could not use ModBus). I want to broadcast a message from server over bus and fetch the ID from of each board (Board ID is 4 digit).

When the boards receive broadcast message and try to send their own ID and the server receive some fake ID and I think it related to Collisions problem when all boards want  to send data in one time.

After I search about this problem found a way that put a constant in each board that save a special delay for send data and when board receive broadcast message send ID with that delay...in this way it work fine and I dont see the Collisions but have some problem:

May be the delay number of 2 board be same.

Good way for small count of board.

Extra process when want to install board on bus.

Anybody know with this problem and could help me how to solve this problem with better solution?

答: It will probably take longer, but here is another way to do it.  First, design your protocol so that each command contains (or an can contain) an ID, and boards only respond to commands for their ID.  Then, on your host, you would iterate through each of the possible IDs and send a simple command to each of them.  If you get a response, you know there is a board with that ID.  If you don't get a response after some period of time, you know there is no board there.</p>

Title: Broadcasting and Fetch Data On UART


问:
moving items of list up and down
Let's say we have a list of items. And, we want to allow users to control their order by clicking (down-arrow) to lower the order of item one level. And, doing the same to set the order one level higher.

views.py

```<code>def item_up(request, item_id):
    item = get_object_or_404(Item, id=item_id)
    swap_order = item.order - 1
    swap = get_object_or_404(Item, order=swap_order)
    item.order += 1000
    item.save()
    swap.order += 1
    item.order -= 1001
    swap.save()
    item.save()
    return redirect(request.META['HTTP_REFERER'])

def item_down(request, item_id):
    item = get_object_or_404(Item, id=item_id)
    swap_order = item.order + 1
    swap = get_object_or_404(Item, order=swap_order)
    item.order -= 1000
    item.save()
    swap.order -= 1
    item.order += 1001
    swap.save()
    item.save()
    return redirect(request.META['HTTP_REFERER'])
</code>```

this way is working except when I have only two items it shows me an error.

```<code>No Item matches the given query.
</code>```

Any Idea?

答:
try:    </p>

```<code>def item_up(request, item_id):
    item = Item.objects.get(id=item_id)
    swap_order = item.order - 1
    if Item.objects.filter(order=swap_order).exists:
        swap = Item.objects.get(order=swap_order)
        item.order += 1000
        item.save()
        swap.order += 1
        item.order -= 1001
        swap.save()
        item.save()
    return redirect(request.META['HTTP_REFERER'])

def item_down(request, item_id):
    item = Item.objects.get(id=item_id)
    swap_order = item.order + 1
    if Item.objects.filter(order=swap_order).exists:
       swap = Item.objects.get(order=swap_order)
       item.order -= 1000
       item.save()
       swap.order -= 1
       item.order += 1001
       swap.save()
       item.save()
    return redirect(request.META['HTTP_REFERER'])
</code>```

Title: moving items of list up and down

Body:
Let's say we have a list of items. And, we want to allow users to control their order by clicking (down-arrow) to lower the order of item one level. And, doing the same to set the order one level higher.

views.py

def item_up(request, item_id):
    item = get_object_or_404(Item, id=item_id)
    swap_order = item.order - 1
    swap = get_object_or_404(Item, order=swap_order)
    item.order += 1000
    item.save()
    swap.order += 1
    item.order -= 1001
    swap.save()
    item.save()
    return redirect(request.META['HTTP_REFERER'])

def item_down(request, item_id):
    item = get_object_or_404(Item, id=item_id)
    swap_order = item.order + 1
    swap = get_object_or_404(Item, order=swap_order)
    item.order -= 1000
    item.save()
    swap.order -= 1
    item.order += 1001
    swap.save()
    item.save()
    return redirect(request.META['HTTP_REFERER'])

this way is working except when I have only two items it shows me an error.

No Item matches the given query.

Any Idea?

Body:
try:

def item_up(request, item_id):
    item = Item.objects.get(id=item_id)
    swap_order = item.order - 1
    if Item.objects.filter(order=swap_order).exists:
        swap = Item.objects.get(order=swap_order)
        item.order += 1000
        item.save()
        swap.order += 1
        item.order -= 1001
        swap.save()
        item.save()
    return redirect(request.META['HTTP_REFERER'])

def item_down(request, item_id):
    item = Item.objects.get(id=item_id)
    swap_order = item.order + 1
    if Item.objects.filter(order=swap_order).exists:
       swap = Item.objects.get(order=swap_order)
       item.order -= 1000
       item.save()
       swap.order -= 1
       item.order += 1001
       swap.save()
       item.save()
    return redirect(request.META['HTTP_REFERER'])


问:
Firebase Cloud Functions Database Trigger 'onCreate is not a function'
I want to use onCreate method instead of onWrite for the sake of efficiency but I face that error:

functions.database.ref(...).onCreate is not a function.

However, there seems to be a function as mentioned in the doc https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder#onCreate

My code starts as follows:

```<code>const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.manager = functions.database.ref('some_ref')
    .onCreate(event =>{
</code>```

I am looking forward to your helps.
Thanks in advance.

答:
Update:  In a comment on the question, Firebaser Doug Stevenson indicates that running  npm upgrade in the project's functions folder is the simpler way to update to the latest version.

I don't find any documentation for how to update to the latest version of firebase-functions.  Following the general guidelines described here, go to your project's functions directory and enter this command:

```<code>npm install --save firebase-functions
</code>```

You can then look in the package.json file to see the versions installed.  The new version of firebase-functions that contains the new triggers is 0.5.9

Body:
I want to use onCreate method instead of onWrite for the sake of efficiency but I face that error:

functions.database.ref(...).onCreate is not a function.

However, there seems to be a function as mentioned in the doc https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder#onCreate

My code starts as follows:

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.manager = functions.database.ref('some_ref')
    .onCreate(event =>{

I am looking forward to your helps.
Thanks in advance.

Body:
Update:  In a comment on the question, Firebaser Doug Stevenson indicates that running  npm upgrade in the project's functions folder is the simpler way to update to the latest version.

I don't find any documentation for how to update to the latest version of firebase-functions.  Following the general guidelines described here, go to your project's functions directory and enter this command:

npm install --save firebase-functions

You can then look in the package.json file to see the versions installed.  The new version of firebase-functions that contains the new triggers is 0.5.9


问:
Disable css on cretin pages
I'm using an angular based website so each page uses the same global header.

I'm using

```<code><link id="first_style" rel="rel="stylesheet"
  href="/css/jquery.dataTables.min.css" href="#" disabled />
</code>```

But it is messing up tables I have on other pages. Is there anything I can put in my HTML template to block this on a particular page. Please take into consideration that the HTML file that it is messing up has no header as the header is in the main index.php file. So what ever can be done to disable will have to be in the main body.

I had a look at the follwing

```<code> <script type="text/javascript">
        window.onload = function()
        {
            document.getElementById('first_style').removeAttribute('disabled');
        }
    </script>
</code>```

Is there a way of instead of original attribute being disabled can i mark as enabled then replace the attribute with disabled using a mofified version of the above js. So instead of .removeAttribute('enabled'); can i replace with disabled.

答: Create another .css file, copy the the code from jquery.dataTables.min.css and then remove the selectors that you want to disable. The only way you can disable a certain .css file is in for example Chrome Dev Tools but that's only for development, it doesn't apply on the production build, it's only intended for testing.

Title: Disable css on cretin pages

Body:
I'm using an angular based website so each page uses the same global header.

I'm using

<link id="first_style" rel="rel="stylesheet"
  href="/css/jquery.dataTables.min.css" href="#" disabled />

But it is messing up tables I have on other pages. Is there anything I can put in my HTML template to block this on a particular page. Please take into consideration that the HTML file that it is messing up has no header as the header is in the main index.php file. So what ever can be done to disable will have to be in the main body.

I had a look at the follwing

Is there a way of instead of original attribute being disabled can i mark as enabled then replace the attribute with disabled using a mofified version of the above js. So instead of .removeAttribute('enabled'); can i replace with disabled.


答:
You have to declarate a call function the pass it to User.Login(call);

function call1(e) {
  console.log('Hi, from call ', e);
}

function User1() {

    this.Login = function(call) {
        // simulating $.ajax http request ;]
        setTimeout(function() {
          call(';)');
        }, 2000);
    }
}

var user1 = new User1();
user1.Login(call);

// in your case
function call(e) {
  console.log('Hi, from call ', e);
}

function User() {
    this.nama;
    this.nis;
    this.pass;
    this.role;
    this.url = "http://localhost/elearning-web/";

    this.Login = function(call) {
        $.ajax({
            type:"POST",
            url:this.url+"dologin.php",
            data:"nis="+this.nis+"&pass="+this.pass,
            success:function(e){
                call(e);
            }
        });
    }
}

var user = new User();
user.Login(call);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: Using callback for ajax

Body:
You have to declarate a call function the pass it to User.Login(call);

function call1(e) {
  console.log('Hi, from call ', e);
}

function User1() {

    this.Login = function(call) {
        // simulating $.ajax http request ;]
        setTimeout(function() {
          call(';)');
        }, 2000);
    }
}

var user1 = new User1();
user1.Login(call);

// in your case
function call(e) {
  console.log('Hi, from call ', e);
}

function User() {
    this.nama;
    this.nis;
    this.pass;
    this.role;
    this.url = "http://localhost/elearning-web/";

    this.Login = function(call) {
        $.ajax({
            type:"POST",
            url:this.url+"dologin.php",
            data:"nis="+this.nis+"&pass="+this.pass,
            success:function(e){
                call(e);
            }
        });
    }
}

var user = new User();
user.Login(call);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Brew remove mysql error
I want to completely remove MySQL from my mac (El Capitan).

I installed homebrew and tried to remove MySQL, but I get the error:

```<code>Error: No such keg: /usr/local/Cellar/mysql
</code>```

答: I solved this problem by manually going to /usr/local directory. There was one mysql folder, I deleted. Also, delete my.cnf file, should be present  It started working after that. If that too doesn't work, re-install homebrew, that will rectify symlink problem.</p>

Title: Brew remove mysql error

Body:
I want to completely remove MySQL from my mac (El Capitan).

I installed homebrew and tried to remove MySQL, but I get the error:

Error: No such keg: /usr/local/Cellar/mysql


问:
Group duplicate column IDs in pandas dataframe
Now there are a lot of similar questions but most of them answer how to delete the duplicate columns. However, I want to know how can I make a list of tuples where each tuple contains the column names of duplicate columns. I am assuming that each column has a unique name. Just to further illustrate my question:

```<code>df = pd.DataFrame({'A': [1, 2, 3, 4, 5],'B': [2, 4, 2, 1, 9],
                   'C': [1, 2, 3, 4, 5],'D': [2, 4, 2, 1, 9],
                   'E': [3, 4, 2, 1, 2],'F': [1, 1, 1, 1, 1]},
                   index = ['a1', 'a2', 'a3', 'a4', 'a5'])
</code>```

then I want the output:

```<code>[('A', 'C'), ('B', 'D')]
</code>```

And if you are feeling great today then also extend the same question to rows. How to get a list of tuples where each tuple contains duplicate rows.

答:
Not using panda, just pure python :

```<code>data = {'A': [1, 2, 3, 4, 5],'B': [2, 4, 2, 1, 9],
        'C': [1, 2, 3, 4, 5],'D': [2, 4, 2, 1, 9],
        'E': [3, 4, 2, 1, 2],'F': [1, 1, 1, 1, 1]}
from collections import defaultdict

deduplicate = defaultdict(list)

for key, items in data.items():
    deduplicate[tuple(items)].append(key)  # cast to tuple because they are hashables but lists are not.

duplicates = list()
for vector, letters in deduplicate.items():
    if len(letters) > 1:
        duplicates.append(letters)

print(duplicates)
</code>```

Using pandas :

```<code>import pandas

df = pandas.DataFrame(data)
duplicates = []

dedup2 = defaultdict(list)

for key in df.columns:
    dedup2[tuple(df[key])].append(key)

duplicates = list()
for vector, letters in dedup2.items():
    if len(letters) > 1:
        duplicates.append(letters)

print(duplicates)
</code>```

Not really nice, but may be quicker since everything is done in one iteration over the data.

```<code>dedup2 = defaultdict(list)

duplicates = {}

for key in df.columns:
    astup = tuple(df[key])
    duplic = dedup2[astup]
    duplic.append(key)
    if len(duplic) > 1:
        duplicates[astup] = duplic

duplicates = duplicates.values()
print(duplicates)
</code>```

Body:
Now there are a lot of similar questions but most of them answer how to delete the duplicate columns. However, I want to know how can I make a list of tuples where each tuple contains the column names of duplicate columns. I am assuming that each column has a unique name. Just to further illustrate my question:

df = pd.DataFrame({'A': [1, 2, 3, 4, 5],'B': [2, 4, 2, 1, 9],
                   'C': [1, 2, 3, 4, 5],'D': [2, 4, 2, 1, 9],
                   'E': [3, 4, 2, 1, 2],'F': [1, 1, 1, 1, 1]},
                   index = ['a1', 'a2', 'a3', 'a4', 'a5'])

then I want the output:

[('A', 'C'), ('B', 'D')]

And if you are feeling great today then also extend the same question to rows. How to get a list of tuples where each tuple contains duplicate rows.

Body:
Not using panda, just pure python :

data = {'A': [1, 2, 3, 4, 5],'B': [2, 4, 2, 1, 9],
        'C': [1, 2, 3, 4, 5],'D': [2, 4, 2, 1, 9],
        'E': [3, 4, 2, 1, 2],'F': [1, 1, 1, 1, 1]}
from collections import defaultdict

deduplicate = defaultdict(list)

for key, items in data.items():
    deduplicate[tuple(items)].append(key)  # cast to tuple because they are hashables but lists are not.

duplicates = list()
for vector, letters in deduplicate.items():
    if len(letters) > 1:
        duplicates.append(letters)

print(duplicates)

Using pandas :

import pandas

df = pandas.DataFrame(data)
duplicates = []

dedup2 = defaultdict(list)

for key in df.columns:
    dedup2[tuple(df[key])].append(key)

duplicates = list()
for vector, letters in dedup2.items():
    if len(letters) > 1:
        duplicates.append(letters)

print(duplicates)

Not really nice, but may be quicker since everything is done in one iteration over the data.

dedup2 = defaultdict(list)

duplicates = {}

for key in df.columns:
    astup = tuple(df[key])
    duplic = dedup2[astup]
    duplic.append(key)
    if len(duplic) > 1:
        duplicates[astup] = duplic

duplicates = duplicates.values()
print(duplicates)


问:
mongodb node - find documents by array of json objects
I'm using mongodb in a nodejs project, in which I have a collection of users :

```<code>{ "_id" : ObjectId("1"), "firstName": "John", "lastName" : "Doe", "age":20 }
{ "_id" : ObjectId("2"), "firstName": "Jane", "lastName" : "Doe", "age":22 }
{ "_id" : ObjectId("3"), "firstName": "Bob", "lastName" : "Smith","age": 32 }
{ "_id" : ObjectId("4"), "firstName": "John", "lastName" : "Smith","age":40}
{ "_id" : ObjectId("5"), "firstName": "John", "lastName" : "Deer","age":66}
</code>```

I'd like a query to return an array of document ids matching the array of users by their first and last name ordered by the array I've given here

This is what I'm trying to fiddle with:

```<code>var usersToFind = [
  { firstName: "John", lastName: "Smith"},
  { firstName: "John", lastName:"Doe"}
];

db.collection('users').then(users => users.aggregate([
   { $match : { /* what to put here? */ } },
   { $addFields : { '__order' : { $indexOfArray : [usersToFind, /* Missing here something */} } },
   { $sort : { '__order' : 1 } }
]).toArray(results => {
  console.log(results);
  // Should print ["ObjectId(4)", "ObjectId(1)"];
});
</code>```

I'm probably missing something fundamental about how to work with mongodb due to my limited knowledge of it.

I'd be grateful if you could help me solve the query or show me a better way to achieve it.

I could always iterate my usersToFind array and find documents one by one, but I'd like to use a single query here. Another approach is to use $or and $and

Thank you

答:
You can use find(). Here is an example:

```<code>db.collection('users').find(
   {
     "firstName": "John",
     "lastName": "Doe"
   }
)
</code>```

Here is the documentation.

Body:
I'm using mongodb in a nodejs project, in which I have a collection of users :

{ "_id" : ObjectId("1"), "firstName": "John", "lastName" : "Doe", "age":20 }
{ "_id" : ObjectId("2"), "firstName": "Jane", "lastName" : "Doe", "age":22 }
{ "_id" : ObjectId("3"), "firstName": "Bob", "lastName" : "Smith","age": 32 }
{ "_id" : ObjectId("4"), "firstName": "John", "lastName" : "Smith","age":40}
{ "_id" : ObjectId("5"), "firstName": "John", "lastName" : "Deer","age":66}

I'd like a query to return an array of document ids matching the array of users by their first and last name ordered by the array I've given here

This is what I'm trying to fiddle with:

var usersToFind = [
  { firstName: "John", lastName: "Smith"},
  { firstName: "John", lastName:"Doe"}
];

db.collection('users').then(users => users.aggregate([
   { $match : { /* what to put here? */ } },
   { $addFields : { '__order' : { $indexOfArray : [usersToFind, /* Missing here something */} } },
   { $sort : { '__order' : 1 } }
]).toArray(results => {
  console.log(results);
  // Should print ["ObjectId(4)", "ObjectId(1)"];
});

I'm probably missing something fundamental about how to work with mongodb due to my limited knowledge of it.

I'd be grateful if you could help me solve the query or show me a better way to achieve it.

I could always iterate my usersToFind array and find documents one by one, but I'd like to use a single query here. Another approach is to use $or and $and

Thank you

Body:
You can use find(). Here is an example:

db.collection('users').find(
   {
     "firstName": "John",
     "lastName": "Doe"
   }
)

Here is the documentation.


问:
internationalization in JSF with ResourceBundle entries which are loaded from database
I'm working on a Java EE6 project using JPA/EJB/JSF and I'm having some trouble designing multiple language support for entities. There are three relevant entities:

Language (has id)

Competence (has id)

CompetenceName (has Competence reference, Language reference and a String)

Competence has a one-to-many reference to CompetenceName implemented with a Map, containing one object for every Language that there exists a name for a Competence. Note that competences are created dynamically and their names can thus not exist in a resource bundle.

When listing the Competences on a web page, I want them to show with the language of the currently logged in user, this is stored in a Session Scoped Managed Bean.

Is there any good way to accomplish this without breaking good MVC design? My first idea was to get the session scoped bean directly from a "getName" method in the Competence entity via FacesContext, and look in the map of CompetenceNames for it as following:

```<code>public class Competence
{
...
@MapKey(name="language")
@OneToMany(mappedBy="competence", cascade=CascadeType.ALL, orphanRemoval=true)
private Map<Language, CompetenceName> competenceNames;

public String getName(String controller){
    FacesContext context = FacesContext.getCurrentInstance();
    ELResolver resolver = context.getApplication().getELResolver();
    SessionController sc = (SessionController)resolver.getValue(context.getELContext(), null, "sessionController");
    Language language = sc.getLoggedInUser().getLanguage();
    if(competenceNames.get(language) != null)
        return competenceNames.get(language).getName();
    else
        return "resource missing";
}
</code>```

This solution feels extremly crude since the entity relies on the Controller layer, and have to fetch a session controller every time I want its name. A more MVC compliant solution would be to take a Language parameter, but this means that every single call from JSF will have to include the language fetched from the session scoped managed bean which does not feel like a good solution either.

Does anyone have any thoughts or design patterns for this issue?

答:
I would move the language specific part from your model into recource bundles. Just model Competence, Language and User. If a user requests a page, you display his competence and lookup the language specific competence (CompetenceName) from the recource bundle.

I searched for sample code to get you started and found this, see Listing 19.16 customerDetails.jsp.

Something like:

```<code><fmt:message key="${competence}" />
</code>```

Body:
I'm working on a Java EE6 project using JPA/EJB/JSF and I'm having some trouble designing multiple language support for entities. There are three relevant entities:

Language (has id)

Competence (has id)

CompetenceName (has Competence reference, Language reference and a String)

Competence has a one-to-many reference to CompetenceName implemented with a Map, containing one object for every Language that there exists a name for a Competence. Note that competences are created dynamically and their names can thus not exist in a resource bundle.

When listing the Competences on a web page, I want them to show with the language of the currently logged in user, this is stored in a Session Scoped Managed Bean.

Is there any good way to accomplish this without breaking good MVC design? My first idea was to get the session scoped bean directly from a "getName" method in the Competence entity via FacesContext, and look in the map of CompetenceNames for it as following:

public class Competence
{
...
@MapKey(name="language")
@OneToMany(mappedBy="competence", cascade=CascadeType.ALL, orphanRemoval=true)
private Map<Language, CompetenceName> competenceNames;

public String getName(String controller){
    FacesContext context = FacesContext.getCurrentInstance();
    ELResolver resolver = context.getApplication().getELResolver();
    SessionController sc = (SessionController)resolver.getValue(context.getELContext(), null, "sessionController");
    Language language = sc.getLoggedInUser().getLanguage();
    if(competenceNames.get(language) != null)
        return competenceNames.get(language).getName();
    else
        return "resource missing";
}

This solution feels extremly crude since the entity relies on the Controller layer, and have to fetch a session controller every time I want its name. A more MVC compliant solution would be to take a Language parameter, but this means that every single call from JSF will have to include the language fetched from the session scoped managed bean which does not feel like a good solution either.

Does anyone have any thoughts or design patterns for this issue?

Body:
I would move the language specific part from your model into recource bundles. Just model Competence, Language and User. If a user requests a page, you display his competence and lookup the language specific competence (CompetenceName) from the recource bundle.

I searched for sample code to get you started and found this, see Listing 19.16 customerDetails.jsp.

Something like:

<fmt:message key="${competence}" />


问:
Uncaught TypeError: e.map is not a function after updating to angular 4
after updating to angular 4 i getting this errormessaging. i dont know where it comes from and i dont understand what exactly chrome will say to me. </p>

```<code>Uncaught TypeError: e.map is not a function
at t.parameters (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51)
at e.parameters (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51)
at t.getDependenciesMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at t.getTypeMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
at Array.forEach (<anonymous>)
at t.getProvidersMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at t.getNgModuleMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
at Array.forEach (<anonymous>)
t.parameters    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51
e.parameters    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51
t.getDependenciesMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getTypeMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
(anonymous) @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getProvidersMetadata  @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getNgModuleMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
(anonymous) @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getNgModuleMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t._compileComponents    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:122
t._compileModuleAndComponents   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:121
t.compileModuleAsync    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:121
e._bootstrapModuleWithZone  @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:59
e.bootstrapModule   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:59
bootApplication @   boot-client.ts:17
t.invokeTask    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:201
n.runTask   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:201
invoke  @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:201
</code>```

答:
Ok. I tried it again. it is a little bit complex. With your example i create an angular app only. But my project is an asp.core with angular. The angular only app works fine at start. I removed all my customizings in my ClientApp-Folder, its the same of src\app. but the error is the same.
I see in the angular2 app the tsconfig.json but in my visual studio project i don't find the file.</p>

Body:
after updating to angular 4 i getting this errormessaging. i dont know where it comes from and i dont understand what exactly chrome will say to me.

Uncaught TypeError: e.map is not a function
at t.parameters (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51)
at e.parameters (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51)
at t.getDependenciesMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at t.getTypeMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
at Array.forEach (<anonymous>)
at t.getProvidersMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at t.getNgModuleMetadata (vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120)
at vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
at Array.forEach (<anonymous>)
t.parameters    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51
e.parameters    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:51
t.getDependenciesMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getTypeMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
(anonymous) @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getProvidersMetadata  @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getNgModuleMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
(anonymous) @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t.getNgModuleMetadata   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:120
t._compileComponents    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:122
t._compileModuleAndComponents   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:121
t.compileModuleAsync    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:121
e._bootstrapModuleWithZone  @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:59
e.bootstrapModule   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:59
bootApplication @   boot-client.ts:17
t.invokeTask    @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:201
n.runTask   @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:201
invoke  @   vendor.js?v=ieYBBzkkpOeg5eS28e4kMG5hTCbhSNE8T-M4VYaekSA:201


问:
Doctrine subquery on FROM statement, Symfony 3
New to Doctrine and trying to convert the MySQL query below to queryBuilder.

```<code>SELECT COUNT(t2.user_id) FROM(
    SELECT t2.* FROM logins t2
        WHERE t2.login_time >= DATE_SUB(NOW(),INTERVAL 5 HOUR)
        LIMIT 10
    ) t2
WHERE t2.is_success = 1
</code>```

I've seen a few examples of subquery on the WHERE clause here on SO and attempted to adapt it as per below, but that does not really work.

```<code>        $sub = $this->createQueryBuilder('l')
        ->select('l')
        ->where('l.loginTime >= :date
            and l.userId = :user_id')
        ->setParameters( $parameters )
        ->getDQL();

    $qb = $this->createQueryBuilder('a')
        ->select('count(a.id)')
        ->from( $sub, 'a' )
        ->where('a.isSuccess = 0');
    return $qb->getQuery()->getSingleScalarResult();
</code>```

Thanks

答:
As @colburton pointed out, it seems that Doctine isn't able to handle subqueries as such. Check this post.

So, I am posting the possible solutions I've found and hopefully somebody will correct me or improve on it.

Alternative 1 - Though I did not verify it, it seems that Native SQL would be able to handle it. Downside is that it seems quite complex, particularly when there are more sensible alternatives.

Alternative 2 - Run plain old mySQL query. Given that the result is a scalar that would be just fine. This is how I set it up.

UsedBundle/Repository/LoginRepository.php

```<code>public function countAllFailedMysqlAction()
{
    $ulink = new \PDO("mysql:host=$hostname;dbname=$database;charset=utf8", $username, $password);
    $sql = "SELECT COUNT(t2.user_id) FROM(
        SELECT t2.* FROM logins t2
        WHERE t2.login_time >= DATE_SUB(NOW(),INTERVAL 5 HOUR)
        LIMIT 10
        ) t2
        WHERE t2.is_success = 0";
        $stmt = $ulink->query($sql);
        return $stmt->fetchColumn();
}
</code>```

Alternative 3 - In this particular instance, one could just run the inner or subquery using regular Entity, return an array and iterate through it to get the result.

UsedBundle/Repository/LoginRepository.php

```<code>public function countAllFailedAction()
{
    $date = new \DateTime();
    $date->modify('-24 hour');

    $qb = $this->createQueryBuilder('l')
        ->select('l.id,l.isSuccess')
        ->where('l.loginTime >= :date')
        ->setParameter('date', $date)
        ->setMaxResults(10);
    $logins = $qb->getQuery()->getArrayResult();

    $ct_failed = 0;
    foreach( $logins as $login ){
        if($login['isSuccess'] == false ){ $ct_failed++;}
    }
    return $ct_failed;
}
</code>```

Body:
New to Doctrine and trying to convert the MySQL query below to queryBuilder.

SELECT COUNT(t2.user_id) FROM(
    SELECT t2.* FROM logins t2
        WHERE t2.login_time >= DATE_SUB(NOW(),INTERVAL 5 HOUR)
        LIMIT 10
    ) t2
WHERE t2.is_success = 1

I've seen a few examples of subquery on the WHERE clause here on SO and attempted to adapt it as per below, but that does not really work.

        $sub = $this->createQueryBuilder('l')
        ->select('l')
        ->where('l.loginTime >= :date
            and l.userId = :user_id')
        ->setParameters( $parameters )
        ->getDQL();

    $qb = $this->createQueryBuilder('a')
        ->select('count(a.id)')
        ->from( $sub, 'a' )
        ->where('a.isSuccess = 0');
    return $qb->getQuery()->getSingleScalarResult();

Thanks

Body:
As @colburton pointed out, it seems that Doctine isn't able to handle subqueries as such. Check this post.

So, I am posting the possible solutions I've found and hopefully somebody will correct me or improve on it.

Alternative 1 - Though I did not verify it, it seems that Native SQL would be able to handle it. Downside is that it seems quite complex, particularly when there are more sensible alternatives.

Alternative 2 - Run plain old mySQL query. Given that the result is a scalar that would be just fine. This is how I set it up.

UsedBundle/Repository/LoginRepository.php

public function countAllFailedMysqlAction()
{
    $ulink = new \PDO("mysql:host=$hostname;dbname=$database;charset=utf8", $username, $password);
    $sql = "SELECT COUNT(t2.user_id) FROM(
        SELECT t2.* FROM logins t2
        WHERE t2.login_time >= DATE_SUB(NOW(),INTERVAL 5 HOUR)
        LIMIT 10
        ) t2
        WHERE t2.is_success = 0";
        $stmt = $ulink->query($sql);
        return $stmt->fetchColumn();
}

Alternative 3 - In this particular instance, one could just run the inner or subquery using regular Entity, return an array and iterate through it to get the result.

UsedBundle/Repository/LoginRepository.php

public function countAllFailedAction()
{
    $date = new \DateTime();
    $date->modify('-24 hour');

    $qb = $this->createQueryBuilder('l')
        ->select('l.id,l.isSuccess')
        ->where('l.loginTime >= :date')
        ->setParameter('date', $date)
        ->setMaxResults(10);
    $logins = $qb->getQuery()->getArrayResult();

    $ct_failed = 0;
    foreach( $logins as $login ){
        if($login['isSuccess'] == false ){ $ct_failed++;}
    }
    return $ct_failed;
}


问:
Convert std::vector<std::string> to const char* const*
I'm working with Vulkan, and I'm trying to pass my validation layer as a vector<string>. But the field ppEnabledLayerNames from VkInstanceCreateInfo only takes const char* const*. I don't understand the type and how to convert my vector's data into it.

```<code>std::vector<std::string> v = {
    "VK_LAYER_LUNARG_standard_validation"
};

const char* const* data = std::accumulate(std::next(v.begin()), v.end(),
                                    v[0],
                                    [](std::string a, std::string b) {
                                        return a + b;
                                    }).c_str();
</code>```

But when I compile, I got this :

```<code>error: cannot convert ‘const char*’ to ‘const char* const*’ in assignment
                     }).c_str();
</code>```

Here's a live example

答:
I finally found the solution this morning, using std::accumulate

```<code>auto d = std::accumulate(
    std::next(v.begin()), v.end(),
    v[0],
    [](std::string a, std::string b) {
        return a + b;
    }).c_str();

const char* const* data = &d;
</code>```

Body:
I'm working with Vulkan, and I'm trying to pass my validation layer as a vector<string>. But the field ppEnabledLayerNames from VkInstanceCreateInfo only takes const char* const*. I don't understand the type and how to convert my vector's data into it.

std::vector<std::string> v = {
    "VK_LAYER_LUNARG_standard_validation"
};

const char* const* data = std::accumulate(std::next(v.begin()), v.end(),
                                    v[0],
                                    [](std::string a, std::string b) {
                                        return a + b;
                                    }).c_str();

But when I compile, I got this :

error: cannot convert ‘const char*’ to ‘const char* const*’ in assignment
                     }).c_str();

Here's a live example

Body:
I finally found the solution this morning, using std::accumulate

auto d = std::accumulate(
    std::next(v.begin()), v.end(),
    v[0],
    [](std::string a, std::string b) {
        return a + b;
    }).c_str();

const char* const* data = &d;


问:
Xamarin Andorid Build Always Fails ("java.exe" exited with code 2)
I'm trying to build a Xamarin.Android app, but the build always fails with error MSB6006: "java.exe" exited with code 2.  I've tried enabling ProGuard and multi-dex, deleting the bin and obj folders, updating all NuGet packages, switching to debug and release modes, and removing all unused references.  The error always points to C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets on line 1965, but that does not help.  I've been struggling with this issue for days and I have no idea what to do next.  These are some SO questions that I've seen, but haven't helped:

"java.exe" exited with code 2

"java.exe" exited with code 2 Xamarin.Android project

Java.exe exited with code 2 in android app build in VS 2015

答:
You can try to enable Multi-Dex in Android project.

Right click on Android project

Options

Android Build

General

Check: Enable Multi-Dex

Now Rebuild the project.


问:
Python: How to multply a dictionary of lists for a dictionary of float numbers?
I was wondering if it is possible to to multply a dictionary of lists of integers for a dictionary of float numbers. Both dictionary have the same keys.

I have a dictionary

```<code>q = dict(((i, f), somefloatnumber) for i in I for f in F)
p = dict(((i, f), somelistofinteger) for i in I for f in F)
</code>```

For instance, if I have:

```<code>dict1={(0, 0):[1, 0, 1], (0, 1):[1, 0, 0], (0, 2):[0, 0, 1]}

dict2={(0, 0): 10.54, (0, 1): 47.32, (0, 2): 33.1}
</code>```

The output would be:

```<code>dict3={(0, 0):[10.54, 0, 10.54], (0, 1):[47.32, 0, 0], (0, 2):[0, 0, 33.1]}
</code>```

Is there a way to multiply the dictionary q and p?
Thanks in advance

Body:
I was wondering if it is possible to to multply a dictionary of lists of integers for a dictionary of float numbers. Both dictionary have the same keys.

I have a dictionary

q = dict(((i, f), somefloatnumber) for i in I for f in F)
p = dict(((i, f), somelistofinteger) for i in I for f in F)

For instance, if I have:

dict1={(0, 0):[1, 0, 1], (0, 1):[1, 0, 0], (0, 2):[0, 0, 1]}

dict2={(0, 0): 10.54, (0, 1): 47.32, (0, 2): 33.1}

The output would be:

dict3={(0, 0):[10.54, 0, 10.54], (0, 1):[47.32, 0, 0], (0, 2):[0, 0, 33.1]}

Is there a way to multiply the dictionary q and p?
Thanks in advance

Body:
Pre-requisite:

"Both dictionaries have the same keys."

You could use dict comprehension wrapping a list comprehension for the list multiplications:

dict1 = {(0, 0): [1, 0, 1], (0, 1): [1, 0, 0], (0, 2): [0, 0, 1]}
dict2 = {(0, 0): 10.54,     (0, 1): 47.32,     (0, 2): 33.1}
dict3 = {k: [dict2[k]*x for x in v] for k, v in dict1.items()}
# dict3 =
# {(0, 0): [10.54, 0.0, 10.54],
#  (0, 1): [47.32, 0.0, 0.0],
#  (0, 2): [0.0, 0.0, 33.1]}

Or, instead of the inner list comprehension, use map with a lambda:

dict1 = {(0, 0): [1, 0, 1], (0, 1): [1, 0, 0], (0, 2): [0, 0, 1]}
dict2 = {(0, 0): 10.54,     (0, 1): 47.32,     (0, 2): 33.1}
dict3 = {k: map(lambda x: dict2[k]*x, v) for k, v in dict1.items()}
# dict3 =
# {(0, 0): [10.54, 0.0, 10.54],
#  (0, 1): [47.32, 0.0, 0.0],
#  (0, 2): [0.0, 0.0, 33.1]}


问:
How to get subclasses attributes using SingleTableInheritance with SpringMVC
i am working on a web application using Spring, Hibernate and SpringMVC,
i am facing a problem with retreiving values from a subclass table using SingleTable inheritance strategy, here are my entities

Client.java (Super class)

```<code>    @Entity
    @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name = "typeClient", discriminatorType = DiscriminatorType.STRING)
    public class Client implements Serializable {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int idClient;

        private String matricule;
        private String statut;

        private String secteurDactivite;
        private String nomClient;

        private String emailClient;

        private String numTelephone;

        private String adresse;
//constructor
//getter & setters
     }
</code>```

Societe.java  (subClass1)

```<code>@Entity
@DiscriminatorValue("Societe")
public class Societe extends Client implements Serializable{

    private String nomResponsable;

    private String emailResponsable;

    private String telResponsable;

    private String nomSuperieur;

    private String emailSuperieur;

    private String telSuperieur;

    private String commentaire;

    //constructeur sans parametre
    public Societe() {
        }
    }
</code>```

Particulier.java (subclass2)

```<code>@Entity
@DiscriminatorValue("Particulier")
public class Particulier extends Client implements Serializable {

    private String cin;

    //constructeur sans parametres
    public Particulier() {

    }
    }
</code>```

in my implementation i am using this methode to get a particular client with his ID

ClientDaoImpl.java

```<code>public class ClientDaoImpl implements ClientDao {
    @PersistenceContext
    private EntityManager em;

    @Override
    public Client getClientByID(int id_client) {
        return em.find(Client.class, id_client);
    }
</code>```

When i ran this code i only selected the attributes of the superClass Client.

what i am trying to do is to get a client with its subclass whether it's a Societe or Particulier based on its type or clientID.

Please Help

答:
As you don't know the type of client before querying and only it's ID, you will need to inspect the type and cast after you retrieve the record;

```<code>Client client1 = clientDao.getClientById(clientID);
if (client1 instanceof Societe) {
    ((Societe) client1).getCommentaire();
}
</code>```

Depending on your use case, it may be useful to map the result of the client query to a ClientDescriptor object which contains all the fields for all client types and returns either nulls or blanks.  This means you don't have to keep checking for client type everywhere;

```<code>public class ClientDTO {
    //client fields
    private String nomResponsable = "";
    ....
    //subclass 1 fields.... initialize to empty
    //subclass 2 fields .... initialize to empty

    public ClientDTO (Client client) {
        // set fields for client entity
    }

    public ClientDTO (Societe societe) {
        this (societe);
        // set societe fields.
    }
    // other constructors.
}
</code>```

Body:
i am working on a web application using Spring, Hibernate and SpringMVC,
i am facing a problem with retreiving values from a subclass table using SingleTable inheritance strategy, here are my entities

Client.java (Super class)

    @Entity
    @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name = "typeClient", discriminatorType = DiscriminatorType.STRING)
    public class Client implements Serializable {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int idClient;

        private String matricule;
        private String statut;

        private String secteurDactivite;
        private String nomClient;

        private String emailClient;

        private String numTelephone;

        private String adresse;
//constructor
//getter & setters
     }

Societe.java  (subClass1)

@Entity
@DiscriminatorValue("Societe")
public class Societe extends Client implements Serializable{

    private String nomResponsable;

    private String emailResponsable;

    private String telResponsable;

    private String nomSuperieur;

    private String emailSuperieur;

    private String telSuperieur;

    private String commentaire;

    //constructeur sans parametre
    public Societe() {
        }
    }

Particulier.java (subclass2)

@Entity
@DiscriminatorValue("Particulier")
public class Particulier extends Client implements Serializable {

    private String cin;

    //constructeur sans parametres
    public Particulier() {

    }
    }

in my implementation i am using this methode to get a particular client with his ID

ClientDaoImpl.java

public class ClientDaoImpl implements ClientDao {
    @PersistenceContext
    private EntityManager em;

    @Override
    public Client getClientByID(int id_client) {
        return em.find(Client.class, id_client);
    }

When i ran this code i only selected the attributes of the superClass Client.

what i am trying to do is to get a client with its subclass whether it's a Societe or Particulier based on its type or clientID.

Please Help

Body:
As you don't know the type of client before querying and only it's ID, you will need to inspect the type and cast after you retrieve the record;

Client client1 = clientDao.getClientById(clientID);
if (client1 instanceof Societe) {
    ((Societe) client1).getCommentaire();
}

Depending on your use case, it may be useful to map the result of the client query to a ClientDescriptor object which contains all the fields for all client types and returns either nulls or blanks.  This means you don't have to keep checking for client type everywhere;

public class ClientDTO {
    //client fields
    private String nomResponsable = "";
    ....
    //subclass 1 fields.... initialize to empty
    //subclass 2 fields .... initialize to empty

    public ClientDTO (Client client) {
        // set fields for client entity
    }

    public ClientDTO (Societe societe) {
        this (societe);
        // set societe fields.
    }
    // other constructors.
}


问:
Formula for sorting/ranking products by their user ratings
I'm trying to get a decent sorting algorithm for my products database. Users can vote for their products with using scores from 0 to 5 (.5 scores are also possible like 2.5). My table structure currently looks like this:

```<code>[ProductID] [Title] ... [NumberOfVotes] [TotalPoints] [FinalScore]
</code>```

Whenever a user votes, I'm calculating the finalscore using a very simple formula like
     (TotalPoints / NumberOfVotes) = FinalScore.

Then I sort the table on FinalScore and NumberOfVotes.

While this works, it's not exactly fair because a product which has only 1 vote of 5 stars can easily come in top rankings.

I'm not very good at statistics or algorithms to get a fair product ranking.
I'm looking for a relatively easy-to-implement formula that's fairer than the method I'm using now.

How can this be done?

答: You could use median, which is often better a figure than raw average. In addition, you might consider not to give ratings for any item that has less than, say, five votes.</p>

Body:
I'm trying to get a decent sorting algorithm for my products database. Users can vote for their products with using scores from 0 to 5 (.5 scores are also possible like 2.5). My table structure currently looks like this:

[ProductID] [Title] ... [NumberOfVotes] [TotalPoints] [FinalScore]

Whenever a user votes, I'm calculating the finalscore using a very simple formula like
     (TotalPoints / NumberOfVotes) = FinalScore.

Then I sort the table on FinalScore and NumberOfVotes.

While this works, it's not exactly fair because a product which has only 1 vote of 5 stars can easily come in top rankings.

I'm not very good at statistics or algorithms to get a fair product ranking.
I'm looking for a relatively easy-to-implement formula that's fairer than the method I'm using now.

How can this be done?


问:
Android XPath HTML parsing like TFHpple (I got a 10-line Obj-C implementation working, can't translate)
2 days ago I wrote this objective-c code to extract text from a website which works exactly as intended. Now I have no idea how to implement this for Android. It's just really weird with Android,

some XPath code that everyone posts is incompatible with HTML files (only accepts standard-XML)

JSoup (which can deal with HTML) can't into Xpath

all in all I am walking in circles right now.

Basically, what I need is to get the elements around //h2/a from a html file at a specific URL. Please take a look at my obj-c implementation that I wrote, it's literally 10 lines of working code but I can't figure out a way to do the same in Android.

```<code>-(void)loadTutorials:(NSString*)startURLS {

NSURL *tutorialsUrl = [NSURL URLWithString:startURLS];
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl];
TFHpple *tutorialsParser = [TFHpple hppleWithHTMLData:tutorialsHtmlData];

NSString *tutorialsXpathQueryString = @"//h2/a";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];

NSString *podcastTitles[99];

int jjj=0;
for (NSString *string in tutorialsNodes) {
    podcastTitles[jjj]=[[[tutorialsNodes[jjj] firstChild] content] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    NSLog(@"%@",podcastTitles[jjj]); //WORKING PERFECTLY FINE
    jjj++;
    }
}
</code>```

答:
Got it working, key was to stick to XPathFactory BUT feeding it a HTMLCleaner-cleaned HTML. Unfortunately I can't find the SO answer that got me on track, so no credit today but hopefully I will stumble across it again.

Idk how many of these lines are necessary and I won't ever clean this code but this block now works for me.

```<code>HtmlCleaner cleaner = new HtmlCleaner();
                CleanerProperties props = cleaner.getProperties();
                props.setAllowHtmlInsideAttributes(true);
                props.setAllowMultiWordAttributes(true);
                props.setRecognizeUnicodeChars(true);
                props.setOmitComments(true);

                TagNode tagNode = new HtmlCleaner().clean(
                        websiteContent);
                org.w3c.dom.Document doc = new DomSerializer(
                        new CleanerProperties()).createDOM(tagNode);

                XPath xpath = XPathFactory.newInstance().newXPath();
                NodeList titleNodes = (NodeList) xpath.evaluate("//h2/a",
                        doc, XPathConstants.NODESET);
                System.out.println("iii"+titleNodes);

                for(int i=0; i<titleNodes.getLength();i++){
                    System.out.println("t t t"+titleNodes.item(i).getTextContent()); //WORKING
                }
</code>```

Body:
2 days ago I wrote this objective-c code to extract text from a website which works exactly as intended. Now I have no idea how to implement this for Android. It's just really weird with Android,

some XPath code that everyone posts is incompatible with HTML files (only accepts standard-XML)

JSoup (which can deal with HTML) can't into Xpath

all in all I am walking in circles right now.

Basically, what I need is to get the elements around //h2/a from a html file at a specific URL. Please take a look at my obj-c implementation that I wrote, it's literally 10 lines of working code but I can't figure out a way to do the same in Android.

-(void)loadTutorials:(NSString*)startURLS {

NSURL *tutorialsUrl = [NSURL URLWithString:startURLS];
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl];
TFHpple *tutorialsParser = [TFHpple hppleWithHTMLData:tutorialsHtmlData];

NSString *tutorialsXpathQueryString = @"//h2/a";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];

NSString *podcastTitles[99];

int jjj=0;
for (NSString *string in tutorialsNodes) {
    podcastTitles[jjj]=[[[tutorialsNodes[jjj] firstChild] content] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    NSLog(@"%@",podcastTitles[jjj]); //WORKING PERFECTLY FINE
    jjj++;
    }
}

Body:
Got it working, key was to stick to XPathFactory BUT feeding it a HTMLCleaner-cleaned HTML. Unfortunately I can't find the SO answer that got me on track, so no credit today but hopefully I will stumble across it again.

Idk how many of these lines are necessary and I won't ever clean this code but this block now works for me.

HtmlCleaner cleaner = new HtmlCleaner();
                CleanerProperties props = cleaner.getProperties();
                props.setAllowHtmlInsideAttributes(true);
                props.setAllowMultiWordAttributes(true);
                props.setRecognizeUnicodeChars(true);
                props.setOmitComments(true);

                TagNode tagNode = new HtmlCleaner().clean(
                        websiteContent);
                org.w3c.dom.Document doc = new DomSerializer(
                        new CleanerProperties()).createDOM(tagNode);

                XPath xpath = XPathFactory.newInstance().newXPath();
                NodeList titleNodes = (NodeList) xpath.evaluate("//h2/a",
                        doc, XPathConstants.NODESET);
                System.out.println("iii"+titleNodes);

                for(int i=0; i<titleNodes.getLength();i++){
                    System.out.println("t t t"+titleNodes.item(i).getTextContent()); //WORKING
                }


问:
Bootstrap - setting Column heights
I'm creating a Bootstrap (version 3.3) website, which has a smallish sized carousel, and I want to create 3 boxes immediately on its right-hand side; (refer image for an idea of what I'm trying to do).

As obviously I want it all responsive, I've placed the Carousel within a column (of width 8 for medium & large screens) + 1 for offset, while the boxes would be the width of 2 + 1 offset.
I then also created another row (and columns) within the 2 column - so that all boxes would move below the Carousel on a xs screen size at the same time.

I've used row-eq-height to make the Carousel column and the column with the boxes the same height, but I'm not sure as to how to make 2 boxes 33% of the height of the Carousel & 1 box 34% of the Carousel height.  (Obviously, I want the boxes displayed below each other, with no gutter between them).

My Code so far on Bootply;
https://www.bootply.com/RQfetegi0e

Otherwise the HTML Code so far;

```<code><div class="container" style="padding-top:100px;">
  <div class="row no-gutter">
    <div class="col-md-offset-1 col-md-8 col-sm-8 col-xs-12 row-eq-height">
      <div id="myCarousel" class="carousel slide">
        <ol class="carousel-indicators">
          <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
          <li data-target="#myCarousel" data-slide-to="1"></li>
          <li data-target="#myCarousel" data-slide-to="2"></li>
          <li data-target="#myCarousel" data-slide-to="3"></li>
          <li data-target="#myCarousel" data-slide-to="4"></li>
        </ol>
        <!-- Carousel items -->
        <div class="carousel-inner img-responsive center-block">
          <div class="active item">
            <img src="images/carousel/coming-events.jpg" alt="">
          </div>
          <div class="item img-responsive center-block">
            <img src="images/carousel/play-group.jpg" alt="">
          </div>
          <div class="item img-responsive center-block">
            <img src="images/carousel/learn-skills.jpg" alt="">
          </div>
          <div class="item img-responsive center-block">
            <img src="images/carousel/kids-xmas.jpg" alt="">
          </div>
          <div class="item img-responsive center-block">
            <img src="images/carousel/backyard-sports.jpg" alt="">
          </div>
        </div>
      </div>
    </div>
    <div class="col-md-2 col-sm-3 col-xs-12 no-padding">
      <div class="row">
        <div class="col-xs-12" style="margin-bottom:-20px; margin-top:-20px; height:33%;">
          <h3 style="text-align:center; color: white; background-color:red; height:33%;">Text Here</h3>
        </div>
        <div class="col-xs-12" style="margin-top:-25px; margin-bottom-25px; height:34%;">
          <h3 style="text-align:center; color: white; background-color:green; height:34%;">Text Here</h3>

        </div>
        <div class="col-xs-12" style="margin-top:-25px; margin-bottom:-25px; height:33%;">
          <h3 style="text-align:center; color: white; background-color:blue; height:33%;">Text Here</h3>
        </div>
      </div>
  </div>
  </div>
</div>
</code>```

CSS Code:

```<code>.no-gutter > [class*='col-'] {
    padding-right:0;
    padding-left:0;
}

.row-eq-height {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display:         flex;
}
</code>```

答:
Fastest solution - if your carousel will have fixed height, is to set the same height to second (right) row...
And also set the background-color attribute to div, not h3, and remove the padding..

```<code><div class="row" style="height:261px">
        <div class="col-xs-12" style="height:33%;background-color:red;">
          <h3 style="text-align:center; color: white; height:33%;">Text Here</h3>
        </div>
        <div class="col-xs-12" style="height:34%;background-color:green;">
          <h3 style="text-align:center; color: white; height:34%;">Text Here</h3>

        </div>
        <div class="col-xs-12" style="height:33%;background-color:blue;">
          <h3 style="text-align:center; color: white; height:33%;">Text Here</h3>
        </div>
      </div>
</code>```

Title: Bootstrap - setting Column heights

Body:
I'm creating a Bootstrap (version 3.3) website, which has a smallish sized carousel, and I want to create 3 boxes immediately on its right-hand side; (refer image for an idea of what I'm trying to do).

As obviously I want it all responsive, I've placed the Carousel within a column (of width 8 for medium & large screens) + 1 for offset, while the boxes would be the width of 2 + 1 offset.
I then also created another row (and columns) within the 2 column - so that all boxes would move below the Carousel on a xs screen size at the same time.

I've used row-eq-height to make the Carousel column and the column with the boxes the same height, but I'm not sure as to how to make 2 boxes 33% of the height of the Carousel & 1 box 34% of the Carousel height.  (Obviously, I want the boxes displayed below each other, with no gutter between them).

My Code so far on Bootply;
https://www.bootply.com/RQfetegi0e

Otherwise the HTML Code so far;

Text Here

Text Here

Text Here

CSS Code:

.no-gutter > [class*='col-'] {
    padding-right:0;
    padding-left:0;
}

.row-eq-height {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display:         flex;
}

Body:
Fastest solution - if your carousel will have fixed height, is to set the same height to second (right) row...
And also set the background-color attribute to div, not h3, and remove the padding..

<div class="row" style="height:261px">
        <div class="col-xs-12" style="height:33%;background-color:red;">
          <h3 style="text-align:center; color: white; height:33%;">Text Here</h3>
        </div>
        <div class="col-xs-12" style="height:34%;background-color:green;">
          <h3 style="text-align:center; color: white; height:34%;">Text Here</h3>

        </div>
        <div class="col-xs-12" style="height:33%;background-color:blue;">
          <h3 style="text-align:center; color: white; height:33%;">Text Here</h3>
        </div>
      </div>


问:
Git unable to identify project.pbxproj
Whenever i commit and push project.xcodeproj file, git not able to identify project.pbxproj because it is not showing on remote branch.

If i do some changes in project like add a new file or change project settings etc. but still git unable to identify any changes in project.xcodeproj.

Please help me out.

答:
Because the project.pbxproj file is packed and embedded in the project.xcodeproj bundle.

You change it , and git add it.

Git not able to identify project.pbxproj because it is not showing on
  remote branch.

I think you need some Plugin to open file in Github, like fugitive.vim .

Title: Git unable to identify project.pbxproj


问:
How do you juggle appcache.manifest, manifest.json, and serviceworkers?
I'm new to javascript development. I'm trying to make an app that will work offline on both iOS and android devices. I'm have trouble learning with no examples and I'm not finding examples that do what I need.

Here's what I've found; it could be wrong:

iOS requires appcache.manifest and it needs to be loaded with this
syntax:

Android requires manifest.json and it needs to be loaded with this syntax:

These seem mutually exclusive

Android also likes serviceworkers. You can have both appcache.manifest and serviceworkers; see this: Application Cache and Service Workers

The above discussion suggests handing appcache vs serviceworker with javascript. I get how it handles appcache & serviceworker but it doesn't address including manifest.json. It looks like the recommended place for scripts on an html page is someplace after the  tag, at which point the decision between appcache.manifest (for ios) and manifest.json (for android) looks like it already needs to have been made.

How do you handle all this? Here are some questions that might get at the root of my confusion:

Do I need a manifest.json for Android? Or is this replaced by the serviceworker and that's why I have found zero examples involving both kinds of manifest?

Is there something I'm missing about order of operations that will allow me to choose between appcache.manifest and manifest.json programmatically?

Is there a more effective approach that I'm missing?

答:
You can have a reference to both. Remember a progressive web app is 'progressive enhancement'. If there is a service worker, then by specification the appCache is ignored and the service worker is used for caching/offline.
The web manifest file contains meta data the browser/platform will use to create the themed experience and chose the icon for the home screen. So different context from the appCache.

Also Progressive Web Applications are not an Android specific thing. They are supported by all browsers except Apple Safari.


问:
Converting non-numeric matrix into numeric
I have an imported table with longitudes and latitudes and want to create a spatial grid from them.
The coordinates are in this format:

```<code>[1] 6.955 6.937 6.956 6.923
</code>```

So looks numeric for me. But trying to create the grid this Error occurs:

Error in .local(obj, ...) :

        cannot derive coordinates from non-numeric matrix

When I try to change the format using as.numeric I get this result:

```<code>[1] 10  9  6  8
</code>```

How can I convert the coordinates in numeric format without changing the value?

```<code>longitude = structure(c(9L, 7L, 10L, 3L, 8L, 4L, 6L, 2L, 11L, 1L, 5L, 9L,
7L, 10L, 3L, 8L, 4L, 6L, 2L, 11L, 1L, 5L), .Label = c("6.920",
"6.922", "6.923", "6.924", "6.926", "6.936", "6.937", "6.939",
"6.955", "6.956", "6.958"), class = "factor")

latitude = structure(c(10L, 9L, 6L, 8L, 1L, 5L, 3L, 2L, 7L, 8L, 4L, 10L,
9L, 6L, 8L, 1L, 5L, 3L, 2L, 7L, 8L, 4L), .Label = c("50.911",
"50.918", "50.920", "50.929", "50.930", "50.931", "50.934", "50.950",
"50.965", "50.969"), class = "factor")
</code>```

The original table luftdaten.set contains latitudes, longitudes and particulate matter values. I tried to created a grid:

```<code>coordinates(luftdaten.set) <- ~ latitude + longitude
</code>```

I also tried to create a dataframe with only the coordinates and tried to derive a grid from it:

```<code>luftdaten.grid <- data.frame(latitude, longitude)
luftdaten.grid <- data.frame(latitude, longitude)
</code>```

Both throws the described error.

coordinates is in the SpatialTools 'sp' package.

Body:
I have an imported table with longitudes and latitudes and want to create a spatial grid from them.
The coordinates are in this format:

[1] 6.955 6.937 6.956 6.923

So looks numeric for me. But trying to create the grid this Error occurs:

Error in .local(obj, ...) :

        cannot derive coordinates from non-numeric matrix

When I try to change the format using as.numeric I get this result:

[1] 10  9  6  8

How can I convert the coordinates in numeric format without changing the value?

longitude = structure(c(9L, 7L, 10L, 3L, 8L, 4L, 6L, 2L, 11L, 1L, 5L, 9L,
7L, 10L, 3L, 8L, 4L, 6L, 2L, 11L, 1L, 5L), .Label = c("6.920",
"6.922", "6.923", "6.924", "6.926", "6.936", "6.937", "6.939",
"6.955", "6.956", "6.958"), class = "factor")

latitude = structure(c(10L, 9L, 6L, 8L, 1L, 5L, 3L, 2L, 7L, 8L, 4L, 10L,
9L, 6L, 8L, 1L, 5L, 3L, 2L, 7L, 8L, 4L), .Label = c("50.911",
"50.918", "50.920", "50.929", "50.930", "50.931", "50.934", "50.950",
"50.965", "50.969"), class = "factor")

The original table luftdaten.set contains latitudes, longitudes and particulate matter values. I tried to created a grid:

coordinates(luftdaten.set) <- ~ latitude + longitude

I also tried to create a dataframe with only the coordinates and tried to derive a grid from it:

luftdaten.grid <- data.frame(latitude, longitude)
luftdaten.grid <- data.frame(latitude, longitude)

Both throws the described error.

coordinates is in the SpatialTools 'sp' package.

Body:
Assuming you're trying to get a matrix where each row is a lat/long pair:

as.matrix(cbind(as.numeric(as.character(latitude)),
                as.numeric(as.character(longitude))))

        [,1]  [,2]
 [1,] 50.969 6.955
 [2,] 50.965 6.937
 [3,] 50.931 6.956
 [4,] 50.950 6.923
 [5,] 50.911 6.939
 [6,] 50.930 6.924
 [7,] 50.920 6.936
 [8,] 50.918 6.922
 [9,] 50.934 6.958
[10,] 50.950 6.920
[11,] 50.929 6.926
[12,] 50.969 6.955
[13,] 50.965 6.937
[14,] 50.931 6.956
[15,] 50.950 6.923
[16,] 50.911 6.939
[17,] 50.930 6.924
[18,] 50.920 6.936
[19,] 50.918 6.922
[20,] 50.934 6.958
[21,] 50.950 6.920
[22,] 50.929 6.926


问:
@aar' is not a valid maven coordinate
Android studio upgraded my gradle wrapper to gradle-4.1-milestone-1-all and seems to have broken the build. Getting the following error.

```<code>Gradle sync failed: java.lang.AssertionError: 'com.spotify.sdk:spotify-player-24-noconnect-2.20b:@aar' is not a valid maven coordinate.
</code>```

The dependancy is in my gradle script as an implementation and the arr is in my libs folder.

```<code>dependencies {
     implementation 'com.spotify.sdk:spotify-player-24-noconnect-2.20b@aar'
}
</code>```

Has anyone else come accross this error?

答:
EDIT studio update 3.0 canary 6 has solved it.

OLD:
So I was facing the same issue (could be like yours) after the canary update.
I had an aar file in the libs directory added as a dependency.

this is what it was before

```<code>compile(name: 'materialbarcodescanner-release', ext: 'aar') {
    exclude group: 'com.android.support', module: 'appcompat-v7'
}
</code>```

this is what solved it

```<code> compile('com.edwardvanraak:materialbarcodescanner-release@aar') {
    exclude group: 'com.android.support', module: 'appcompat-v7'
}
</code>```

basically added the '{packagename}:{filename}@arr' instead of the usual convention.

Title: @aar' is not a valid maven coordinate

Body:
Android studio upgraded my gradle wrapper to gradle-4.1-milestone-1-all and seems to have broken the build. Getting the following error.

Gradle sync failed: java.lang.AssertionError: 'com.spotify.sdk:spotify-player-24-noconnect-2.20b:@aar' is not a valid maven coordinate.

The dependancy is in my gradle script as an implementation and the arr is in my libs folder.

dependencies {
     implementation 'com.spotify.sdk:spotify-player-24-noconnect-2.20b@aar'
}

Has anyone else come accross this error?

Body:
EDIT studio update 3.0 canary 6 has solved it.

OLD:
So I was facing the same issue (could be like yours) after the canary update.
I had an aar file in the libs directory added as a dependency.

this is what it was before

compile(name: 'materialbarcodescanner-release', ext: 'aar') {
    exclude group: 'com.android.support', module: 'appcompat-v7'
}

this is what solved it

 compile('com.edwardvanraak:materialbarcodescanner-release@aar') {
    exclude group: 'com.android.support', module: 'appcompat-v7'
}

basically added the '{packagename}:{filename}@arr' instead of the usual convention.


问:
Calling a C# from a VB project in one solution
I have 2 projects in one solution.

The main is a VB.net project and the secondary is a C# project. I want to call a form from the C# project from the VB.net project at the click of a button but I am unsure how.

I have read it is possible if I create the C# .dll and reference it but I cannot find a guide for this. Would anybody give me a step by step on how one would accomplish this please?

答:
It's a fairly simple and easy thing to do, and also common. Saves duplicating code across projects if you have multiple projects which all have a function which does the same thing.

Right Click the VB project and click Add ->  Reference...

Press the Projects node on the left.

Now hover over the C# project and click the checkbox that appears.

You've now added the reference. Beware that you cannot then reference the Vb project from the C# as Visual Studio will not allow this because you're creating a circular reference.

To call a form to show up, you can do the following.

First, you'll need to make a reference somewhere of the new form. For example; (OtherProject being the name of the other project, and FormName being the name of the form in the project. Depending on what you're doing, you might want to do this when you start your VB app, or you might only need it once. It entirely depends on your setup.

```<code>Dim OtherProjectForm as New OtherProject.FormName
</code>```

When you've done that, just go ahead and do

```<code>OtherProjectForm.Show()
</code>```

or of course, again, depending what you're doing,

```<code>OtherProjectForm.ShowDialog()
</code>```

You'll also be able to access and public members of the form. By default, every control on the form's access mode is "Friend", which means just objects which are part of the same assembly can access them, but if you need to, you can make them public. Or you can just make methods to interact with them.

Body:
It's a fairly simple and easy thing to do, and also common. Saves duplicating code across projects if you have multiple projects which all have a function which does the same thing.

Right Click the VB project and click Add ->  Reference...

Press the Projects node on the left.

Now hover over the C# project and click the checkbox that appears.

You've now added the reference. Beware that you cannot then reference the Vb project from the C# as Visual Studio will not allow this because you're creating a circular reference.

To call a form to show up, you can do the following.

First, you'll need to make a reference somewhere of the new form. For example; (OtherProject being the name of the other project, and FormName being the name of the form in the project. Depending on what you're doing, you might want to do this when you start your VB app, or you might only need it once. It entirely depends on your setup.

Dim OtherProjectForm as New OtherProject.FormName

When you've done that, just go ahead and do

OtherProjectForm.Show()

or of course, again, depending what you're doing,

OtherProjectForm.ShowDialog()

You'll also be able to access and public members of the form. By default, every control on the form's access mode is "Friend", which means just objects which are part of the same assembly can access them, but if you need to, you can make them public. Or you can just make methods to interact with them.