问:
Perl too slow concurrent download with both HTTP::Async & Net::Async::HTTP
I'm trying to GET about 7 dozens of urls in parallel with scripts: the first is below, with HTTP::Async, and the second one is on pastebin, with Net::Async::HTTP.
The problem is that I'm getting pretty same timing results - about 8..14 seconds for all urls list. It's inacceptable slow compared to curl+xargs started from shell, which gets all in less than 3 seconds with 10-20 "threads".
For example, Devel::Timer in first script shows that max queue length is even less than 6 ($queue->in_progress_count<=5, $queue->to_send_count=0 allways). So, it's looks like foreach with $queue->add is executing too slow, and I don't know why.
Pretty same situation I got with Net::Async::HTTP (second script on pastebin), which is even slower than the first.

So, please, does anybody know, what I'm doing wrong? How can I get concurrent download speed at least compared to curl+xargs started from shell?

```<code>#!/usr/bin/perl -w
use utf8;
use strict;
use POSIX qw(ceil);
use XML::Simple;
use Data::Dumper;
use HTTP::Request;
use HTTP::Async;
use Time::HiRes qw(usleep time);
use Devel::Timer;

#settings
use constant passwd => 'ultramegahypapassword';
use constant agent => 'supa agent dev.alpha';
use constant timeout => 10;
use constant slots => 10;
use constant debug => 1;

my @qids;
my @xmlz;
my $queue = HTTP::Async->new(slots => slots,max_request_time => 10, timeout => timeout, poll_interval => 0.0001);
my %responses;
my @urlz = (
'http://testpodarki.afghanet/api/products/4577',
'http://testpodarki.afghanet/api/products/4653',
'http://testpodarki.afghanet/api/products/4652',
'http://testpodarki.afghanet/api/products/4571',
'http://testpodarki.afghanet/api/products/4572',
'http://testpodarki.afghanet/api/products/4666',
'http://testpodarki.afghanet/api/products/4576',
'http://testpodarki.afghanet/api/products/4574',
'http://testpodarki.afghanet/api/products/4651',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[3294]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[3294]',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4577]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4577]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4577]',
'http://testpodarki.afghanet/api/product_option_values/188',
'http://testpodarki.afghanet/api/product_option_values/191',
'http://testpodarki.afghanet/api/product_option_values/187',
'http://testpodarki.afghanet/api/product_option_values/190',
'http://testpodarki.afghanet/api/product_option_values/189',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4653]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4653]',
'http://testpodarki.afghanet/api/images/products/4577/12176',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4652]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4652]',
'http://testpodarki.afghanet/api/images/products/4653/12390',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4571]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4571]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4571]',
'http://testpodarki.afghanet/api/images/products/4652/12388',
'http://testpodarki.afghanet/api/product_option_values/175',
'http://testpodarki.afghanet/api/product_option_values/178',
'http://testpodarki.afghanet/api/product_option_values/179',
'http://testpodarki.afghanet/api/product_option_values/180',
'http://testpodarki.afghanet/api/product_option_values/181',
'http://testpodarki.afghanet/api/images/products/3294/8965',
'http://testpodarki.afghanet/api/product_option_values/176',
'http://testpodarki.afghanet/api/product_option_values/177',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4572]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4572]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4572]',
'http://testpodarki.afghanet/api/product_option_values/176',
'http://testpodarki.afghanet/api/product_option_values/181',
'http://testpodarki.afghanet/api/product_option_values/180',
'http://testpodarki.afghanet/api/images/products/4571/12159',
'http://testpodarki.afghanet/api/product_option_values/177',
'http://testpodarki.afghanet/api/product_option_values/179',
'http://testpodarki.afghanet/api/product_option_values/175',
'http://testpodarki.afghanet/api/product_option_values/178',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4666]',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4576]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4666]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4576]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4576]',
'http://testpodarki.afghanet/api/images/products/4572/12168',
'http://testpodarki.afghanet/api/product_option_values/185',
'http://testpodarki.afghanet/api/product_option_values/182',
'http://testpodarki.afghanet/api/product_option_values/184',
'http://testpodarki.afghanet/api/product_option_values/183',
'http://testpodarki.afghanet/api/product_option_values/186',
'http://testpodarki.afghanet/api/images/products/4666/12413',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4574]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4574]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4574]',
'http://testpodarki.afghanet/api/product_option_values/177',
'http://testpodarki.afghanet/api/product_option_values/181',
'http://testpodarki.afghanet/api/images/products/4576/12174',
'http://testpodarki.afghanet/api/product_option_values/176',
'http://testpodarki.afghanet/api/product_option_values/180',
'http://testpodarki.afghanet/api/product_option_values/179',
'http://testpodarki.afghanet/api/product_option_values/175',
'http://testpodarki.afghanet/api/product_option_values/178',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4651]',
'http://testpodarki.afghanet/api/images/products/4574/12171',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4651]',
'http://testpodarki.afghanet/api/images/products/4651/12387'
);

my $timer = Devel::Timer->new();

foreach my $el (@urlz) {
    my $request = HTTP::Request->new(GET => $el);
    $request->header(User_Agent => agent);
    $request->authorization_basic(passwd,'');
    push @qids,$queue->add($request);
    $timer->mark("pushed [$el], to_send=".$queue->to_send_count().", to_return=".$queue->to_return_count().", in_progress=".$queue->in_progress_count());
}

$timer->mark('requestz pushed');

while ($queue->in_progress_count) {
    usleep(2000);
    $queue->poke();
}

$timer->mark('requestz complited');

process_responses();

$timer->mark('responzez processed');

foreach my $q (@xmlz) {
#    print ">>>>>>".Dumper($q)."<<<<<<<<\n";
}

$timer->report();
print "\n\n";
</code>```

答:
Async will be slower than parallel downloading: the async code will yield to other calls only while waiting for a response, but downloading happens sequentially in a single process, while the curl+xargs will work 100% (well, almost 100%, and as long as you don't saturate the cores) in parallel, same as when using forked workers.

please, google for "concurrency is not parallelism"

Body:
I'm trying to GET about 7 dozens of urls in parallel with scripts: the first is below, with HTTP::Async, and the second one is on pastebin, with Net::Async::HTTP.
The problem is that I'm getting pretty same timing results - about 8..14 seconds for all urls list. It's inacceptable slow compared to curl+xargs started from shell, which gets all in less than 3 seconds with 10-20 "threads".
For example, Devel::Timer in first script shows that max queue length is even less than 6 ($queue->in_progress_count<=5, $queue->to_send_count=0 allways). So, it's looks like foreach with $queue->add is executing too slow, and I don't know why.
Pretty same situation I got with Net::Async::HTTP (second script on pastebin), which is even slower than the first.

So, please, does anybody know, what I'm doing wrong? How can I get concurrent download speed at least compared to curl+xargs started from shell?

#!/usr/bin/perl -w
use utf8;
use strict;
use POSIX qw(ceil);
use XML::Simple;
use Data::Dumper;
use HTTP::Request;
use HTTP::Async;
use Time::HiRes qw(usleep time);
use Devel::Timer;

#settings
use constant passwd => 'ultramegahypapassword';
use constant agent => 'supa agent dev.alpha';
use constant timeout => 10;
use constant slots => 10;
use constant debug => 1;

my @qids;
my @xmlz;
my $queue = HTTP::Async->new(slots => slots,max_request_time => 10, timeout => timeout, poll_interval => 0.0001);
my %responses;
my @urlz = (
'http://testpodarki.afghanet/api/products/4577',
'http://testpodarki.afghanet/api/products/4653',
'http://testpodarki.afghanet/api/products/4652',
'http://testpodarki.afghanet/api/products/4571',
'http://testpodarki.afghanet/api/products/4572',
'http://testpodarki.afghanet/api/products/4666',
'http://testpodarki.afghanet/api/products/4576',
'http://testpodarki.afghanet/api/products/4574',
'http://testpodarki.afghanet/api/products/4651',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[3294]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[3294]',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4577]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4577]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4577]',
'http://testpodarki.afghanet/api/product_option_values/188',
'http://testpodarki.afghanet/api/product_option_values/191',
'http://testpodarki.afghanet/api/product_option_values/187',
'http://testpodarki.afghanet/api/product_option_values/190',
'http://testpodarki.afghanet/api/product_option_values/189',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4653]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4653]',
'http://testpodarki.afghanet/api/images/products/4577/12176',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4652]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4652]',
'http://testpodarki.afghanet/api/images/products/4653/12390',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4571]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4571]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4571]',
'http://testpodarki.afghanet/api/images/products/4652/12388',
'http://testpodarki.afghanet/api/product_option_values/175',
'http://testpodarki.afghanet/api/product_option_values/178',
'http://testpodarki.afghanet/api/product_option_values/179',
'http://testpodarki.afghanet/api/product_option_values/180',
'http://testpodarki.afghanet/api/product_option_values/181',
'http://testpodarki.afghanet/api/images/products/3294/8965',
'http://testpodarki.afghanet/api/product_option_values/176',
'http://testpodarki.afghanet/api/product_option_values/177',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4572]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4572]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4572]',
'http://testpodarki.afghanet/api/product_option_values/176',
'http://testpodarki.afghanet/api/product_option_values/181',
'http://testpodarki.afghanet/api/product_option_values/180',
'http://testpodarki.afghanet/api/images/products/4571/12159',
'http://testpodarki.afghanet/api/product_option_values/177',
'http://testpodarki.afghanet/api/product_option_values/179',
'http://testpodarki.afghanet/api/product_option_values/175',
'http://testpodarki.afghanet/api/product_option_values/178',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4666]',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4576]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4666]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4576]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4576]',
'http://testpodarki.afghanet/api/images/products/4572/12168',
'http://testpodarki.afghanet/api/product_option_values/185',
'http://testpodarki.afghanet/api/product_option_values/182',
'http://testpodarki.afghanet/api/product_option_values/184',
'http://testpodarki.afghanet/api/product_option_values/183',
'http://testpodarki.afghanet/api/product_option_values/186',
'http://testpodarki.afghanet/api/images/products/4666/12413',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4574]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4574]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4574]',
'http://testpodarki.afghanet/api/product_option_values/177',
'http://testpodarki.afghanet/api/product_option_values/181',
'http://testpodarki.afghanet/api/images/products/4576/12174',
'http://testpodarki.afghanet/api/product_option_values/176',
'http://testpodarki.afghanet/api/product_option_values/180',
'http://testpodarki.afghanet/api/product_option_values/179',
'http://testpodarki.afghanet/api/product_option_values/175',
'http://testpodarki.afghanet/api/product_option_values/178',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4651]',
'http://testpodarki.afghanet/api/images/products/4574/12171',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4651]',
'http://testpodarki.afghanet/api/images/products/4651/12387'
);

my $timer = Devel::Timer->new();

foreach my $el (@urlz) {
    my $request = HTTP::Request->new(GET => $el);
    $request->header(User_Agent => agent);
    $request->authorization_basic(passwd,'');
    push @qids,$queue->add($request);
    $timer->mark("pushed [$el], to_send=".$queue->to_send_count().", to_return=".$queue->to_return_count().", in_progress=".$queue->in_progress_count());
}

$timer->mark('requestz pushed');

while ($queue->in_progress_count) {
    usleep(2000);
    $queue->poke();
}

$timer->mark('requestz complited');

process_responses();

$timer->mark('responzez processed');

foreach my $q (@xmlz) {
#    print ">>>>>>".Dumper($q)."<<<<<<<<\n";
}

$timer->report();
print "\n\n";


来源: stackexchange

问:
Why the outputs are strange when using REAL type values as do-loop control variables in Fortran？
When I code in Fortran language, I find when I set REAL value as control-var in do-loop, the outputs are strange, for example:

```<code>do i=0.1,1.0,0.1
write (13,"(F15.6)") i
end do
</code>```

The out puts are: 0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0.But when I set the start value as 0.6:

```<code>do i=0.6,1.0,0.1
write (13,"(F15.6)") i
end do
</code>```

the outputs are:0.6,0.7,0.8,0.9,and 1.0 is not outputted. Why does this happen?

答:
This is basically a rounding issue see Precision problems of real numbers in Fortran and the link that follows from there. Comparing two floating points is tricky and it does not play well with do loops.

You should print more decimal numbers and not just 6:

```<code>   0.1000000015
   0.2000000030
   0.3000000119
   0.4000000060
   0.5000000000
   0.6000000238
   0.7000000477
   0.8000000715
   0.9000000954
   1.0000001192
</code>```

The values are not precise.

In Fortran the number of iterations is computed before starting the loop. And when you compute the loop trip count:

```<code>write (*,"(F15.10)") (1.0 - 0.1) / 0.1

write (*,"(F15.10)") (1.0 - 0.6) / 0.1
</code>```

you will get:

```<code>   9.0000000000
   3.9999997616
</code>```

so the latter one will be iterated only four times (3 + 1 = 4; so i = 0.6, 0.7, 0.8 and 0.9), because the count is truncated from 3.999... to 3.

Real loop counters were deleted from Fortran for good reasons, don't use them. The rounding is one of the problems. The compiler should warn you:

Warning: Deleted feature: Start expression in DO loop at (1) must be
  integer

Also, naming a real variable as i should be a crime.

ContentLicense: CC BY-SA 3.0

Body:
When I code in Fortran language, I find when I set REAL value as control-var in do-loop, the outputs are strange, for example:

do i=0.1,1.0,0.1
write (13,"(F15.6)") i
end do

The out puts are: 0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0.But when I set the start value as 0.6:

do i=0.6,1.0,0.1
write (13,"(F15.6)") i
end do

the outputs are:0.6,0.7,0.8,0.9,and 1.0 is not outputted. Why does this happen?

Body:
This is basically a rounding issue see Precision problems of real numbers in Fortran and the link that follows from there. Comparing two floating points is tricky and it does not play well with do loops.

You should print more decimal numbers and not just 6:

   0.1000000015
   0.2000000030
   0.3000000119
   0.4000000060
   0.5000000000
   0.6000000238
   0.7000000477
   0.8000000715
   0.9000000954
   1.0000001192

The values are not precise.

In Fortran the number of iterations is computed before starting the loop. And when you compute the loop trip count:

write (*,"(F15.10)") (1.0 - 0.1) / 0.1

write (*,"(F15.10)") (1.0 - 0.6) / 0.1

you will get:

   9.0000000000
   3.9999997616

so the latter one will be iterated only four times (3 + 1 = 4; so i = 0.6, 0.7, 0.8 and 0.9), because the count is truncated from 3.999... to 3.

Real loop counters were deleted from Fortran for good reasons, don't use them. The rounding is one of the problems. The compiler should warn you:

Warning: Deleted feature: Start expression in DO loop at (1) must be
  integer

Also, naming a real variable as i should be a crime.


问:
What's the meaning of p = (int(*)[3])malloc(3*sizeof(*p));
```<code>#include<stdio.h>
#include<stdlib.h>

int main()
{
     int i, j;
     int(*p)[3];
     p = (int(*)[3])malloc(3*sizeof(*p));
     for(i=0; i<3; i++)
     {
         for(j=0; j<3; j++)
             printf("%d", p[i][j]);
     }
     return 0;
}
</code>```

<p>p is a pointer to an array of 3 integer then why it is behaving as a 2D array </p>

答:
malloc is a command to allocate a block of memory according to the size of data you needed (in byte).
in this case you are trying to allocate a block of memory for an array of integer with size of 3.
meanwhile sizeof() is a method to get actual byte size of memory would be used for a data type which is an integer in this case. and because you are needing an array with size of 3, that's why the 3 multiplier comes for
and than you would like to type cast as an pointer into an array of integer with size of 3 to be used later

Body:
#include<stdio.h>
#include<stdlib.h>

int main()
{
     int i, j;
     int(*p)[3];
     p = (int(*)[3])malloc(3*sizeof(*p));
     for(i=0; i<3; i++)
     {
         for(j=0; j<3; j++)
             printf("%d", p[i][j]);
     }
     return 0;
}

p is a pointer to an array of 3 integer then why it is behaving as a 2D array


问:
R - Aggregate county map polygons to create custom borders
I can create a county map using ggplot. I would like to use this map data, and map new boundaries that are aggregates of counties. For example, an equivalent task to mine would be to map state boundaries ("region" variable), rather than county boundaries, using this county map dataset (I have another variable I would use to aggregate counties).

Simply changing the group in ggplot does not work for this. I believe I might need to create new polygon shapes based on the variable I am using to aggregate, but I am not sure. Any thoughts on how I can do this? Any help is greatly appreciated!

```<code>library(ggplot2)

# load county map data
m.county <- map_data("county")
head(m.county)
       long      lat group order  region subregion
1 -86.50517 32.34920     1     1 alabama   autauga
2 -86.53382 32.35493     1     2 alabama   autauga
3 -86.54527 32.36639     1     3 alabama   autauga
4 -86.55673 32.37785     1     4 alabama   autauga
5 -86.57966 32.38357     1     5 alabama   autauga
6 -86.59111 32.37785     1     6 alabama   autauga

# map county data with county borders
ggplot(data = m.county) +
  geom_polygon(aes(x=long, y=lat,group=group))
</code>```

答:
You can use gUnaryUnion from library(rgeos) to merge polygons, but as you use maps from library maps, this requires few steps:

Get the data from map library, which is what uses get_map

```<code>library(ggplot2)
library(sp)
library(rgdal)
library(maps)
library(mapdata)

# adapted from
# http://stackoverflow.com/questions/26062280/converting-a-map-object-to-a-spatialpolygon-object
require(sp)
require(maptools)
county <- map("county", fill = TRUE)
</code>```

Transform map data into SpatialPolygonsDataFrame of library(sp)

```<code>head(county$names)
county.sp <- map2SpatialPolygons(county, IDs = as.factor(county$names),
                                 proj4string = CRS("+proj=longlat +datum=WGS84"))

# Add information data of the polygons
region <- sapply(strsplit(county$names, ","), function(x) x[1])
subregion <- sapply(strsplit(county$names, ","), function(x) x[2])
subregion[is.na(subregion)] <- region[is.na(subregion)]

# Create the SpatialPolygonsDataFrame
county.sp.data <- SpatialPolygonsDataFrame(
  county.sp,
  data = data.frame(region = region,
                    subregion = subregion),
  match.ID = FALSE)
</code>```

Merge polygons according to region using gUnaryUnion

Because maps from library maps is not clean in terms of topology, you need to use a buffer as a trick to clean it.

```<code>library(rgeos)
# Because of topology problems
county.sp.data.buffer <- gBuffer(county.sp.data, byid = TRUE, width = 0)
# Merge polygons according to region
county.region <- gUnaryUnion(county.sp.data.buffer,
                             id = county.sp.data.buffer@data$region)
</code>```

Transform back as a dataset suitable for ggplot

Use fortify to be able to plot the spatialdata with ggplot

```<code>county.fortify <- fortify(county.region)

ggplot(data = county.fortify) +
  geom_polygon(aes(x=long, y=lat, fill=group)) +
  guides(fill = FALSE)
</code>```

Body:
I can create a county map using ggplot. I would like to use this map data, and map new boundaries that are aggregates of counties. For example, an equivalent task to mine would be to map state boundaries ("region" variable), rather than county boundaries, using this county map dataset (I have another variable I would use to aggregate counties).

Simply changing the group in ggplot does not work for this. I believe I might need to create new polygon shapes based on the variable I am using to aggregate, but I am not sure. Any thoughts on how I can do this? Any help is greatly appreciated!

library(ggplot2)

# load county map data
m.county <- map_data("county")
head(m.county)
       long      lat group order  region subregion
1 -86.50517 32.34920     1     1 alabama   autauga
2 -86.53382 32.35493     1     2 alabama   autauga
3 -86.54527 32.36639     1     3 alabama   autauga
4 -86.55673 32.37785     1     4 alabama   autauga
5 -86.57966 32.38357     1     5 alabama   autauga
6 -86.59111 32.37785     1     6 alabama   autauga

# map county data with county borders
ggplot(data = m.county) +
  geom_polygon(aes(x=long, y=lat,group=group))

Body:
You can use gUnaryUnion from library(rgeos) to merge polygons, but as you use maps from library maps, this requires few steps:

Get the data from map library, which is what uses get_map

library(ggplot2)
library(sp)
library(rgdal)
library(maps)
library(mapdata)

# adapted from
# http://stackoverflow.com/questions/26062280/converting-a-map-object-to-a-spatialpolygon-object
require(sp)
require(maptools)
county <- map("county", fill = TRUE)

Transform map data into SpatialPolygonsDataFrame of library(sp)

head(county$names)
county.sp <- map2SpatialPolygons(county, IDs = as.factor(county$names),
                                 proj4string = CRS("+proj=longlat +datum=WGS84"))

# Add information data of the polygons
region <- sapply(strsplit(county$names, ","), function(x) x[1])
subregion <- sapply(strsplit(county$names, ","), function(x) x[2])
subregion[is.na(subregion)] <- region[is.na(subregion)]

# Create the SpatialPolygonsDataFrame
county.sp.data <- SpatialPolygonsDataFrame(
  county.sp,
  data = data.frame(region = region,
                    subregion = subregion),
  match.ID = FALSE)

Merge polygons according to region using gUnaryUnion

Because maps from library maps is not clean in terms of topology, you need to use a buffer as a trick to clean it.

library(rgeos)
# Because of topology problems
county.sp.data.buffer <- gBuffer(county.sp.data, byid = TRUE, width = 0)
# Merge polygons according to region
county.region <- gUnaryUnion(county.sp.data.buffer,
                             id = county.sp.data.buffer@data$region)

Transform back as a dataset suitable for ggplot

Use fortify to be able to plot the spatialdata with ggplot

county.fortify <- fortify(county.region)

ggplot(data = county.fortify) +
  geom_polygon(aes(x=long, y=lat, fill=group)) +
  guides(fill = FALSE)


问:
how to get data usage from settings in android
I'm trying to get 3g and wifi usage from Settings page in android, is there anyway to do that, i can set an intent Settings data usage page, code is below;

```<code>Intent intent = new Intent();
    intent.setComponent(new ComponentName("com.android.settings","com.android.settings.Settings$DataUsageSummaryActivity"));

    startActivity(intent);
</code>```

But is there any way to reach these intent's component and to get data from those components.

Thankss..

答:
Yes you can programmatically get the data usage

```<code>// Get running processes
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningApps = manager.getRunningAppProcesses();

for (RunningAppProcessInfo runningApp : runningApps) {

  // Get UID of the selected process
  int uid = ((RunningAppProcessInfo)getListAdapter().getItem(position)).uid;

  // Get traffic data
  long received = TrafficStats.getUidRxBytes(uid);
  long send   = TrafficStats.getUidTxBytes(uid);
  Log.v("" + uid , "Send :" + send + ", Received :" + received);
}
</code>```

Try this way
And You can also refer this tutorial
http://www.techrepublic.com/blog/software-engineer/create-a-network-monitor-using-androids-trafficstats-class/

Body:
I'm trying to get 3g and wifi usage from Settings page in android, is there anyway to do that, i can set an intent Settings data usage page, code is below;

Intent intent = new Intent();
    intent.setComponent(new ComponentName("com.android.settings","com.android.settings.Settings$DataUsageSummaryActivity"));

    startActivity(intent);

But is there any way to reach these intent's component and to get data from those components.

Thankss..

Body:
Yes you can programmatically get the data usage

// Get running processes
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningApps = manager.getRunningAppProcesses();

for (RunningAppProcessInfo runningApp : runningApps) {

  // Get UID of the selected process
  int uid = ((RunningAppProcessInfo)getListAdapter().getItem(position)).uid;

  // Get traffic data
  long received = TrafficStats.getUidRxBytes(uid);
  long send   = TrafficStats.getUidTxBytes(uid);
  Log.v("" + uid , "Send :" + send + ", Received :" + received);
}

Try this way
And You can also refer this tutorial
http://www.techrepublic.com/blog/software-engineer/create-a-network-monitor-using-androids-trafficstats-class/


问:
What is the maximum (practical) number of nodes in an Erlang system
I wish to create a platform as a service in the financial markets using Erlang/Elixir. I will provide AWS lambda-style functions in financial markets, but rather than being accessible via web/rest/http, I plan to distribute my own ARM-based hardware terminals to clients (Nvidia Jetson TX2-based or similar, so decent hardware). They will access the functions from these terminals. I want said terminals to be full nodes in the system. So they will use the actor model to message pass to my central servers, and indeed, the terminals might message pass amongst each other if terminal users decide to put their own functions online.

Is this a viable model? Could I run 1000 terminals like this? 100 000? What kinds of limitations might I start bumping into? Is Erlang message routing scalable enough to imagine such a network still being performant if we had soft-real time financial markets streaming data flowing around? (mostly from central servers to terminals, but a good proportion possible moving directly around from terminal to terminal). We could have a system where up to 100k or more different "subscription" data channel processes were available, many of them taking input and producing output every second.

Basically I'd like a canonical guide to the scalability capabilities of an Erlang system something like the above. Ideally I'd also like some guide to the security implications of such a system ie. would global routing tables or any other part of the system be compromisable by a rogue terminal user, or can edge nodes be partly "sealed off" from sensitive parts of the rest of the Erlang network?

Note that I'd want to make heavy use of ports/NIFs for high-compute processes.

答:
You will find a lot of information regarding erlang Architectures is this answer: How scalable is distributed Erlang?

Short answer is, there is a pratical limitation of nodes in a cluster, but this limitation can be breach with federations fairly easily.

EDIT 1/ Further more I would recommend to read this book : Designing for scalability with Erlang/OTP


问:
How to stop CKEditor producing \r\n characters automatically when data is sanitized in PHP?
I am having a problem regarding data coming from CKEditor textarea field. I am using CKEditor 4.4.1. Whenever I try to submit the content of CKEditor it generates characters \r\n again and again. But it happening only when I am sanitizing my incoming data. Here is my function which sanitizes the incoming content -

```<code>// filter user input
public function filter_data($input)
{
    // if magic quotes are on
    if(get_magic_quotes_gpc())
    {
        $input = stripslashes($input);
    }
    $sanitized_data = mysqli_real_escape_string($this->con, trim($input));
    return $sanitized_data;
}
</code>```

And this is how I am calling the above function -

```<code>$post_content = $users_obj->filter_data($_POST['txtpostcontent']);
</code>```

And then I am getting following output in CKEditor -

```<code>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

\r\n\r\n

\r\n\r\n

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

\r\n\r\n
</code>```

But when I don't call the above function then everything is fine and there is no characters like \r\n in my content.

So I want to know how can I stop these characters from being produced automatically by keeping my sanitizing function on? Is there any way I can sanitized my content and also don't get these characters as well? Thanks.

答:
one more thing is helpful :

 $text = str_ireplace(array("\r","\n",'\r','\n'),'', $text);

ContentLicense: CC BY-SA 4.0

Body:
I am having a problem regarding data coming from CKEditor textarea field. I am using CKEditor 4.4.1. Whenever I try to submit the content of CKEditor it generates characters \r\n again and again. But it happening only when I am sanitizing my incoming data. Here is my function which sanitizes the incoming content -

// filter user input
public function filter_data($input)
{
    // if magic quotes are on
    if(get_magic_quotes_gpc())
    {
        $input = stripslashes($input);
    }
    $sanitized_data = mysqli_real_escape_string($this->con, trim($input));
    return $sanitized_data;
}

And this is how I am calling the above function -

$post_content = $users_obj->filter_data($_POST['txtpostcontent']);

And then I am getting following output in CKEditor -

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

\r\n\r\n

\r\n\r\n

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

\r\n\r\n

But when I don't call the above function then everything is fine and there is no characters like \r\n in my content.

So I want to know how can I stop these characters from being produced automatically by keeping my sanitizing function on? Is there any way I can sanitized my content and also don't get these characters as well? Thanks.


问:
Excel IF formula with criteria based on structure of cell contents
I'm trying to figure out if it's possible to arrange to have an IF condition based off the arrangement of text in a cell..

Pretty much I have a bunch of raw data pasted in excel from a web page where the column with the data I need is mixed in with useless text from the webpage.

The data I need is all just unit codes in 8 character alpha numeric form (eg. ASSA2125 PHOS1801)

To extract just the right data I was hoping to write a formula that tested the cell for either characters in that alphanumeric arrangement or perhaps tested for only 8 characters in the cell. eg =IF(J52=AAAA2222,J52,"")

Not sure if such a thing is possible, or if I just need to write the formula some type of way for excel to go looking for that...

答:
You can find string within string using FIND(find_text, within_text, [start_num]) like this:

```<code>=FIND("ASSA2125",J52)
</code>```

If there is no such sting within cell it will throw an #VALUE! error.
To catch this error you can use ISERROR(value) which returns either TRUE or FALSE:

```<code>=ISERROR(FIND("ASSA2125",J52))
</code>```

Now you can wrap this with an IF() statement:

```<code>=IF(ISERROR(FIND("ASSA2125",J52)),"",J52)
</code>```

Body:
You can find string within string using FIND(find_text, within_text, [start_num]) like this:

=FIND("ASSA2125",J52)

If there is no such sting within cell it will throw an #VALUE! error.
To catch this error you can use ISERROR(value) which returns either TRUE or FALSE:

=ISERROR(FIND("ASSA2125",J52))

Now you can wrap this with an IF() statement:

=IF(ISERROR(FIND("ASSA2125",J52)),"",J52)


问:
How to set time like today, yesterday and date on particular item in ListView
I have ListView, it's showing the messages and time like any chat app. I want to show the time stamp like Today,Yesterday and also date in ListView. I have set it into the adapter but it's showing in all row but i want just show the starting like yesterday the message all below it and today the messages should show the today's messages.
I stuck in it, please guys help to solve it!!!

I have tried this it's working fine but i want just show in one row item not in all row item

```<code>public String getSmsTodayYestFromMilli(long msgTimeMillis) {

        Calendar messageTime = Calendar.getInstance();
        messageTime.setTimeInMillis(msgTimeMillis);
        // get Currunt time
        Calendar now = Calendar.getInstance();

        final String strTimeFormate = "h:mm aa";
        final String strDateFormate = "dd/MM/yyyy h:mm aa";

        if (now.get(Calendar.DATE) == messageTime.get(Calendar.DATE)
                &&
                ((now.get(Calendar.MONTH) == messageTime.get(Calendar.MONTH)))
                &&
                ((now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)))
                ) {

//            return "today at " + DateFormat.format(strTimeFormate, messageTime);
            return "Today";

        } else if (
                ((now.get(Calendar.DATE) - messageTime.get(Calendar.DATE)) == 1)
                        &&
                        ((now.get(Calendar.MONTH) == messageTime.get(Calendar.MONTH)))
                        &&
                        ((now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)))
                ) {
//            return "yesterday at " + DateFormat.format(strTimeFormate, messageTime);
            return "Yesterday";
        } else {
            mDay = DateFormat.format(strDateFormate, messageTime) + "";
//            return "date : " + DateFormat.format(strDateFormate, messageTime);
            return DateFormat.format(strDateFormate, messageTime) + "";
        }
    }
</code>```

答: Take a look at this method getRelativeTimeSpanString from DateUtils

Body:
I have ListView, it's showing the messages and time like any chat app. I want to show the time stamp like Today,Yesterday and also date in ListView. I have set it into the adapter but it's showing in all row but i want just show the starting like yesterday the message all below it and today the messages should show the today's messages.
I stuck in it, please guys help to solve it!!!

I have tried this it's working fine but i want just show in one row item not in all row item

public String getSmsTodayYestFromMilli(long msgTimeMillis) {

        Calendar messageTime = Calendar.getInstance();
        messageTime.setTimeInMillis(msgTimeMillis);
        // get Currunt time
        Calendar now = Calendar.getInstance();

        final String strTimeFormate = "h:mm aa";
        final String strDateFormate = "dd/MM/yyyy h:mm aa";

        if (now.get(Calendar.DATE) == messageTime.get(Calendar.DATE)
                &&
                ((now.get(Calendar.MONTH) == messageTime.get(Calendar.MONTH)))
                &&
                ((now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)))
                ) {

//            return "today at " + DateFormat.format(strTimeFormate, messageTime);
            return "Today";

        } else if (
                ((now.get(Calendar.DATE) - messageTime.get(Calendar.DATE)) == 1)
                        &&
                        ((now.get(Calendar.MONTH) == messageTime.get(Calendar.MONTH)))
                        &&
                        ((now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)))
                ) {
//            return "yesterday at " + DateFormat.format(strTimeFormate, messageTime);
            return "Yesterday";
        } else {
            mDay = DateFormat.format(strDateFormate, messageTime) + "";
//            return "date : " + DateFormat.format(strDateFormate, messageTime);
            return DateFormat.format(strDateFormate, messageTime) + "";
        }
    }


问:
Chaining sprite sequences in Corona SDK?
So, I was chaining some sprite sequences recently and it took me a long time, considering the actual simplicity of the chain. I noticed, that if one wanted to do some more complex chains, that it would be extremely frustrating and probably not worth the effort.

This is a very simplified case with a sequence changing method of a sprite object, due to multiple image sheets, which works properly. But as soon as you get more complex, you end up with really hard to read code :

```<code>        function fox:playSeq()
            pcall(function() self:removeEventListener("sprite", self.sequenceChanger) end)
            local counter = 0
            function self.sequenceChanger(event)
                if event.phase == "ended" then
                    counter = counter + 1
                    if counter == 3 then
                        counter = 0
                    end
                    self:setSequence("walking"..(counter + 1))
                    self:play()
                end
            end
            self:addEventListener("sprite", self.sequenceChanger)
            self:play()
        end
</code>```

I was just wondering if anybody here is aware of a plugin (module), that made the process of making a little more complex sprite animations (chaining them) easier.

Thanks for your help!

Greetings, Nils

答:
I did not use sprite animation so far but maybe this advises will be useful for you.
Try

use Spine (no free, Trial version available, export to Corona). Read more: Is Spine Essential For Basic Animation

how to make animations in Corona SDK - see video The Corona SDK - Ep 11 - Animation Sequences on YouTube

some useful tips from Tutorial: Dynamically-optimized sprites

Body:
So, I was chaining some sprite sequences recently and it took me a long time, considering the actual simplicity of the chain. I noticed, that if one wanted to do some more complex chains, that it would be extremely frustrating and probably not worth the effort.

This is a very simplified case with a sequence changing method of a sprite object, due to multiple image sheets, which works properly. But as soon as you get more complex, you end up with really hard to read code :

        function fox:playSeq()
            pcall(function() self:removeEventListener("sprite", self.sequenceChanger) end)
            local counter = 0
            function self.sequenceChanger(event)
                if event.phase == "ended" then
                    counter = counter + 1
                    if counter == 3 then
                        counter = 0
                    end
                    self:setSequence("walking"..(counter + 1))
                    self:play()
                end
            end
            self:addEventListener("sprite", self.sequenceChanger)
            self:play()
        end

I was just wondering if anybody here is aware of a plugin (module), that made the process of making a little more complex sprite animations (chaining them) easier.

Thanks for your help!

Greetings, Nils


问:
percentage not shown in Amcharts
I am plotting a bar graph with amcharts and I wanted to display the percentage on the top of the bar.So below is the code:

```<code>$.ajax({
    url: "https://daturl",
    contentType: "application/json; charset=utf-8",
    type: "GET",
    dataformat: "JSON",
    async: false,
    success: function (data) {
        var amc = AmCharts.makeChart("chartdiv",
        {
            "type": "serial",
            "dataProvider": data,
            "categoryField": "name",
            "startDuration": 1,
            "categoryAxis": {
                "gridPosition": "start"
            },
            "trendLines": [],
            "graphs": [
                {
                    "valueField": "count",
                    "fillColors": "#0095cc",
                    "type": "column",
                    "balloonText": "[[title]] of [[category]]:[[value]]",
                    "fillAlphas": 0.8,
                    "lineAlpha": 0.2,
                    "id": "AmGraph-1",
                    "title": "graph",
                    "labelText": " ",

                    //the percentage calculation function
                    "labelFunction": function (item, data) {
                        var total = 0;
                        console.log(data.length + " is the size of the data in long trips");

                        for (var i = 0; i < data.length; i++) {
                            total += data[i][item.graph.valueField];
                        }

                        var percent = Math.round((item.values.value / total) * 1000) / 10;
                        return percent + "%";
                    }
                }],
            "guides": [],
            "valueAxes": [
                {
                    "id": "ValueAxis-1",
                    "title": "Count",
                    "gridColor": "#FFFFFF",
                    "gridAlpha": 0.2
                }
            ],
            "categoryAxis": {
                "title": "Zone",
                "gridPosition": "start",
                "gridAlpha": 0,
                "tickPosition": "start",
                "tickLength": 20,
                "labelRotation": 24
            },
            "gridAboveGraphs": true,
            "allLabels": [],
            "balloon": {},
            "legend": {
                "enabled": true,
                "useGraphSettings": true
            },
            "titles": [
                {
                    "id": "Title-1",
                    "size": 15,
                    "text": "graph"
                }
            ]
        });
    },
    error: function () {
        alert("error while plotting down graph ");
    }
});
</code>```

So when I run the code the graphs are plotting but the percentages are not shown.Instead they show as NaN. Any help is appreciated

答:
You're using the labelFunction wrong. You can see in the documentation, that the parameters given are a reference to GraphDataItem and the formatted label text.

In your for-loop you actually do total += "   "[0]["value"] which results in total += undefined and cause total to be NaN. That's where to wrong labels come from.

You could access the full dataSet via item.graph.data and make a correct calculation with this.

My suggestion though would be, that you move that for-loop to another place in your script. You basically just sum up the data values over and over again, whenever the graph is drawn. This means this loop runs several hundred to thousand times when you are just resizing the graph. You could just calculate the total sum once and use it in the labelFunction.

Title: percentage not shown in Amcharts

Body:
I am plotting a bar graph with amcharts and I wanted to display the percentage on the top of the bar.So below is the code:

$.ajax({
    url: "https://daturl",
    contentType: "application/json; charset=utf-8",
    type: "GET",
    dataformat: "JSON",
    async: false,
    success: function (data) {
        var amc = AmCharts.makeChart("chartdiv",
        {
            "type": "serial",
            "dataProvider": data,
            "categoryField": "name",
            "startDuration": 1,
            "categoryAxis": {
                "gridPosition": "start"
            },
            "trendLines": [],
            "graphs": [
                {
                    "valueField": "count",
                    "fillColors": "#0095cc",
                    "type": "column",
                    "balloonText": "[[title]] of [[category]]:[[value]]",
                    "fillAlphas": 0.8,
                    "lineAlpha": 0.2,
                    "id": "AmGraph-1",
                    "title": "graph",
                    "labelText": " ",

                    //the percentage calculation function
                    "labelFunction": function (item, data) {
                        var total = 0;
                        console.log(data.length + " is the size of the data in long trips");

                        for (var i = 0; i < data.length; i++) {
                            total += data[i][item.graph.valueField];
                        }

                        var percent = Math.round((item.values.value / total) * 1000) / 10;
                        return percent + "%";
                    }
                }],
            "guides": [],
            "valueAxes": [
                {
                    "id": "ValueAxis-1",
                    "title": "Count",
                    "gridColor": "#FFFFFF",
                    "gridAlpha": 0.2
                }
            ],
            "categoryAxis": {
                "title": "Zone",
                "gridPosition": "start",
                "gridAlpha": 0,
                "tickPosition": "start",
                "tickLength": 20,
                "labelRotation": 24
            },
            "gridAboveGraphs": true,
            "allLabels": [],
            "balloon": {},
            "legend": {
                "enabled": true,
                "useGraphSettings": true
            },
            "titles": [
                {
                    "id": "Title-1",
                    "size": 15,
                    "text": "graph"
                }
            ]
        });
    },
    error: function () {
        alert("error while plotting down graph ");
    }
});

So when I run the code the graphs are plotting but the percentages are not shown.Instead they show as NaN. Any help is appreciated


问:
How to acces a model attribute from another model
I newbie with Django Framework and I wish to know if is possible I access a attribute from the model X via model Y...In my case a have a model called "Evaluation" this model receive the scores of evaluations of the candidates..they have a ForeignKey that receive the Candidate(what is another model) and a PositiveIntegerField with receive a score what I want is access this PositiveIntegerField via Candidate model, it's possible?

My models.py:

```<code>from django.db import models
from jsonfield import JSONField
from site_.settings import MEDIA_ROOT
from django.core.validators import MaxValueValidator

class Criterion(models.Model):
    label = models.CharField(max_length=100)

    def  __str__(self):
        return self.label

class Candidate(models.Model):
    name = models.CharField(max_length=100)
    e_mail = models.EmailField(max_length=100, default = '')
    github = models.URLField(default = '')
    linkedin = models.URLField(max_length=100, default = '')
    cover_letter = models.TextField(default = '')
    higher_education = models.BooleanField(default = False)
    docfile = models.FileField(upload_to='/home/douglas/Documentos/Django/my-second-blog/site_/media', null=True, blank=True)

    def  __str__(self):
        return self.name

class Evaluation(models.Model):
    candidate = models.ForeignKey(Candidate)
    criterion = models.ForeignKey(Criterion, default='')
    score = models.PositiveIntegerField(default = 0, validators=[MaxValueValidator(10)])
    appraiser = models.ForeignKey('auth.User')

    def  __str__(self):
        return str(self.candidate)

#model de teste
class Teste(models.Model):
    nome = models.CharField(max_length=10)

    def  __str__(self):
        return str(self.nome)
</code>```

答:
You can use

```<code>Candidate_obj.evaluation_set.all()[0].score
</code>```

Since you are using a Foriegn Key, there is chance to multiple Evaluation objects.So Candidate_obj.evaluation_set.all() may get more than one objects.

Body:
I newbie with Django Framework and I wish to know if is possible I access a attribute from the model X via model Y...In my case a have a model called "Evaluation" this model receive the scores of evaluations of the candidates..they have a ForeignKey that receive the Candidate(what is another model) and a PositiveIntegerField with receive a score what I want is access this PositiveIntegerField via Candidate model, it's possible?

My models.py:

from django.db import models
from jsonfield import JSONField
from site_.settings import MEDIA_ROOT
from django.core.validators import MaxValueValidator

class Criterion(models.Model):
    label = models.CharField(max_length=100)

    def  __str__(self):
        return self.label

class Candidate(models.Model):
    name = models.CharField(max_length=100)
    e_mail = models.EmailField(max_length=100, default = '')
    github = models.URLField(default = '')
    linkedin = models.URLField(max_length=100, default = '')
    cover_letter = models.TextField(default = '')
    higher_education = models.BooleanField(default = False)
    docfile = models.FileField(upload_to='/home/douglas/Documentos/Django/my-second-blog/site_/media', null=True, blank=True)

    def  __str__(self):
        return self.name

class Evaluation(models.Model):
    candidate = models.ForeignKey(Candidate)
    criterion = models.ForeignKey(Criterion, default='')
    score = models.PositiveIntegerField(default = 0, validators=[MaxValueValidator(10)])
    appraiser = models.ForeignKey('auth.User')

    def  __str__(self):
        return str(self.candidate)

#model de teste
class Teste(models.Model):
    nome = models.CharField(max_length=10)

    def  __str__(self):
        return str(self.nome)

Body:
You can use

Candidate_obj.evaluation_set.all()[0].score

Since you are using a Foriegn Key, there is chance to multiple Evaluation objects.So Candidate_obj.evaluation_set.all() may get more than one objects.


问:
Extract a tar file using tar -xzvf
I want to extract a tar file that I obtained by using: curl -O https://github.com/fhcrc/seqmagick/archive/0.6.1.tar.gz
but when I try: tar -xzvf 0.6.1
I get tar: Error opening archive: Failed to open '0.6.1'

I see the file in the directory as 0.6.1.tar.gz and  I tried to do tar -xzvf 0.6.1.tar.gz but I get error Error exit delayed from previous errors.

Any suggestion will be much appreciated.

答:
I use to manipulate curl issues like bellow.
I first use -o- option with curl. This forces curl to "dump" contents in screen - in real time.

In your case the situation is like advised by merlin2011 :

```<code>$ curl -o- "https://github.com/fhcrc/seqmagick/archive/0.6.1.tar.gz"
<html><body>You are being <a href="https://codeload.github.com/fhcrc/seqmagick/tar.gz/0.6.1">redirected</a>.</body></html>
</code>```

PS: With -o- option, if the archive was correct would flood the screen with many unrecognized characters... So handle with care or pipt to tar

This movement can be solved with -L option of curl, which follows the moved links.

I use to include also -s for "silent" operation. Combine with a pipe to tar to see on screen the files content included in this archive without downloading it:

```<code>$ curl -sL -o- "https://github.com/fhcrc/seqmagick/archive/0.6.1.tar.gz" |tar -zt
seqmagick-0.6.1/
seqmagick-0.6.1/.gitignore
seqmagick-0.6.1/.travis.yml
seqmagick-0.6.1/CHANGELOG
seqmagick-0.6.1/CONTRIB
seqmagick-0.6.1/INSTALL
seqmagick-0.6.1/LICENSE
seqmagick-0.6.1/MANIFEST.in
<much more files here>
</code>```

So now we have hit the correct archive. You can now use -O option to store the correct file in your current working directory.

```<code>$ curl -sLO "https://github.com/fhcrc/seqmagick/archive/0.6.1.tar.gz"
$ ls -l *.tar.gz
-rw-r--r-- 1 root root 672141 Apr  3 11:37 0.6.1.tar.gz
$ tar -tf 0.6.1.tar.gz
seqmagick-0.6.1/
seqmagick-0.6.1/.gitignore
seqmagick-0.6.1/.travis.yml
seqmagick-0.6.1/CHANGELOG
seqmagick-0.6.1/CONTRIB
seqmagick-0.6.1/INSTALL
seqmagick-0.6.1/LICENSE
seqmagick-0.6.1/MANIFEST.in
<much more files follow>
</code>```

Title: Extract a tar file using tar -xzvf

Body:
I use to manipulate curl issues like bellow.
I first use -o- option with curl. This forces curl to "dump" contents in screen - in real time.

In your case the situation is like advised by merlin2011 :

$ curl -o- "https://github.com/fhcrc/seqmagick/archive/0.6.1.tar.gz"
<html><body>You are being <a href="https://codeload.github.com/fhcrc/seqmagick/tar.gz/0.6.1">redirected</a>.</body></html>

PS: With -o- option, if the archive was correct would flood the screen with many unrecognized characters... So handle with care or pipt to tar

This movement can be solved with -L option of curl, which follows the moved links.

I use to include also -s for "silent" operation. Combine with a pipe to tar to see on screen the files content included in this archive without downloading it:

$ curl -sL -o- "https://github.com/fhcrc/seqmagick/archive/0.6.1.tar.gz" |tar -zt
seqmagick-0.6.1/
seqmagick-0.6.1/.gitignore
seqmagick-0.6.1/.travis.yml
seqmagick-0.6.1/CHANGELOG
seqmagick-0.6.1/CONTRIB
seqmagick-0.6.1/INSTALL
seqmagick-0.6.1/LICENSE
seqmagick-0.6.1/MANIFEST.in
<much more files here>

So now we have hit the correct archive. You can now use -O option to store the correct file in your current working directory.

$ curl -sLO "https://github.com/fhcrc/seqmagick/archive/0.6.1.tar.gz"
$ ls -l *.tar.gz
-rw-r--r-- 1 root root 672141 Apr  3 11:37 0.6.1.tar.gz
$ tar -tf 0.6.1.tar.gz
seqmagick-0.6.1/
seqmagick-0.6.1/.gitignore
seqmagick-0.6.1/.travis.yml
seqmagick-0.6.1/CHANGELOG
seqmagick-0.6.1/CONTRIB
seqmagick-0.6.1/INSTALL
seqmagick-0.6.1/LICENSE
seqmagick-0.6.1/MANIFEST.in
<much more files follow>


问:
Java return array from class
So I have 2 classes that I use:

```<code>public class Vote {

      public String vote;

       public Vote(String vote) {
            this.vote = vote;
        }

        public String getvote() {
            return vote;
        }
}
</code>```

And then the other one that returns votes array:

```<code>public class Campaign {

    private String title;
    private Vote[] votes;

    public Campaign(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public Vote[] getvotes() {
        return votes;
    }
    }
</code>```

And in main im using this code:

```<code>public class maintest {

public static void main(String[] args) {
    Campaign first= new Campaign("test");
    Vote pvote = new Vote("vote1222");
    System.out.println(first.getTitle() + " " + " " + first.getvotes());
}
}
</code>```

In the end I get value null. However I want to get "vote1222" also if I add more campaigns i want to retrieve more votes as well.

答:
You need to create a setter in your Campaign class:

```<code>public void setVotes(Vote[] votes) {
    this.votes = votes;
}
</code>```

In your main you must invoke this method:

```<code>public static void main(String[] args) {
    Campaign first= new Campaign("test");
    Vote pvote = new Vote("vote1222");
    Vote[] votes = new Vote[] { pvote };
    first.setVotes(votes);
    System.out.println(first.getTitle() + " " + " " + Arrays.toString(first.getvotes()));
}
</code>```

As you can read in the comments, you should use Arrays.toString.

Thanks to Fildur: in Vote you need to overwrite toString:

```<code>@Override
public String toString() {
    return vote;
}
</code>```

Title: Java return array from class

Body:
So I have 2 classes that I use:

public class Vote {

      public String vote;

       public Vote(String vote) {
            this.vote = vote;
        }

        public String getvote() {
            return vote;
        }
}

And then the other one that returns votes array:

public class Campaign {

    private String title;
    private Vote[] votes;

    public Campaign(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public Vote[] getvotes() {
        return votes;
    }
    }

And in main im using this code:

public class maintest {

public static void main(String[] args) {
    Campaign first= new Campaign("test");
    Vote pvote = new Vote("vote1222");
    System.out.println(first.getTitle() + " " + " " + first.getvotes());
}
}

In the end I get value null. However I want to get "vote1222" also if I add more campaigns i want to retrieve more votes as well.

Body:
You need to create a setter in your Campaign class:

public void setVotes(Vote[] votes) {
    this.votes = votes;
}

In your main you must invoke this method:

public static void main(String[] args) {
    Campaign first= new Campaign("test");
    Vote pvote = new Vote("vote1222");
    Vote[] votes = new Vote[] { pvote };
    first.setVotes(votes);
    System.out.println(first.getTitle() + " " + " " + Arrays.toString(first.getvotes()));
}

As you can read in the comments, you should use Arrays.toString.

Thanks to Fildur: in Vote you need to overwrite toString:

@Override
public String toString() {
    return vote;
}


问:
How to use workbook activate application class event with automation
I need workbook activate application class event code which minimizes "Workbook Window" whenever Workbook is activated.

So, whenever C:\Book1.xlsx is activated then minimize "Workbook Window".

Following code just for test begining;

```<code>Imports Microsoft.Office.Interop

Public Class Form1

Public WithEvents wb1 As Excel.Workbook

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    Dim xlApp As New Excel.Application
    xlApp.Visible = True

    Threading.Thread.Sleep(10000)

    Dim wb1 As Excel.Workbook
    wb1 = xlApp.Workbooks.Open("C:\Book1.xlsx")

    Threading.Thread.Sleep(100000000)
End Sub

End Class
</code>```

Following link may support you;

https://support.microsoft.com/en-us/help/822750/how-to-handle-events-for-excel-by-using-visual-basic-.net

答:
First thing to do is move the declaration of xlApp to class level and declare WithEvents:

```<code>Private WithEvents xlApp As New Excel.Application
</code>```

Now we can make use of the events that come with Excel.Application, specifically WindowActivate:

Occurs when any workbook window is activated.

```<code>Private Sub xlApp_WindowActivate(Wb As Excel.Workbook, Wn As Excel.Window) Handles xlApp.WindowActivate
    xlApp.WindowState = Excel.XlWindowState.xlMinimized
End Sub
</code>```

And WindowResize:

Occurs when any workbook window is resized.

```<code>Private Sub xlApp_WindowResize(Wb As Excel.Workbook, Wn As Excel.Window) Handles xlApp.WindowResize
    xlApp.WindowState = Excel.XlWindowState.xlMinimized
End Sub
</code>```

As you can see, within these handlers, I am setting the WindowState property to xlMinimized. This means that whenever I try and bring up the Workbook it becomes minimised again.

In full your code would look something similar to this:

```<code>Public Class Form1

    Private WithEvents xlApp As New Excel.Application

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

        xlApp.Visible = True

        Dim wb1 As Excel.Workbook
        wb1 = xlApp.Workbooks.Open("C:\Book1.xlsx")

    End Sub

    Private Sub xlApp_WindowActivate(Wb As Excel.Workbook, Wn As Excel.Window) Handles xlApp.WindowActivate
        xlApp.WindowState = Excel.XlWindowState.xlMinimized
    End Sub

    Private Sub xlApp_WindowResize(Wb As Excel.Workbook, Wn As Excel.Window) Handles xlApp.WindowResize
        xlApp.WindowState = Excel.XlWindowState.xlMinimized
    End Sub

End Class
</code>```

Body:
I need workbook activate application class event code which minimizes "Workbook Window" whenever Workbook is activated.

So, whenever C:\Book1.xlsx is activated then minimize "Workbook Window".

Following code just for test begining;

Imports Microsoft.Office.Interop

Public Class Form1

Public WithEvents wb1 As Excel.Workbook

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    Dim xlApp As New Excel.Application
    xlApp.Visible = True

    Threading.Thread.Sleep(10000)

    Dim wb1 As Excel.Workbook
    wb1 = xlApp.Workbooks.Open("C:\Book1.xlsx")

    Threading.Thread.Sleep(100000000)
End Sub

End Class

Following link may support you;

https://support.microsoft.com/en-us/help/822750/how-to-handle-events-for-excel-by-using-visual-basic-.net

Body:
First thing to do is move the declaration of xlApp to class level and declare WithEvents:

Private WithEvents xlApp As New Excel.Application

Now we can make use of the events that come with Excel.Application, specifically WindowActivate:

Occurs when any workbook window is activated.

Private Sub xlApp_WindowActivate(Wb As Excel.Workbook, Wn As Excel.Window) Handles xlApp.WindowActivate
    xlApp.WindowState = Excel.XlWindowState.xlMinimized
End Sub

And WindowResize:

Occurs when any workbook window is resized.

Private Sub xlApp_WindowResize(Wb As Excel.Workbook, Wn As Excel.Window) Handles xlApp.WindowResize
    xlApp.WindowState = Excel.XlWindowState.xlMinimized
End Sub

As you can see, within these handlers, I am setting the WindowState property to xlMinimized. This means that whenever I try and bring up the Workbook it becomes minimised again.

In full your code would look something similar to this:

Public Class Form1

    Private WithEvents xlApp As New Excel.Application

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

        xlApp.Visible = True

        Dim wb1 As Excel.Workbook
        wb1 = xlApp.Workbooks.Open("C:\Book1.xlsx")

    End Sub

    Private Sub xlApp_WindowActivate(Wb As Excel.Workbook, Wn As Excel.Window) Handles xlApp.WindowActivate
        xlApp.WindowState = Excel.XlWindowState.xlMinimized
    End Sub

    Private Sub xlApp_WindowResize(Wb As Excel.Workbook, Wn As Excel.Window) Handles xlApp.WindowResize
        xlApp.WindowState = Excel.XlWindowState.xlMinimized
    End Sub

End Class


问:
How to trace the surface area as well as smoothen a specific region in an image using MATLAB
I have an image with 6 colors each indicating a value. I had obtained an image as shown below.

I need to smoothen the edges and then find out the area as well as the surface area of that region. The second image shows a black line drawn in the edges which indicates that I need to smoothen the edges in such a way.

I had used segmentation to create a mask as shown in the third image, and then obtain a segmented image using the code following the image.

I have used the following code for generating till the masked image.
Source :  How to segment

```<code> imshow(Out1)
 str = 'Click to select initial contour location. Double-click to confirm    and proceed.';
 title(str,'Color','b','FontSize',12);
 disp(sprintf('\nNote: Click close to object boundaries for more accurate   result.'));
 mask = roipoly;
 figure, imshow(mask)
 title('Initial MASK');
 maxIterations = 3000;
 bw = activecontour(Out1, mask, maxIterations, 'Chan-Vese');

 % Display segmented image
 figure, imshow(bw)
 title('Segmented Image');
</code>```

In order to use the 'activecontour' function my image needs to be a grey-scale image, which I'm not being able to convert to greyscale and back. Also to find out surface area/ area of the region is there any inbuilt function. Please help thanks.

答:
use im2double, im2uint8, etc. to convert binary image to grayscale.

use bwarea or regionprops to find the region area.

Body:
I have an image with 6 colors each indicating a value. I had obtained an image as shown below.

I need to smoothen the edges and then find out the area as well as the surface area of that region. The second image shows a black line drawn in the edges which indicates that I need to smoothen the edges in such a way.

I had used segmentation to create a mask as shown in the third image, and then obtain a segmented image using the code following the image.

I have used the following code for generating till the masked image.
Source :  How to segment

 imshow(Out1)
 str = 'Click to select initial contour location. Double-click to confirm    and proceed.';
 title(str,'Color','b','FontSize',12);
 disp(sprintf('\nNote: Click close to object boundaries for more accurate   result.'));
 mask = roipoly;
 figure, imshow(mask)
 title('Initial MASK');
 maxIterations = 3000;
 bw = activecontour(Out1, mask, maxIterations, 'Chan-Vese');

 % Display segmented image
 figure, imshow(bw)
 title('Segmented Image');

In order to use the 'activecontour' function my image needs to be a grey-scale image, which I'm not being able to convert to greyscale and back. Also to find out surface area/ area of the region is there any inbuilt function. Please help thanks.


问:
EF builds EntityCollection, but I (think I) want IQueryable
I have an entity A with a simple navigation property B.  For any given instance of A, we expect several related thousand instances of B.

There is no case where I call something like:

```<code>foreach(var x in A.B) { ... }
</code>```

Instead, I'm only interested in doing aggregate operations such as

```<code>var statY = A.B.Where(o => o.Property == "Y");
var statZ = A.B.Where(o => o.CreateDate > DateTime.Now.AddDays(-1));
</code>```

As far as I can tell, EF instantiates thousands of references to B and does these operations in memory.  This is because navigation properties use EntityCollection.  Instead, I'd like it to perform these queries at the SQL level if possible.

My current hunch is that Navigation Properties may not be the right way to go.  I'm not attached to EF, so I am open to other approaches.  But I'd be very interested to know the right way to do this under EF if possible.

(I'm using EF4.)

答:
There's one thing you should know. Members that derives from IQueryable<> are executed on the server, not in memory. Members which are derived from IEnumerable<> is executed in memory.
for example

```<code>var someEntities = db.SomeEntities; <-- returns an IQueryable<> object. no data fetched. SomeEntities table may contain thousands of rows, but we are not fetching it yet, we are just building a query.
someEntities = someEntities.Where(s => s.Id > 100 && s.Id < 200); <-- creates expression tree with where statement. The query is not executed yet and data is not fetched on the client. We just tell EF to perform a where filter when query will execute. This statement too returns an IQueryable<> object.
var entities = someEntities.AsEnumerable(); <-- here we tell EF to execute query. now entities will be fetched and any additional linq query will be performed in memory.
</code>```

you can also fetch the data using foreach, calling ToArray() or ToList<>.

Hope you understand what I mean, and sorry for my english :)

ContentLicense: CC BY-SA 2.5

Body:
I have an entity A with a simple navigation property B.  For any given instance of A, we expect several related thousand instances of B.

There is no case where I call something like:

foreach(var x in A.B) { ... }

Instead, I'm only interested in doing aggregate operations such as

var statY = A.B.Where(o => o.Property == "Y");
var statZ = A.B.Where(o => o.CreateDate > DateTime.Now.AddDays(-1));

As far as I can tell, EF instantiates thousands of references to B and does these operations in memory.  This is because navigation properties use EntityCollection.  Instead, I'd like it to perform these queries at the SQL level if possible.

My current hunch is that Navigation Properties may not be the right way to go.  I'm not attached to EF, so I am open to other approaches.  But I'd be very interested to know the right way to do this under EF if possible.

(I'm using EF4.)

Body:
There's one thing you should know. Members that derives from IQueryable<> are executed on the server, not in memory. Members which are derived from IEnumerable<> is executed in memory.
for example

var someEntities = db.SomeEntities; <-- returns an IQueryable<> object. no data fetched. SomeEntities table may contain thousands of rows, but we are not fetching it yet, we are just building a query.
someEntities = someEntities.Where(s => s.Id > 100 && s.Id < 200); <-- creates expression tree with where statement. The query is not executed yet and data is not fetched on the client. We just tell EF to perform a where filter when query will execute. This statement too returns an IQueryable<> object.
var entities = someEntities.AsEnumerable(); <-- here we tell EF to execute query. now entities will be fetched and any additional linq query will be performed in memory.

you can also fetch the data using foreach, calling ToArray() or ToList<>.

Hope you understand what I mean, and sorry for my english :)


问:
HTML input field height different in different browsers

Current Situation

On a simple website I have an input control with a fix height where I have a text with a certain font size. I want that text to show up vertically aligned in the middle of the input field. But even though I used a reset css (link here) and setting the -webkit-appearance to none it still is not centered.

You can see that for IE the padding at the top is higher, for iOS it is even worse. There are 12 more pixels padding.

Some Code

HTML:

```<code><!-- time -->
<input type="text" class="meeting-time" style="-webkit-appearance: none; padding: 0px; inn" value="00:00"/>
</code>```

CSS:

```<code>.meeting-time {
    margin: 0;
    padding: 0;
    width: 100px;
    height: 37px;
    text-align: center;
    font-family: "roboto",sans-serif;
    font-style: normal;
    font-size: 37px;
    font-weight: 300;
    background: yellow;
    vertical-align: middle;
    -webkit-appearance: none;
}
</code>```

Actual Question

How can I have a text field where the text is vertically aligned for all browsers.

I know this has been asked a couple of times already, but the solutions proposed didn't work until now. It's probably something trivial that I miss.

答:
UPDATE

Took @scooterlord's advice about removing height and it fixed 90% of the problem. The 10% was still that 4px offset using iOS which was the same issue with my first solution. The difference is, with height no longer specified, I was able to add 4px padding-top to align iOS and it wasn't pushing the font on the desktop browsers. So basically:

Remove height

Add padding-top: 4px;

See Snippet 2 and/or CODEPEN

OLD

There were some changes that were more for aesthetics than for cross-browser compatibilty of the changes that have significant importance they are denoted with a /* ✎ */.  Tested in Chrome, Firefox, Edge and IE. I tried my iPhone 5, but I lost my patience trying to navigate to this page (I have 5 left thumbs )

IE11

SNIPPET 1

html {
  /* ✎ */
  font: 300 16px/1.428 "roboto", sans-serif;
  /* ✎ */
  box-sizing: border-box;
}

html,
body {
  width: 100%;
  height: 100%;
}

*,
*::before,
*::after {
  /* ✎ */
  box-sizing: border-box;
  /* ✎ */
  margin: 0;
  /* ✎ */
  padding: 0;
  /* ✎ */
  border: 0;
}

.meeting-time {
  width: 100px;
  height: 37px;
  text-align: center;
  /* ✎ */
  font: inherit;
  /* ✎ */
  font-size: 2.3125rem;
  /* ✎ */
  line-height: 100%;
  background: yellow;
  /* ✎ */
  vertical-align: middle;
  -webkit-appearance: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?family=Roboto:300" rel="stylesheet">

<input type="text" class="meeting-time" style="-webkit-appearance: none; padding: 0px;" value="00:00" /></code>```

SNIPPET 2

html {
  /* ✎ */
  font: 300 16px/1.428 "roboto", sans-serif;
  /* ✎ */
  box-sizing: border-box;
}

html,
body {
  width: 100%;
  height: 100%;
}

*,
*::before,
*::after {
  /* ✎ */
  box-sizing: border-box;
  /* ✎ */
  margin: 0;
  /* ✎ */
  padding: 0;
  /* ✎ */
  border: 0;
}

/* For iOS BEGIN */

/* ✎ */

input[type=text],
input[type=email],
input[type=tel],
input[type=url],
input[type=search] {
  appearance: none;
  -moz-appearance: none;
  -webkit-appearance: none;
  border-radius: 0;
  box-shadow: none;
}

/* For iOS  END */

/* For demo (optional) BEGIN */

main {
  height: auto;
  width: 100%;
  padding: 2vh 2vw;
}

header {
  display: table;
}

hgroup {
  display: table-row;
}

h5 {
  text-align: right;
  font: inherit;
  font-weight: 700;
  font-size: 1.2rem;
  width: 150px;
}

h6 {
  display: table-cell;
  width: 100px;
  font: inherit;
}

hr {
  height: 0;
  margin: 1.25em auto;
  border: 0 none transparent;
  border-bottom: 1px solid #000;
}

hr:nth-of-type(even) {
  border-bottom: 1px dashed #000;
}

/* For demo (optional) END */

/* Example 1 */

.ex1Time {
  width: 100px;
  height: 37px;
  text-align: center;
  font: inherit;
  font-size: 37px;
  background: yellow;
}

/* Example 2 */

.ex2Time {
  width: 5ch;
  text-align: center;
  font: inherit;
  font-size: 2.3125rem;
  background: yellow;
  padding-top: 4px;
}

/* Example 3 */

.ex3Time {
  width: 5ch;
  text-align: center;
  font-family: Arial;
  font-size: 2.3125rem;
  background: yellow;
  padding-top: 4px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href='https://fonts.googleapis.com/css?family=Roboto:300' rel='stylesheet'>

<main>

  <hr/>
  <header>
    <hgroup>
      <h6>Original Code</h6>
      <h5>Example 1</h5>
    </hgroup>
  </header>
  <hr/>

  <input type="text" class="ex1Time" value="00:00">

  <input type="text" class="ex1Time" value="07:22">

  <input type="text" class="ex1Time" value="11:11">

  <input type="text" class="ex1Time" value="12:34">

  <hr/>
  <header>
    <hgroup>
      <h6 style='display:table-row'>Font dependent lengths are measured in ch units</h6>
      <h6 style='display:table-row;width:400px'>4 inputs Within .ex2Align</h6>
      <h6> </h6>
      <h5>Example 2</h5>
    </hgroup>
  </header>
  <hr/>

  <input type="text" class="ex2Time" value="00:00">

  <input type="text" class="ex2Time" value="07:22">

  <input type="text" class="ex2Time" value="11:11">

  <input type="text" class="ex2Time" value="12:34">

  <hr/>
  <header>
    <hgroup>
      <h6 style='display:table-row'>Using Arial instead of Roboto</h6>
      <h6 style='display:table-row;width:400px'>4 inputs Within .ex3Align</h6>
      <h6> </h6>
      <h5>Example 3</h5>
    </hgroup>
  </header>
  <hr/>

  <input type="text" class="ex3Time" value="00:00">

  <input type="text" class="ex3Time" value="07:22">

  <input type="text" class="ex3Time" value="11:11">

  <input type="text" class="ex3Time" value="12:34">

  <hr/>
</main></code>```

Body:
Current Situation

On a simple website I have an input control with a fix height where I have a text with a certain font size. I want that text to show up vertically aligned in the middle of the input field. But even though I used a reset css (link here) and setting the -webkit-appearance to none it still is not centered.

You can see that for IE the padding at the top is higher, for iOS it is even worse. There are 12 more pixels padding.

Some Code

HTML:

<input type="text" class="meeting-time" style="-webkit-appearance: none; padding: 0px; inn" value="00:00"/>

CSS:

.meeting-time {
    margin: 0;
    padding: 0;
    width: 100px;
    height: 37px;
    text-align: center;
    font-family: "roboto",sans-serif;
    font-style: normal;
    font-size: 37px;
    font-weight: 300;
    background: yellow;
    vertical-align: middle;
    -webkit-appearance: none;
}

Actual Question

How can I have a text field where the text is vertically aligned for all browsers.

I know this has been asked a couple of times already, but the solutions proposed didn't work until now. It's probably something trivial that I miss.

Body:
UPDATE

Took @scooterlord's advice about removing height and it fixed 90% of the problem. The 10% was still that 4px offset using iOS which was the same issue with my first solution. The difference is, with height no longer specified, I was able to add 4px padding-top to align iOS and it wasn't pushing the font on the desktop browsers. So basically:

Remove height

Add padding-top: 4px;

See Snippet 2 and/or CODEPEN

OLD

There were some changes that were more for aesthetics than for cross-browser compatibilty of the changes that have significant importance they are denoted with a /* ✎ */.  Tested in Chrome, Firefox, Edge and IE. I tried my iPhone 5, but I lost my patience trying to navigate to this page (I have 5 left thumbs )

IE11

SNIPPET 1

html {
  /* ✎ */
  font: 300 16px/1.428 "roboto", sans-serif;
  /* ✎ */
  box-sizing: border-box;
}

html,
body {
  width: 100%;
  height: 100%;
}

*,
*::before,
*::after {
  /* ✎ */
  box-sizing: border-box;
  /* ✎ */
  margin: 0;
  /* ✎ */
  padding: 0;
  /* ✎ */
  border: 0;
}

.meeting-time {
  width: 100px;
  height: 37px;
  text-align: center;
  /* ✎ */
  font: inherit;
  /* ✎ */
  font-size: 2.3125rem;
  /* ✎ */
  line-height: 100%;
  background: yellow;
  /* ✎ */
  vertical-align: middle;
  -webkit-appearance: none;
}

<link href="https://fonts.googleapis.com/css?family=Roboto:300" rel="stylesheet">

<input type="text" class="meeting-time" style="-webkit-appearance: none; padding: 0px;" value="00:00" />

SNIPPET 2

html {
  /* ✎ */
  font: 300 16px/1.428 "roboto", sans-serif;
  /* ✎ */
  box-sizing: border-box;
}

html,
body {
  width: 100%;
  height: 100%;
}

*,
*::before,
*::after {
  /* ✎ */
  box-sizing: border-box;
  /* ✎ */
  margin: 0;
  /* ✎ */
  padding: 0;
  /* ✎ */
  border: 0;
}

/* For iOS BEGIN */

/* ✎ */

input[type=text],
input[type=email],
input[type=tel],
input[type=url],
input[type=search] {
  appearance: none;
  -moz-appearance: none;
  -webkit-appearance: none;
  border-radius: 0;
  box-shadow: none;
}

/* For iOS  END */

/* For demo (optional) BEGIN */

main {
  height: auto;
  width: 100%;
  padding: 2vh 2vw;
}

header {
  display: table;
}

hgroup {
  display: table-row;
}

h5 {
  text-align: right;
  font: inherit;
  font-weight: 700;
  font-size: 1.2rem;
  width: 150px;
}

h6 {
  display: table-cell;
  width: 100px;
  font: inherit;
}

hr {
  height: 0;
  margin: 1.25em auto;
  border: 0 none transparent;
  border-bottom: 1px solid #000;
}

hr:nth-of-type(even) {
  border-bottom: 1px dashed #000;
}

/* For demo (optional) END */

/* Example 1 */

.ex1Time {
  width: 100px;
  height: 37px;
  text-align: center;
  font: inherit;
  font-size: 37px;
  background: yellow;
}

/* Example 2 */

.ex2Time {
  width: 5ch;
  text-align: center;
  font: inherit;
  font-size: 2.3125rem;
  background: yellow;
  padding-top: 4px;
}

/* Example 3 */

.ex3Time {
  width: 5ch;
  text-align: center;
  font-family: Arial;
  font-size: 2.3125rem;
  background: yellow;
  padding-top: 4px;
}

<link href='https://fonts.googleapis.com/css?family=Roboto:300' rel='stylesheet'>

<main>

  <hr/>
  <header>
    <hgroup>
      <h6>Original Code</h6>
      <h5>Example 1</h5>
    </hgroup>
  </header>
  <hr/>

  <input type="text" class="ex1Time" value="00:00">

  <input type="text" class="ex1Time" value="07:22">

  <input type="text" class="ex1Time" value="11:11">

  <input type="text" class="ex1Time" value="12:34">

  <hr/>
  <header>
    <hgroup>
      <h6 style='display:table-row'>Font dependent lengths are measured in ch units</h6>
      <h6 style='display:table-row;width:400px'>4 inputs Within .ex2Align</h6>
      <h6>&nbsp;</h6>
      <h5>Example 2</h5>
    </hgroup>
  </header>
  <hr/>

  <input type="text" class="ex2Time" value="00:00">

  <input type="text" class="ex2Time" value="07:22">

  <input type="text" class="ex2Time" value="11:11">

  <input type="text" class="ex2Time" value="12:34">

  <hr/>
  <header>
    <hgroup>
      <h6 style='display:table-row'>Using Arial instead of Roboto</h6>
      <h6 style='display:table-row;width:400px'>4 inputs Within .ex3Align</h6>
      <h6>&nbsp;</h6>
      <h5>Example 3</h5>
    </hgroup>
  </header>
  <hr/>

  <input type="text" class="ex3Time" value="00:00">

  <input type="text" class="ex3Time" value="07:22">

  <input type="text" class="ex3Time" value="11:11">

  <input type="text" class="ex3Time" value="12:34">

  <hr/>
</main>


问:
Delete entity under some conditions Drupal 8
The task is to delete the entities, which satisfies some specified conditions. How can I do it ?

```<code>$current_user = \Drupal::currentUser()->id();
$storage = \Drupal::entityManager()->getStorage('context');

$query = $storage->getQuery()->condition('user_id', $current_user);

$query = $storage->getQuery()->delete();
$query->condition('user_id', $current_user);
$query->condition('key_text', $key);

$query->execute();
</code>```

But the code returns: Fatal error: Call to undefined method Drupal\Core\Config\Entity\Query\Query::delete()

答:
To query entities you can use entityQuery, example below uses this.</p>

```<code>// Get all users with email containing "xyz"
$query = \Drupal::entityQuery('user')
  ->condition('mail', "XYZ", 'CONTAINS');
$uids = $query->execute();

// Load these entities ($uids) in our case using storage controller.
// We call loadMultiple method and give $uids array as argument.
$itemsToDelete = \Drupal::entityTypeManager()->getStorage('user')
  ->loadMultiple($uids);

// Loop through our entities and deleting them by calling by delete method.
foreach ($itemsToDelete as $item) {
  $item->delete();
}
</code>```

Body:
The task is to delete the entities, which satisfies some specified conditions. How can I do it ?

$current_user = \Drupal::currentUser()->id();
$storage = \Drupal::entityManager()->getStorage('context');

$query = $storage->getQuery()->condition('user_id', $current_user);

$query = $storage->getQuery()->delete();
$query->condition('user_id', $current_user);
$query->condition('key_text', $key);

$query->execute();

But the code returns: Fatal error: Call to undefined method Drupal\Core\Config\Entity\Query\Query::delete()

Body:
To query entities you can use entityQuery, example below uses this.

// Get all users with email containing "xyz"
$query = \Drupal::entityQuery('user')
  ->condition('mail', "XYZ", 'CONTAINS');
$uids = $query->execute();

// Load these entities ($uids) in our case using storage controller.
// We call loadMultiple method and give $uids array as argument.
$itemsToDelete = \Drupal::entityTypeManager()->getStorage('user')
  ->loadMultiple($uids);

// Loop through our entities and deleting them by calling by delete method.
foreach ($itemsToDelete as $item) {
  $item->delete();
}


问:
Mock a dependency of a React component using Jest
I have a react component (CreateForm). The React component depends on a module (Store). The CreateForm has a Cancel button. On clicking the cancel button, the handleCancel function of the Store module should be called.

I wrote a test unsuccessfully using Jest:

```<code>test.only('should handle cancel button click', () => {
    jest.mock('../../src/store');
    const store = require('../../src/store');
    const wrapper = shallow(<CreateForm />);
    const cancelButton = wrapper.find('button').at(1);
    cancelButton.simulate('click');
    expect(store.default.handleCancel).toBeCalled();
});
</code>```

The test failed. The mock function did not get called and the test failed. Does the react component not get this version of the mock? If so, how do I fix the test? Thanks.

My CreateForm component looks something like the below:

```<code>import Store from './store';

render() {
   return (
     <Panel>
       <FormControls />
       <button onClick={Store.create}>Create</button>
       <button onClick={Store.handleCancel}>Cancel</button>
    </Panel>
  );
}
</code>```

A second improvised test that works for me is shown below.

```<code>test.only('should handle cancel button click', () => {
  const store = require('../../src/store').default;
  const cancel = store.handleCancel;
  store.handleCancel = jest.fn();

  const wrapper = shallow(<CreateForm />);
  const cancelButton = wrapper.find('button').at(1);
  cancelButton.simulate('click');
  expect(store.handleCancel).toBeCalled();

  store.handleCancel = cancel;
});
</code>```

The above test works. I am manually mocking the function, doing the test and restoring the function back to its original after the test. Is there a better way or Jest way of writing the above test? Thanks.

答:
This is how I have managed to spy on imported functions using Jest.

Import everything that is imported in the file you're testing.

Mock it in the beforeEach, you can use more complex mocking if you need to return values or whatever.

In the afterEach call jest.clearAllMocks() to reset all the functions to normal to stop any mocking falling through to other tests.

Putting it all together it looks something like this.

```<code>import shallow from 'enzyme'
import * as Store from './Store' // This should be the actual path from the test file to the import

describe('mocking', () => {
  beforeEach(() => {
    jest.spyOn(Store, 'handleCancel')
    jest.spyOn(Store, 'create')
  })

  afterEach(() => {
    jest.clearAllMocks();
  })

  test.only('should handle cancel button click', () => {
    const wrapper = shallow(<CreateForm />);
    const cancelButton = wrapper.find('button').at(1);
    cancelButton.simulate('click');
    expect(Store.handleCancel).toBeCalled();
  })
})
</code>```

Also, in case you need to mock a default import you can do so like this. jest.spyOn(Store, 'default')

Body:
I have a react component (CreateForm). The React component depends on a module (Store). The CreateForm has a Cancel button. On clicking the cancel button, the handleCancel function of the Store module should be called.

I wrote a test unsuccessfully using Jest:

test.only('should handle cancel button click', () => {
    jest.mock('../../src/store');
    const store = require('../../src/store');
    const wrapper = shallow(<CreateForm />);
    const cancelButton = wrapper.find('button').at(1);
    cancelButton.simulate('click');
    expect(store.default.handleCancel).toBeCalled();
});

The test failed. The mock function did not get called and the test failed. Does the react component not get this version of the mock? If so, how do I fix the test? Thanks.

My CreateForm component looks something like the below:

import Store from './store';

render() {
   return (
     <Panel>
       <FormControls />
       <button onClick={Store.create}>Create</button>
       <button onClick={Store.handleCancel}>Cancel</button>
    </Panel>
  );
}

A second improvised test that works for me is shown below.

test.only('should handle cancel button click', () => {
  const store = require('../../src/store').default;
  const cancel = store.handleCancel;
  store.handleCancel = jest.fn();

  const wrapper = shallow(<CreateForm />);
  const cancelButton = wrapper.find('button').at(1);
  cancelButton.simulate('click');
  expect(store.handleCancel).toBeCalled();

  store.handleCancel = cancel;
});

The above test works. I am manually mocking the function, doing the test and restoring the function back to its original after the test. Is there a better way or Jest way of writing the above test? Thanks.

Body:
This is how I have managed to spy on imported functions using Jest.

Import everything that is imported in the file you're testing.

Mock it in the beforeEach, you can use more complex mocking if you need to return values or whatever.

In the afterEach call jest.clearAllMocks() to reset all the functions to normal to stop any mocking falling through to other tests.

Putting it all together it looks something like this.

import shallow from 'enzyme'
import * as Store from './Store' // This should be the actual path from the test file to the import

describe('mocking', () => {
  beforeEach(() => {
    jest.spyOn(Store, 'handleCancel')
    jest.spyOn(Store, 'create')
  })

  afterEach(() => {
    jest.clearAllMocks();
  })

  test.only('should handle cancel button click', () => {
    const wrapper = shallow(<CreateForm />);
    const cancelButton = wrapper.find('button').at(1);
    cancelButton.simulate('click');
    expect(Store.handleCancel).toBeCalled();
  })
})

Also, in case you need to mock a default import you can do so like this. jest.spyOn(Store, 'default')


问:
Magento 2: How to Filter a Product Collection By Store ID
I am trying to display brand specific product. brand is one of my attribute which is mandatory and attached by each product.

I created different store under one website for each brand and also created different URL for each brand. so, i want to display product brand wise for each brand store.

So, which of the easiest way to filter product by attribute i.e brand.

I am using Magento 2.1.2, MySQL 6, PHP 7.0

答:
Use the following code to Filter a Product Collection By Store ID:</p>

```<code>$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToSelect('*')
$collection->addStoreFilter($storeid)
$collection->addAttributeToFilter('attribute_code');
</code>```

Body:
Use the following code to Filter a Product Collection By Store ID:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToSelect('*')
$collection->addStoreFilter($storeid)
$collection->addAttributeToFilter('attribute_code');


问:
How to prevent duplicates
I'm trying to figure out how I can have it loop through the data in the UL (each li) and prevent it from duplicating any prior existence of a selection.

```<code><script type="text/javascript" language="javascript">
// Long version
function HandlerCharacters() {
 var characterid = $('#charactersdrop option:selected').val();
 var characterName = $('#charactersdrop option:selected').text();

 if( characterid > 0 ) {
  // Create the anchor element
  var anchor = $( '<a href="#">Remove</a>' );

  // Create a click handler for the anchor element
  anchor.click( function() {
   $( this ).parent().remove();
   return false;  // makes the href in the anchor tag ignored
  } );

  // Create the <li> element with its text, and then append the anchor inside it.
  var li = $( '<li>' + characterName + ' </li>' ).append( anchor );
  li.data( 'characterid', characterid );

  // Append the new <li> element to the <ul> element
  $( '#characterlist' ).append( li );
 }
}
</script>
</code>```

答:
As I understand the question, you're trying to insert a new li only when the new characterID is not within the data of another li in the list. If so, then you could write a function like this:

```<code>function isDupe(which) {
  var result = false;
  $('ul#the_list li').each( function(i,e) { // look at all list elements
    if ( $(e).data('characterid') == which ) { // compare to argument
      result = true; // matched!
      return false; // break out of .each()
    }
  });
  return result;
}
</code>```

Then you could wrap your li creation code like this:

```<code>if( !isDupe(characterid) ){
  // do your checks
  // make your li
  // append to your list
}
</code>```

Here's a reduced example: http://jsfiddle.net/redler/B7myn/

Title: How to prevent duplicates

Body:
As I understand the question, you're trying to insert a new li only when the new characterID is not within the data of another li in the list. If so, then you could write a function like this:

function isDupe(which) {
  var result = false;
  $('ul#the_list li').each( function(i,e) { // look at all list elements
    if ( $(e).data('characterid') == which ) { // compare to argument
      result = true; // matched!
      return false; // break out of .each()
    }
  });
  return result;
}

Then you could wrap your li creation code like this:

if( !isDupe(characterid) ){
  // do your checks
  // make your li
  // append to your list
}

Here's a reduced example: http://jsfiddle.net/redler/B7myn/