问:
Best way to remove multiple entries from kml file
I have a very large KML file (over 20000 placemarkers). They are named by numbers which go up in increments of 5 starting at about 7000 up to 27000.

```<code><Placemark>
    <name>7750</name>
    <description><![CDATA[converted by:</br><a href="http://gridreferencefinder.com/">GridReferenceFinder.com</a></br>]]></description>
    <Point>
        <coordinates>-0.99153654,52.225002,0</coordinates>
    </Point>
</Placemark>
</code>```

I would like to remove any placemarker that doesnt end in 00 or 50. Having a placemarker every 5 metres is slowing down some of the lower end devices on site.

Is there some script, command or whatever that will check the name and if it doesn't end in 00 or 50 delete from <Placemark> to </Placemark> for that entry?

You would literally be saving me 10 hours work deleting them individually.

答:
Something like this in awk:

```<code>$ awk '
/<Placemark>/ { d=""; b="" }         # d is delete, b is buffer, reset both
{ b=b $0 (/<\/Placemark>/?"":ORS) }  # gather data to d
!/[50]0</ && /<\/name>/ { d=1 }      # if not 50 or 00 set del flag
/<\/Placemark>/ && d!=1 { print b }  # print b if not marked delete
' file
</code>```

It only works with well formed input, especially:

```<code>...
</Placemark>
<Placemark>
...
<name>1234</name>
...
</code>```

not:

```<code>...
</Placemark><Placemark>
... <!-- or: -->
<name>1234
</name>
...
</code>```

It's an ugly hack. Someone will probably set you up with something nicer but try it if it suits your needs.

Body:
I have a very large KML file (over 20000 placemarkers). They are named by numbers which go up in increments of 5 starting at about 7000 up to 27000.

<Placemark>
    <name>7750</name>
    <description><![CDATA[converted by:
GridReferenceFinder.com
]]></description>
    <Point>
        <coordinates>-0.99153654,52.225002,0</coordinates>
    </Point>
</Placemark>

I would like to remove any placemarker that doesnt end in 00 or 50. Having a placemarker every 5 metres is slowing down some of the lower end devices on site.

Is there some script, command or whatever that will check the name and if it doesn't end in 00 or 50 delete from <Placemark> to </Placemark> for that entry?

You would literally be saving me 10 hours work deleting them individually.

Body:
Something like this in awk:

$ awk '
/<Placemark>/ { d=""; b="" }         # d is delete, b is buffer, reset both
{ b=b $0 (/<\/Placemark>/?"":ORS) }  # gather data to d
!/[50]0</ && /<\/name>/ { d=1 }      # if not 50 or 00 set del flag
/<\/Placemark>/ && d!=1 { print b }  # print b if not marked delete
' file

It only works with well formed input, especially:

...
</Placemark>
<Placemark>
...
<name>1234</name>
...

not:

...
</Placemark><Placemark>
... <!-- or: -->
<name>1234
</name>
...

It's an ugly hack. Someone will probably set you up with something nicer but try it if it suits your needs.


来源: stackexchange

问:
Tomcat Access Logs in Spring Boot for different operating systems
Recently I've started to work with Spring Boot and have a following question:

We have different environments (like stage, development, production) and all of them can be run on windows or linux.
So I've created application-stage.properties, application-prod.properties, application-devl.properties to specify stuff like db connections and so on because its OS agnostic (the same for windows and linux).

Now I would like to enable access logs for embedded Tomcat server.
So following various guides I used the following in my application.properties file:

```<code>server.tomcat.accesslog.directory=logs
server.tomcat.accesslog.enabled=true
</code>```

I was forced to specify a relative path because we use both linux and windows, however I would like the access log to be created in different places depending on the OS .
For example, we store logs in windows under c:\<product>\logs and in linux we use /var/log/<product>/...

For usual logs we use logbacks and it allows stuff like this, but since access log is not actually logback driven and instead uses Valves, my question is: how we can achieve the same level of flexibility here?

I don't think I should provide additional profile for this and use it like:

```<code>--spring.profiles.active=windows / linux
</code>```

Because I believe spring boot has some solution up on its sleeves for this :)
Thanks a lot in advance

答: You will have to do some kind of env specific action if relative paths are no good.  From https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html you can use profiles or you can use an environment variable or a system property. As the other answer says you can load properties from an environment specific file if that is what makes the most sense for you.</p>

ContentLicense: CC BY-SA 3.0

Body:
Recently I've started to work with Spring Boot and have a following question:

We have different environments (like stage, development, production) and all of them can be run on windows or linux.
So I've created application-stage.properties, application-prod.properties, application-devl.properties to specify stuff like db connections and so on because its OS agnostic (the same for windows and linux).

Now I would like to enable access logs for embedded Tomcat server.
So following various guides I used the following in my application.properties file:

server.tomcat.accesslog.directory=logs
server.tomcat.accesslog.enabled=true

I was forced to specify a relative path because we use both linux and windows, however I would like the access log to be created in different places depending on the OS .
For example, we store logs in windows under c:\<product>\logs and in linux we use /var/log/<product>/...

For usual logs we use logbacks and it allows stuff like this, but since access log is not actually logback driven and instead uses Valves, my question is: how we can achieve the same level of flexibility here?

I don't think I should provide additional profile for this and use it like:

--spring.profiles.active=windows / linux

Because I believe spring boot has some solution up on its sleeves for this :)
Thanks a lot in advance


问:
matplotlab: plt.figure() creates empty figure
I am playing with the example at

https://github.com/seanabu/seanabu.github.io/blob/master/Seasonal_ARIMA_model_Portland_transit.ipynb

However, on my own Jupyter Notebook, the following piece of code creates an empty figure. Any idea? Thanks!

答:
You are creating two figures. Simply remove the first creation of the empty figure fig = plt.figure().

Here is a minimal example:

```<code>%matplotlib inline
import statsmodels.api as sm
from statsmodels.tsa.seasonal import seasonal_decompose

dat = sm.datasets.co2.load_pandas().data.dropna()
decomposition = seasonal_decompose(dat.co2, freq=12)
fig = decomposition.plot()
fig .set_size_inches(15, 8)
</code>```

Body:
You are creating two figures. Simply remove the first creation of the empty figure fig = plt.figure().

Here is a minimal example:

%matplotlib inline
import statsmodels.api as sm
from statsmodels.tsa.seasonal import seasonal_decompose

dat = sm.datasets.co2.load_pandas().data.dropna()
decomposition = seasonal_decompose(dat.co2, freq=12)
fig = decomposition.plot()
fig .set_size_inches(15, 8)


问:
Vectorized way of dropping duplicates from a DataFrame
I denote duplicate values in a file with "duplicates" using the following (working) code:

```<code>frame=pd.read_excel(io=r"D:XXXX\test.xlsx")
df=pd.DataFrame(frame)

dup=[df.duplicated(subset=(i),keep=False) for i in [("id","Type"),("id","Time"),("Time","Type")]]
duplicate="duplicate"

for i in range(len(dup)):
    for j in range(len(dup[i])):
        if dup[i][j]==True:
            df.loc[j,"Attribute"]=duplicate
</code>```

The shape of the DataFrame is something like:

```<code>id  Type    Time
12  ab  12:00:00
11  cd  11:12:22
663 dfd 10:00:00
</code>```

But if there are many rows in a file this approch gets tedious.
I'm searching for a way to replace the loop by a combination of lambda or apply with LC

Thanks for any response

答:
I believe his is what you're looking for using pandas.duplicated and pandas.apply:

```<code>for i in [("id","Type"),("id","Time"),("Time","Type")]:
    df['Attribute'] = df.duplicated(subset=i,keep=False).apply(lambda x: "duplicate" if x else "not duplicate")
</code>```

solution with numpy.where:

```<code>for i in [("id","Type"),("id","Time"),("Time","Type")]:
    df['Attribute'] = np.where(df.duplicated(subset=i,keep=False),"duplicate","not duplicate")
</code>```

i used this dataframe as input:

```<code>    id   Type      Time
0   12     ab  12:00:00
1   12  abacd  11:12:22
2  663    dfd  10:00:00
3   11     ab  12:00:00
4  663    dfd  10:00:00
5   11   caad  11:12:22
</code>```

this is the output:

```<code>    id   Type      Time      Attribute
0   12     ab  12:00:00      duplicate
1   12  abacd  11:12:22  not duplicate
2  663    dfd  10:00:00      duplicate
3   11     ab  12:00:00      duplicate
4  663    dfd  10:00:00      duplicate
5   11   caad  11:12:22  not duplicate
</code>```

Hope this was helpful.

Body:
I denote duplicate values in a file with "duplicates" using the following (working) code:

frame=pd.read_excel(io=r"D:XXXX\test.xlsx")
df=pd.DataFrame(frame)

dup=[df.duplicated(subset=(i),keep=False) for i in [("id","Type"),("id","Time"),("Time","Type")]]
duplicate="duplicate"

for i in range(len(dup)):
    for j in range(len(dup[i])):
        if dup[i][j]==True:
            df.loc[j,"Attribute"]=duplicate

The shape of the DataFrame is something like:

id  Type    Time
12  ab  12:00:00
11  cd  11:12:22
663 dfd 10:00:00

But if there are many rows in a file this approch gets tedious.
I'm searching for a way to replace the loop by a combination of lambda or apply with LC

Thanks for any response

Body:
I believe his is what you're looking for using pandas.duplicated and pandas.apply:

for i in [("id","Type"),("id","Time"),("Time","Type")]:
    df['Attribute'] = df.duplicated(subset=i,keep=False).apply(lambda x: "duplicate" if x else "not duplicate")

solution with numpy.where:

for i in [("id","Type"),("id","Time"),("Time","Type")]:
    df['Attribute'] = np.where(df.duplicated(subset=i,keep=False),"duplicate","not duplicate")

i used this dataframe as input:

    id   Type      Time
0   12     ab  12:00:00
1   12  abacd  11:12:22
2  663    dfd  10:00:00
3   11     ab  12:00:00
4  663    dfd  10:00:00
5   11   caad  11:12:22

this is the output:

    id   Type      Time      Attribute
0   12     ab  12:00:00      duplicate
1   12  abacd  11:12:22  not duplicate
2  663    dfd  10:00:00      duplicate
3   11     ab  12:00:00      duplicate
4  663    dfd  10:00:00      duplicate
5   11   caad  11:12:22  not duplicate

Hope this was helpful.


问:
Multiple Times load of image from API in ImageView in IOS
I have made a custom Tableview which has an image view and some labels that takes values from API.

It's a custom table in which images and labels recieve data from API related to real estate .

When my custom table loads, values start coming from API.

The actual issue ocurr in image view . I have set a local image in an image view , when the data coming from API has no image than it should show local image otherwise data should show its original image submitted by customer in the forms.

Now when data start coming from API first in image view it shows local image than when images start coming from API it start showing that but when we scroll down in image view it shows same images in image view and repeats many times and we cannot identify that which is original image.

I can provide the code if anyone sent me his email , he can get all the senario of work.

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier=@"Cell";
    CustomTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    StringData* cust = [_Title objectAtIndex:indexPath.row];

    cell.Title.text = cust.title1;
    cell.area.text=cust.Area;
    cell.city.text=cust.City;
    cell.phone.text=cust.phoneno;
    cell.price.text=cust.Price;
    cell.location1.text=cust.location;
    cell.name1.text=cust.dealer_name;
    cell.email1.text=cust.dealer_email;
    cell.type1.text=cust.property_type;
    cell.status1.text=cust.status;
    cell.room1.text=cust.rooms;
    cell.washrooms.text=cust.bath;
    cell.floor1.text=cust.floors;
    cell.imagetext.text = cust.images;

    tii=cell.Title.text;
    NSLog(@"Tittttttle is %@",tii);

    NSURL *url = [NSURL URLWithString:cust.images];
    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data,    NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            UIImage *image = [UIImage imageWithData:data];
            if (image) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    cell.images1.image = image;
                });
            }
        }
    }];
    [task resume];

    return cell;
}
</code>```

答:
It seems you don't store an image into local application memory. You tried to load image on every time when cell is appear. So you download image every time.

Best Solution:

You need to store image local memory using SDWebImage.

Objective-C:

```<code>#import <SDWebImage/UIImageView+WebCache.h>
...
[imageView sd_setImageWithURL:[NSURL URLWithString:@"IMAGE_URL"]
             placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
</code>```

Swift:

```<code>import SDWebImage

imageView.sd_setImage(with: URL(string: "IMAGE_URL"), placeholderImage: UIImage(named: "placeholder.png"))
</code>```

If you are loading an image for the first time, then it will download and store an image into local memory. So from second times, it will load from local itself.

Body:
I have made a custom Tableview which has an image view and some labels that takes values from API.

It's a custom table in which images and labels recieve data from API related to real estate .

When my custom table loads, values start coming from API.

The actual issue ocurr in image view . I have set a local image in an image view , when the data coming from API has no image than it should show local image otherwise data should show its original image submitted by customer in the forms.

Now when data start coming from API first in image view it shows local image than when images start coming from API it start showing that but when we scroll down in image view it shows same images in image view and repeats many times and we cannot identify that which is original image.

I can provide the code if anyone sent me his email , he can get all the senario of work.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier=@"Cell";
    CustomTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    StringData* cust = [_Title objectAtIndex:indexPath.row];

    cell.Title.text = cust.title1;
    cell.area.text=cust.Area;
    cell.city.text=cust.City;
    cell.phone.text=cust.phoneno;
    cell.price.text=cust.Price;
    cell.location1.text=cust.location;
    cell.name1.text=cust.dealer_name;
    cell.email1.text=cust.dealer_email;
    cell.type1.text=cust.property_type;
    cell.status1.text=cust.status;
    cell.room1.text=cust.rooms;
    cell.washrooms.text=cust.bath;
    cell.floor1.text=cust.floors;
    cell.imagetext.text = cust.images;

    tii=cell.Title.text;
    NSLog(@"Tittttttle is %@",tii);

    NSURL *url = [NSURL URLWithString:cust.images];
    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data,    NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            UIImage *image = [UIImage imageWithData:data];
            if (image) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    cell.images1.image = image;
                });
            }
        }
    }];
    [task resume];

    return cell;
}

Body:
It seems you don't store an image into local application memory. You tried to load image on every time when cell is appear. So you download image every time.

Best Solution:

You need to store image local memory using SDWebImage.

Objective-C:

#import <SDWebImage/UIImageView+WebCache.h>
...
[imageView sd_setImageWithURL:[NSURL URLWithString:@"IMAGE_URL"]
             placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

Swift:

import SDWebImage

imageView.sd_setImage(with: URL(string: "IMAGE_URL"), placeholderImage: UIImage(named: "placeholder.png"))

If you are loading an image for the first time, then it will download and store an image into local memory. So from second times, it will load from local itself.


问:
Vim search for pattern replaces search pattern
I try to search my file %s/ by pattern Audi, and what I would expect is that Vim should only search but not replace what I'm searching by empty space.

Here an example:

my.file:

```<code>BMW = 0
Audi = 1
Ford = 2
</code>```

When I perform search like so: :%s/Audi Vim does search in my.file for string that first has Audi pattern in it. And what comes next surprised me: it does replace Audi with white space.

Like it is not a big deal when your string is just 4 letters long, but I have some configuration files on my VPS and some of the config vars has the length of 20-30 symbols.

Question: How could I achieve just-search-but-not-replace behavior in Vim?

答:
As melpomene has mentioned in comments section:

:s is the substitute command. Use / if you just want to search.

Body:
I try to search my file %s/ by pattern Audi, and what I would expect is that Vim should only search but not replace what I'm searching by empty space.

Here an example:

my.file:

BMW = 0
Audi = 1
Ford = 2

When I perform search like so: :%s/Audi Vim does search in my.file for string that first has Audi pattern in it. And what comes next surprised me: it does replace Audi with white space.

Like it is not a big deal when your string is just 4 letters long, but I have some configuration files on my VPS and some of the config vars has the length of 20-30 symbols.

Question: How could I achieve just-search-but-not-replace behavior in Vim?


问:
how to set variable using fetched array in php
I have a query that fetches values from a database and I'd like to store an instance of the value 'current' into a variable for reuse.

My fetch is currently:

```<code>function updateTable() {
if(isset($_POST['submit'])) {
global $connection;
$sql = "SELECT * FROM myTable";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "current: " . $row["current"];
    }
} else {
    echo "0 results";
}
}}
</code>```

As you can see I have been able to confirm the values are being fetched by echoing out the array. What I'd like to do now is to store the first instance of the array into a new variable called $total.

I have been able to separate the array and echo values using:

```<code>while ($row = mysqli_fetch_array($result)) {

    $value = $row ['current'];
    if($row['id'] == 2){
    echo $value;
    }
                }
</code>```

I had thought storing the value would be similar but I can't get it to work.

Any help appreciated.
Thanks
James

答:
Create array of values when the key is the id and the value is the current then after for loop echo the value where key is 2</p>

```<code>while ($row = mysqli_fetch_array($result)) {
$values[$row['id']]=$row ['current'];
}
}
echo $values[2];
</code>```

Body:
I have a query that fetches values from a database and I'd like to store an instance of the value 'current' into a variable for reuse.

My fetch is currently:

function updateTable() {
if(isset($_POST['submit'])) {
global $connection;
$sql = "SELECT * FROM myTable";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "current: " . $row["current"];
    }
} else {
    echo "0 results";
}
}}

As you can see I have been able to confirm the values are being fetched by echoing out the array. What I'd like to do now is to store the first instance of the array into a new variable called $total.

I have been able to separate the array and echo values using:

while ($row = mysqli_fetch_array($result)) {

    $value = $row ['current'];
    if($row['id'] == 2){
    echo $value;
    }
                }

I had thought storing the value would be similar but I can't get it to work.

Any help appreciated.
Thanks
James

Body:
Create array of values when the key is the id and the value is the current then after for loop echo the value where key is 2

while ($row = mysqli_fetch_array($result)) {
$values[$row['id']]=$row ['current'];
}
}
echo $values[2];


问:
How to send a two dimensional array over gdbus?
I'm trying to send a two dimendional array of strings over dbus.( I'm using the gdbus api, with gdbus-codegen).

I have defined the dbus interface as follows.

```<code><method name="foo">
            <arg name="count" direction="out" type="i" />
            <arg name="array" direction="out" type="a(ia(s))" />
</method>
</code>```

I'm trying to create the GVariant in the following manner:

```<code>GVariantBuilder *builder;
GVariant *variant;
builder = g_variant_builder_new(G_VARIANT_TYPE("a(ia(s))"));
for (int i = 0; i < count; i++)
{
    g_variant_builder_add(builder, "(ia(s))",
                          options[i].num_supported,
                          pack_string_array(options[i].num_supported, options[i].supported_values));
}

variant = g_variant_new("a(a(s))", builder);
my_interface_complete_foo(interface, invocation, count, variant);
</code>```

where pack_string_array packs an array of c style strings into a gvariant.

```<code>GVariant* pack_string_array(int num_val, char **val)
{
    GVariantBuilder *builder;
    GVariant *values;
    builder = g_variant_builder_new(G_VARIANT_TYPE("a(s)"));
    for (int i = 0; i < num_val; i++)
    {
        g_message("%s", val[i]);
        g_variant_builder_add(builder, "(s)", val[i]);
    }

    if (num_val == 0)
        g_variant_builder_add(builder, "(s)", "NA");

    values = g_variant_new("a(s)", builder);
    return values;
}
</code>```

However when I test it,the program crashes with the following errors:

```<code> GLib-CRITICAL **: g_variant_builder_end: assertion 'ensure_valid_builder (builder)' failed
g_variant_get_type: assertion 'value != NULL' failed
</code>```

How can I send a array of string arrays over the dbus?

答:
The signatures used for the builder and the variant do not match:</p>

```<code>builder = g_variant_builder_new(G_VARIANT_TYPE("a(ia(s))"));
...
variant = g_variant_new("a(a(s))", builder);
</code>```

Body:
I'm trying to send a two dimendional array of strings over dbus.( I'm using the gdbus api, with gdbus-codegen).

I have defined the dbus interface as follows.

<method name="foo">
            <arg name="count" direction="out" type="i" />
            <arg name="array" direction="out" type="a(ia(s))" />
</method>

I'm trying to create the GVariant in the following manner:

GVariantBuilder *builder;
GVariant *variant;
builder = g_variant_builder_new(G_VARIANT_TYPE("a(ia(s))"));
for (int i = 0; i < count; i++)
{
    g_variant_builder_add(builder, "(ia(s))",
                          options[i].num_supported,
                          pack_string_array(options[i].num_supported, options[i].supported_values));
}

variant = g_variant_new("a(a(s))", builder);
my_interface_complete_foo(interface, invocation, count, variant);

where pack_string_array packs an array of c style strings into a gvariant.

GVariant* pack_string_array(int num_val, char **val)
{
    GVariantBuilder *builder;
    GVariant *values;
    builder = g_variant_builder_new(G_VARIANT_TYPE("a(s)"));
    for (int i = 0; i < num_val; i++)
    {
        g_message("%s", val[i]);
        g_variant_builder_add(builder, "(s)", val[i]);
    }

    if (num_val == 0)
        g_variant_builder_add(builder, "(s)", "NA");

    values = g_variant_new("a(s)", builder);
    return values;
}

However when I test it,the program crashes with the following errors:

 GLib-CRITICAL **: g_variant_builder_end: assertion 'ensure_valid_builder (builder)' failed
g_variant_get_type: assertion 'value != NULL' failed

How can I send a array of string arrays over the dbus?

Body:
The signatures used for the builder and the variant do not match:

builder = g_variant_builder_new(G_VARIANT_TYPE("a(ia(s))"));
...
variant = g_variant_new("a(a(s))", builder);


问:
Better way in SQL to fetch most recent customer record?
Imagine we have two tables: customers and purchases.
Purchases has a customerID, purchaseDateTime, etc.

What is the best way to select the most recent purchase for all customers in hive or impala SQL?

I've seen this query:

```<code>With recent as (
    select customerID, max(purchaseDateTime)     as dt
    from purchases group by customerID
)
Select *
from customer c
join recent r
    on c.customerID = r.customerID
join purchases p
    on r.customerId = p.customerid and
       p.purchaseDateTime = dt
</code>```

Seems like that's not as efficient as it could be...

答:
I would use row_number():

```<code>Select c.*, p.*
from customer c join
     (select p.*,
             row_number() over (partition by p.customerid order by p.purchaseDateTime desc) as seqnum
      from purchases p
     ) p
     on c.customerId = p.customerid and p.purchaseDateTime = dt
where seqnum = 1;
</code>```

row_number() is ANSI standard functionality, so it is standard SQL.  In general, it should be faster than doing an explicit group by and join.

One difference is that -- in the event of ties -- this returns one row.  Your query will return multiple rows.  If you want that behavior, change the row_number() to rank().

Body:
Imagine we have two tables: customers and purchases.
Purchases has a customerID, purchaseDateTime, etc.

What is the best way to select the most recent purchase for all customers in hive or impala SQL?

I've seen this query:

With recent as (
    select customerID, max(purchaseDateTime)     as dt
    from purchases group by customerID
)
Select *
from customer c
join recent r
    on c.customerID = r.customerID
join purchases p
    on r.customerId = p.customerid and
       p.purchaseDateTime = dt

Seems like that's not as efficient as it could be...

Body:
I would use row_number():

Select c.*, p.*
from customer c join
     (select p.*,
             row_number() over (partition by p.customerid order by p.purchaseDateTime desc) as seqnum
      from purchases p
     ) p
     on c.customerId = p.customerid and p.purchaseDateTime = dt
where seqnum = 1;

row_number() is ANSI standard functionality, so it is standard SQL.  In general, it should be faster than doing an explicit group by and join.

One difference is that -- in the event of ties -- this returns one row.  Your query will return multiple rows.  If you want that behavior, change the row_number() to rank().


问:
Intellij IDEA ssh tunnel to datasource
I'm trying to view my remote database running on digital ocean droplet as data source in Intellij IDEA.

ssh tunnel settings

general database settings

I accessed the database from Sequel Pro through ssh so I believe it is set correctly on the server side.

When I test the connection it says: Connection refused by foreign host.

What have I done wrong?
The ip is correct and the passwords and ssh keys as well, I'm certain of that.

答:
usually the ssh port is 22, if you haven't it customized.

If this tunnel is successful, you can connect against your database with the given port.

Check your screenshot. It shows 3306 for the ssh tunnel.

ContentLicense: CC BY-SA 4.0

Title: Intellij IDEA ssh tunnel to datasource


问:
Javascript can't find element by id?
```<code><html>
<head>
    <title>Test javascript</title>

    <script type="text/javascript">
        var e = document.getElementById("db_info");
        e.innerHTML='Found you';
    </script>
</head>
<body>
    <div id="content">
        <div id="tables">

        </div>
        <div id="db_info">
        </div>
    </div>
</body>
</html>
</code>```

If I use alert(e); it turns up null.... and obviously I don't get any "found you" on screen. What am I doing wrong?

答: The script is performed before the DOM of the body is built. Put it all into a function and call it from the onload of the body-element.

ContentLicense: CC BY-SA 2.5

Title: Javascript can't find element by id?

Body:
    <title>Test javascript</title>

If I use alert(e); it turns up null.... and obviously I don't get any "found you" on screen. What am I doing wrong?


问:
background image is not changing using jquery on IE 11
Dears am trying to change div background-image using jquery on click as shown in code below its working on all browsers except IE.....help please

```<code><div id="section1" class="section111">
        <div class="container">
            <div style="width: 100%; z-index: 999999999;" class="ServicesTitle">
                <p class="Main_TitaleServices">SERVICES & SOLUTIONS</p>
                <p class="slogan">Full Solutions for a Perfect Business   </p>
            </div>
            <div id="title-underline" style="margin-bottom: -30px;">
                <img src="../../App_Themes/ThemeEn/Images/title-underline.png">
            </div>
            <div class="firstrow">
                <div class="col-lg-3 divServices ">
                </div>
                </div>

        </div>
    </div>
</code>```

here is the script

```<code><script>
$(function () {
$("#WebsiteDevelopment").click(function () {
    $("#section1").css("background-image", "url(/App_Themes/ThemeEn/Images/webdevelopment.jpg !important")
    /

});
$("#btnWebsiteDevelopment").click(function () {

    $("#section1").css("background-image", "url(/App_Themes/ThemeEn/Images/section1bg.png")

});
});
</script>
</code>```

答:
Try setting background instead of background-image.

```<code><script>
$(function () {
$("#WebsiteDevelopment").click(function () {
    $("#section1").css("background", "url(/App_Themes/ThemeEn/Images/webdevelopment.jpg !important")
    /

});
$("#btnWebsiteDevelopment").click(function () {

    $("#section1").css("background", "url(/App_Themes/ThemeEn/Images/section1bg.png")

});
});
</script>
</code>```

Or use pure javascript approach,

```<code>document.getElementById('section1').backgroundImage = "url('url(/App_Themes/ThemeEn/Images/webdevelopment.jpg !important')";
</code>```

Body:
Dears am trying to change div background-image using jquery on click as shown in code below its working on all browsers except IE.....help please

SERVICES & SOLUTIONS

Full Solutions for a Perfect Business

here is the script

Body:
Try setting background instead of background-image.

<script>
$(function () {
$("#WebsiteDevelopment").click(function () {
    $("#section1").css("background", "url(/App_Themes/ThemeEn/Images/webdevelopment.jpg !important")
    /

});
$("#btnWebsiteDevelopment").click(function () {

    $("#section1").css("background", "url(/App_Themes/ThemeEn/Images/section1bg.png")

});
});
</script>

Or use pure javascript approach,

document.getElementById('section1').backgroundImage = "url('url(/App_Themes/ThemeEn/Images/webdevelopment.jpg !important')";


问:
Setting multiple attributes of a Ruby object in a loop
I have a class with bunch of attributes (first, second, third, etc.).
I need to go through all "even" attributes (i.e. second, fourth, sixth, etc.) and make some corrections to just those:

```<code>report.first = Calculate('1')

report.second = Calculate('2')
report.second *= 0.9 if requireCorrection && report.second > 5

report.third = Calculate('3')

report.fourth = Calculate('4')
report.fourth *= 0.9 if requireCorrection && report.fourth > 5

report.fifth = Calculate('5')

report.sixth = Calculate('6')
report.sixth *= 0.9 if requireCorrection && report.sixth > 5

# etc.
</code>```

As you can see, I have the exact same code for each "even" attribute, except for the different attribute name. Is there a way to avoid this repetition in the code (I have around 50 attributes in total)?

答:
You can use Object#send to invoke an arbitrary method on report by specifying the method name as a string or a symbol:

```<code>def make_correction(report, which_method)
  current_value = report.send(which_method)
  current_value *= 0.9 if current_value > 5
  report.send "#{which_method}=", current_value
end
</code>```

The method names first, second, third, etc. do not easily lend themselves to automatization, but if you renamed the methods to item_1, item_2, etc., you could use a loop to process all of them:

```<code>(1..50).each do |i|
  report.send "item_#{i}=", Calculate(i.to_s)

  if i.even?
    make_correction(report, "item_#{i}") if require_correction
  end
end
</code>```

If the method names need to stay the same, you can still simplify the code like this:

```<code>attrs = [:first, :second, :third, :fourth, :fifth]

attrs.each_with_index do |attr, ix|
  i = ix + 1  # indexes are zero based, we need to adjust them

  report.send "#{attr}=", Calculate(i.to_s)

  if i.even?
    make_correction(report, attr) if require_correction
  end
end
</code>```

Body:
I have a class with bunch of attributes (first, second, third, etc.).
I need to go through all "even" attributes (i.e. second, fourth, sixth, etc.) and make some corrections to just those:

report.first = Calculate('1')

report.second = Calculate('2')
report.second *= 0.9 if requireCorrection && report.second > 5

report.third = Calculate('3')

report.fourth = Calculate('4')
report.fourth *= 0.9 if requireCorrection && report.fourth > 5

report.fifth = Calculate('5')

report.sixth = Calculate('6')
report.sixth *= 0.9 if requireCorrection && report.sixth > 5

# etc.

As you can see, I have the exact same code for each "even" attribute, except for the different attribute name. Is there a way to avoid this repetition in the code (I have around 50 attributes in total)?

Body:
You can use Object#send to invoke an arbitrary method on report by specifying the method name as a string or a symbol:

def make_correction(report, which_method)
  current_value = report.send(which_method)
  current_value *= 0.9 if current_value > 5
  report.send "#{which_method}=", current_value
end

The method names first, second, third, etc. do not easily lend themselves to automatization, but if you renamed the methods to item_1, item_2, etc., you could use a loop to process all of them:

(1..50).each do |i|
  report.send "item_#{i}=", Calculate(i.to_s)

  if i.even?
    make_correction(report, "item_#{i}") if require_correction
  end
end

If the method names need to stay the same, you can still simplify the code like this:

attrs = [:first, :second, :third, :fourth, :fifth]

attrs.each_with_index do |attr, ix|
  i = ix + 1  # indexes are zero based, we need to adjust them

  report.send "#{attr}=", Calculate(i.to_s)

  if i.even?
    make_correction(report, attr) if require_correction
  end
end


问:
PHP Composer - Unable to install composer on macOS Sierra
I'm trying to install composer running the command provided on the getcomposer.org/download documentation site:

```<code>php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === 'e115a8dc7871f15d853148a7fbac7da27d6c0030b848d9b3dc09e2a0388afed865e6a3d6b3c0fad45c48e2b5fc1196ae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"
</code>```

But I get an error message saying:

```<code>Warning: copy(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in Command line code on line 1

Warning: copy(): Failed to enable crypto in Command line code on line 1

Warning: copy(https://getcomposer.org/installer): failed to open stream: operation failed in Command line code on line 1
Yoshihiros-MacBook-Pro:~ yoshihiro$ php -r "if (hash_file('SHA384', 'composer-setup.php') === 'e115a8dc7871f15d853148a7fbac7da27d6c0030b848d9b3dc09e2a0388afed865e6a3d6b3c0fad45c48e2b5fc1196ae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

Warning: hash_file(composer-setup.php): failed to open stream: No such file or directory in Command line code on line 1
Installer corrupt
Warning: unlink(composer-setup.php): No such file or directory in Command line code on line 1

Yoshihiros-MacBook-Pro:~ yoshihiro$ php composer-setup.php
Could not open input file: composer-setup.php
</code>```

I'm also trying to install it globally but I can't get out of this message. Please help D:

答:
The instructions in Composer official page is sometimes confusing

or not working on macOS Sierra.

But installation is still simple like before.Just simply run two lines of command on your Terminal.

curl -sS https://getcomposer.org/installer | php

mv composer.phar usr/local/bin/composer

Body:
I'm trying to install composer running the command provided on the getcomposer.org/download documentation site:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === 'e115a8dc7871f15d853148a7fbac7da27d6c0030b848d9b3dc09e2a0388afed865e6a3d6b3c0fad45c48e2b5fc1196ae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

But I get an error message saying:

Warning: copy(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in Command line code on line 1

Warning: copy(): Failed to enable crypto in Command line code on line 1

Warning: copy(https://getcomposer.org/installer): failed to open stream: operation failed in Command line code on line 1
Yoshihiros-MacBook-Pro:~ yoshihiro$ php -r "if (hash_file('SHA384', 'composer-setup.php') === 'e115a8dc7871f15d853148a7fbac7da27d6c0030b848d9b3dc09e2a0388afed865e6a3d6b3c0fad45c48e2b5fc1196ae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

Warning: hash_file(composer-setup.php): failed to open stream: No such file or directory in Command line code on line 1
Installer corrupt
Warning: unlink(composer-setup.php): No such file or directory in Command line code on line 1

Yoshihiros-MacBook-Pro:~ yoshihiro$ php composer-setup.php
Could not open input file: composer-setup.php

I'm also trying to install it globally but I can't get out of this message. Please help D:


问:
how to make border-right's height according to vertical-middle
i'm an Asian person. I'm sorry because i'm not good at English writing and grammar.

I am designing a bulletin board's view page using HTML, JSP, CSS, and I'm implementing it using  tag.

I want to implement distinguished right line between  and  tag,  a written information such as writer, viewed number, title, etc,.   like bottom image.the line looks like applied vertical-middle line of height value.
I want to implement this using CSS Attribute related border-right.

How can I design this using CSS ? pls T.T;;

please refer to the bottom exam's image that i want to make.

Regards,

答:
You can do this by applying css
 border property like -
    border-right: thick groove black;
  Or
You can apply sign convention like | between content.
 I hope my answer may help you.
  if it does, please upgrade me.</p>


问:
Upload Only Image jpg, jpeg,bmp,gif and png. how write code in this code
if (FileUpload1.HasFile)
{
    string extension = System.IO.Path.GetExtension(FileUpload1.FileName);</p>

```<code>if (extension == ".jpg")
{
    FileUpload1.SaveAs("yourpath" + FileUpload1.FileName);

}
else
{
Response.Write("Only .Jpg allowed");
}
</code>```

<p>}  </p>

答:
Try following :</p>

```<code>            string[] imageTypes = {"jpg", "jpeg","bmp","gif", "png"};
            string filename = "abc.jpg";
            Boolean validFileName = imageTypes.Contains(filename.Substring(filename.LastIndexOf(".") + 1).ToLower());
</code>```

Body:
if (FileUpload1.HasFile)
{
    string extension = System.IO.Path.GetExtension(FileUpload1.FileName);

if (extension == ".jpg")
{
    FileUpload1.SaveAs("yourpath" + FileUpload1.FileName);

}
else
{
Response.Write("Only .Jpg allowed");
}

}

Body:
Try following :

            string[] imageTypes = {"jpg", "jpeg","bmp","gif", "png"};
            string filename = "abc.jpg";
            Boolean validFileName = imageTypes.Contains(filename.Substring(filename.LastIndexOf(".") + 1).ToLower());


问:
Tab-content not showing up
I'm working with tabs that show content for two data-target(no problem in that). I've added a script which automatically changes tab after 5 sec. Tab changes but the tab-content doesn't show up. I don't know why. Any help would be appreciated. Thanks.

Codepen Here

$(document).ready(function () {
            var timeInterval, currnetIndex = 1;
            tabCount = 5;
            var tabContentObj = $('.tab-content');
            changeTabIndex();
            timeInterval = setInterval(function () { changeTabIndex(); }, 4 * 1000);

            function changeTabIndex() {
                if (currnetIndex > tabCount) {
                    currnetIndex = 1;
                }
                tabContentObj.hide();
                $('ul#myTab').find('li.active').removeClass('active');
                var currentAncorObj = $('ul#myTab').find('li a').eq(currnetIndex - 1);
                currentAncorObj.parent().addClass('active');
                $(currentAncorObj.attr('href')).show();
                currnetIndex++;

            };

            $('#myTab li').mouseenter(function () {
                clearInterval(timeInterval);
            }).mouseleave(function () {
                timeInterval = setInterval(function () { changeTabIndex(); }, 4 * 1000);
            });

            $('#myTab li a').click(function () {
                tabContentObj.hide();
                $('ul#myTab').find('li.active').removeClass('active');
                var currentAncorObj = $(this);
                currnetIndex = $('ul#myTab').find('li a').index($(this)) + 1;
                currentAncorObj.parent().addClass('active');
                $(currentAncorObj.attr('href')).show();
                currnetIndex++;

                //return false;
            });
        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.how-it-works {
 padding-bottom: 30px;
}
.board .nav-tabs {
 position: relative;
 margin: 40px auto;
 margin-bottom: 0;
 box-sizing: border-box;
}
.board > div.board-inner > .nav-tabs {
 border: none;
}
p.narrow{
 width: 60%;
 margin: 10px auto;
}
.liner{
 height: 2px;
 background: #ddd;
 position: absolute;
 width: 80%;
 margin: 0 auto;
 left: 0;
 right: 0;
 top: 50%;
 z-index: 1;
}
.nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus {
 color: #555555;
 cursor: default;
 border: 0;
 border-bottom-color: transparent;
 outline: 0;
}
span.round-tabs{
 width: 70px;
 height: 70px;
 line-height: 70px;
 display: inline-block;
 border-radius: 100px;
 background: white;
 z-index: 2;
 position: absolute;
 left: 0;
 text-align: center;
 font-size: 25px;
}
span.round-tabs.one{
 border: 2px solid #ddd;
 color: #ddd;
}
li.active span.round-tabs.one, li.active span.round-tabs.two, li.active span.round-tabs.three, li.active span.round-tabs.four, li.active span.round-tabs.five{
 background: #36ABE7 !important;
 border: 2px solid #2AC7CC;
 color: #fff;
}

span.round-tabs,.two{
 border: 2px solid #ddd;
 color: #ddd;
}
span.round-tabs,.three{
 border: 2px solid #ddd;
 color: #ddd;
}
span.round-tabs,.four{
 border: 2px solid #ddd;
 color: #ddd;
}
span.round-tabs,.five{
 border: 2px solid #ddd;
 color: #ddd;
}
.nav-tabs > li.active > a.span.round-tabs{
 background: #fafafa;
}
.nav-tabs > li{
 width: 20%;
}
.nav-tabs > li a{
 width: 70px;
 height: 70px;
 margin: 0px auto;
 border-radius: 100%;
 padding: 0;
}

.nav-tabs > li a:hover{
 background: transparent;
}
.tab-pane{
 position: relative;
 padding-top: 50px;
}
.btn-outline-rounded{
 padding: 10px 40px;
 margin: 20px 0;
 border: 2px solid transparent;
 border-radius: 25px;
}
.btn.green{
 background-color: #69cb95;
 color: #fff;
}
@media(max-width: 585px){
 .board{
  width: 90%;
  height: auto !important;
 }
 span.round-tabs{
  font-size: 16px;
  width: 50px;
  height: 50px;
  line-height: 50px;
 }
 .tab-content.head{
  font-size:20px;
 }
 .nav-tabs > li a{
  width: 50px;
  height: 50px;
  line-height: 50px;
 }
 li.active:after{
  content:"";
  position: absolute;
  left: 35%;
 }
 .btn-outline-rounded{
  padding: 12px 20px;
 }
}</code>```

<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"/>

Our Services

Service Title 1

Service Title 2

Service Title 3

Service Title 4

Service Title 5

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

```

Please look at the codepen. Snippet have some problem.
1

答:
Here you go with working solution https://jsfiddle.net/L64s4bxh/2/</p>

```<code>var tabContentObj = $('.tab-pane');

tabContentObj.hide().removeClass('in');

$(currentAncorObj.attr('data-target')).show().addClass('in');
</code>```

Title: Tab-content not showing up

Body:
I'm working with tabs that show content for two data-target(no problem in that). I've added a script which automatically changes tab after 5 sec. Tab changes but the tab-content doesn't show up. I don't know why. Any help would be appreciated. Thanks.

Codepen Here

$(document).ready(function () {
            var timeInterval, currnetIndex = 1;
            tabCount = 5;
            var tabContentObj = $('.tab-content');
            changeTabIndex();
            timeInterval = setInterval(function () { changeTabIndex(); }, 4 * 1000);

            function changeTabIndex() {
                if (currnetIndex > tabCount) {
                    currnetIndex = 1;
                }
                tabContentObj.hide();
                $('ul#myTab').find('li.active').removeClass('active');
                var currentAncorObj = $('ul#myTab').find('li a').eq(currnetIndex - 1);
                currentAncorObj.parent().addClass('active');
                $(currentAncorObj.attr('href')).show();
                currnetIndex++;

            };

            $('#myTab li').mouseenter(function () {
                clearInterval(timeInterval);
            }).mouseleave(function () {
                timeInterval = setInterval(function () { changeTabIndex(); }, 4 * 1000);
            });

            $('#myTab li a').click(function () {
                tabContentObj.hide();
                $('ul#myTab').find('li.active').removeClass('active');
                var currentAncorObj = $(this);
                currnetIndex = $('ul#myTab').find('li a').index($(this)) + 1;
                currentAncorObj.parent().addClass('active');
                $(currentAncorObj.attr('href')).show();
                currnetIndex++;

                //return false;
            });
        });

.how-it-works {
 padding-bottom: 30px;
}
.board .nav-tabs {
 position: relative;
 margin: 40px auto;
 margin-bottom: 0;
 box-sizing: border-box;
}
.board > div.board-inner > .nav-tabs {
 border: none;
}
p.narrow{
 width: 60%;
 margin: 10px auto;
}
.liner{
 height: 2px;
 background: #ddd;
 position: absolute;
 width: 80%;
 margin: 0 auto;
 left: 0;
 right: 0;
 top: 50%;
 z-index: 1;
}
.nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus {
 color: #555555;
 cursor: default;
 border: 0;
 border-bottom-color: transparent;
 outline: 0;
}
span.round-tabs{
 width: 70px;
 height: 70px;
 line-height: 70px;
 display: inline-block;
 border-radius: 100px;
 background: white;
 z-index: 2;
 position: absolute;
 left: 0;
 text-align: center;
 font-size: 25px;
}
span.round-tabs.one{
 border: 2px solid #ddd;
 color: #ddd;
}
li.active span.round-tabs.one, li.active span.round-tabs.two, li.active span.round-tabs.three, li.active span.round-tabs.four, li.active span.round-tabs.five{
 background: #36ABE7 !important;
 border: 2px solid #2AC7CC;
 color: #fff;
}

span.round-tabs,.two{
 border: 2px solid #ddd;
 color: #ddd;
}
span.round-tabs,.three{
 border: 2px solid #ddd;
 color: #ddd;
}
span.round-tabs,.four{
 border: 2px solid #ddd;
 color: #ddd;
}
span.round-tabs,.five{
 border: 2px solid #ddd;
 color: #ddd;
}
.nav-tabs > li.active > a.span.round-tabs{
 background: #fafafa;
}
.nav-tabs > li{
 width: 20%;
}
.nav-tabs > li a{
 width: 70px;
 height: 70px;
 margin: 0px auto;
 border-radius: 100%;
 padding: 0;
}

.nav-tabs > li a:hover{
 background: transparent;
}
.tab-pane{
 position: relative;
 padding-top: 50px;
}
.btn-outline-rounded{
 padding: 10px 40px;
 margin: 20px 0;
 border: 2px solid transparent;
 border-radius: 25px;
}
.btn.green{
 background-color: #69cb95;
 color: #fff;
}
@media(max-width: 585px){
 .board{
  width: 90%;
  height: auto !important;
 }
 span.round-tabs{
  font-size: 16px;
  width: 50px;
  height: 50px;
  line-height: 50px;
 }
 .tab-content.head{
  font-size:20px;
 }
 .nav-tabs > li a{
  width: 50px;
  height: 50px;
  line-height: 50px;
 }
 li.active:after{
  content:"";
  position: absolute;
  left: 35%;
 }
 .btn-outline-rounded{
  padding: 12px 20px;
 }
}

<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"/>

Our Services

Service Title 1

Service Title 2

Service Title 3

Service Title 4

Service Title 5

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eget viverra sem. Curabitur lobortis bibendum odio ac varius. Ut non felis varius, viverra nibh vel, luctus neque. Nullam eget ante a felis lacinia convallis. Vestibulum varius metus sit amet aliquam convallis. Pellentesque vel venenatis justo. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus. Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.Vestibulum finibus rhoncus urna quis dapibus.

              Know More

Please look at the codepen. Snippet have some problem.
1

Body:
Here you go with working solution https://jsfiddle.net/L64s4bxh/2/

var tabContentObj = $('.tab-pane');

tabContentObj.hide().removeClass('in');

$(currentAncorObj.attr('data-target')).show().addClass('in');


问:
Symfony 3.3 - where does assets:install look for web assets?
Back in Symfony 2.x, the assets:install command looked for assets in /path/to/YourProject/YourBundle/src/Resources/public and copied (or symlinked, depending on whether or not the flag was used) those files to /web.  Now that assets are stored in /path/to/YourProject/app/Resources in Symfony 3+, does the console command look there instead?  Should I even bother using that console command at all?

答:
According to the recent symfony best practice store your assets directly in web folder. Check this out: https://symfony.com/doc/current/best_practices/web-assets.html

This way your assets will be available without touching server-side commands. Also any frontend developer working on your project does not need to know anything about symfony, he will work directly with assets in web folder and templates in app/Resources/views


问:
Php artisan migrate fails Laravel
I have the following error. Someone is understanding why?

php artisan migrate

```<code> SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key
was too long; max key length is 767 bytes (SQL: alter table `users`
add unique `users_email_unique`(`email`))
</code>```

create_users_table.php

```<code>Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name',255);
    $table->string('email',255)->unique();
    $table->string('password',255);
    $table->rememberToken();
    $table->timestamps();
});
</code>```

答:
Edit AppServiceProvider.php file, you will find this file in app/Providers/AppServiceProvider.php

```<code>use Illuminate\Support\Facades\Schema;

public function boot()
{
     Schema::defaultStringLength(191);
}
</code>```

Then run

```<code>composer update
</code>```

on your terminal. Then try migrating your script, It would solve your problem.

Title: Php artisan migrate fails Laravel

Body:
I have the following error. Someone is understanding why?

php artisan migrate

 SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key
was too long; max key length is 767 bytes (SQL: alter table `users`
add unique `users_email_unique`(`email`))

create_users_table.php

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name',255);
    $table->string('email',255)->unique();
    $table->string('password',255);
    $table->rememberToken();
    $table->timestamps();
});

Body:
Edit AppServiceProvider.php file, you will find this file in app/Providers/AppServiceProvider.php

use Illuminate\Support\Facades\Schema;

public function boot()
{
     Schema::defaultStringLength(191);
}

Then run

composer update

on your terminal. Then try migrating your script, It would solve your problem.


问:
How can i rewrite URL in Nginx
How can i rewrite URL in nginx
http://www.example.com/dir/mobil.php
To
http://www.example.com/dir/mobil.php?action=add_form&page</p>

答:
I suggest google for such a question. Quick search with exact your terms brought this up:

https://www.nginx.com/blog/creating-nginx-rewrite-rules/

Title: How can i rewrite URL in Nginx


问:
Can I install IE7 and IE8 in Windows 10?
I'm using Windows 10 and IE 11. I wanna install IE7 and IE8 to test javascript.

I followed these links to download IE7 - IE8:

https://www.microsoft.com/en-us/download/internet-explorer-7-details.aspx
  https://www.microsoft.com/en-us/download/internet-explorer-8-details.aspx

But, the page gave me error message:

Internet Explorer 7(8) is not compatible with your system.

You are running Windows 10 64-bit. Although Internet Explorer 7(8)
  will not run on your system, you can download Internet Explorer 8 for
  other operating systems.

Is there another way (or hacking) to install IE7 and IE8 in Windows 10?

答: Just use BrowseEmAll and IE Collection, both allows you to run old Internet Explorer versions in newer Microsoft Windows systems.</p>


答:
The problem is that you are trying to access the element before it exists. You need to wait for the page to be fully loaded. A possible approach is to use the onload handler:

```<code>window.onload = function () {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';
};
</code>```

Most common JavaScript libraries provide a DOM-ready event, though. This is better, since window.onload waits for all images, too. You do not need that in most cases.

Another approach is to place the script tag right before your closing -tag, since everything in front of it is loaded at the time of execution, then.

Title: Javascript can't find element by id?

Body:
The problem is that you are trying to access the element before it exists. You need to wait for the page to be fully loaded. A possible approach is to use the onload handler:

window.onload = function () {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';
};

Most common JavaScript libraries provide a DOM-ready event, though. This is better, since window.onload waits for all images, too. You do not need that in most cases.

Another approach is to place the script tag right before your closing </body>-tag, since everything in front of it is loaded at the time of execution, then.


问:
NVDA screen reader requests wrong QAccessible::InterfaceType
I'm on Qt 5.9.1.

I'm trying to make an application accessible through screen readers. I have a custom widget (let's call it MyWidget) that contains text (a lot of it.) The text is drawn using QPainter, which is why a custom widget is used rather than something like QTextBrowser.

I implemented the QAccessibleTextInterface for the widget in a AccessibleMyWidget class that derives from QAccessibleWidget and QAccessibleTextInterface. It works fine with Orca under Linux, but when used in Windows 7 with NVDA, QAccessibleInterface::interface_cast() requests the wrong interface type. With Orca, I get requests for a QAccessible::TextInterface. In NVDA, it's always QAccessible::ValueInterface.

AccessibleMyWidget is defined as:

```<code>class AccessibleMyWidget:
    public QAccessibleWidget, public QAccessibleTextInterface {

public:
    explicit AccessibleMyWidget(QWidget* w)
        : QAccessibleWidget(w, QAccessible::EditableText)
    {
        Q_ASSERT(isValid());
    }

    void* interface_cast(QAccessible::InterfaceType t) override
    {
        if (t == QAccessible::TextInterface) {
            // !!! This is never requested with NVDA !!!
            return static_cast<QAccessibleTextInterface*>(this);
        }
        return QAccessibleWidget::interface_cast(t);
    }

    /*
     * QAccessibleTextInterface implementation below this point.
     */
    void addSelection(int startOffset, int endOffset) override;
    QString attributes(int offset, int* startOffset,
                       int* endOffset) const override;
    // etc.
};
</code>```

With Orca under Linux, everything seems to work as intended. I get calls to interface_cast() for a TextInterface, and after that, the various functions of QAccessibleTextInterface are called. With NVDA under Linux, I just get interface_cast() calls for ValueInterface, and none of the QAccessibleTextInterface functions are called. Which means MyWidget is completely inaccessible, unless I override QAccessibleWidget::text() and just return all text as a single string, which means no cursor navigation, no selection support... It basically becomes just a QLabel at this point, but with a ton of text and thus very hard to use.

What am I missing here?

答:
Well, an NVDA developer helped me track down the issue. It's because the MinGW version of Qt has IAccessible2 disabled and uses MSAA (Microsoft Active Accessibility) instead, which doesn't support any of these interfaces. IA2 needs COM, and MinGW doesn't support that.

So I would have to switch from GCC/MinGW to MSVC to make this work on Windows. Too bad that's not actually an option in the foreseeable future :-/

2020 update:

This has been fixed since. Not sure when exactly, but the current mingw Qt builds now support this.

Body:
I'm on Qt 5.9.1.

I'm trying to make an application accessible through screen readers. I have a custom widget (let's call it MyWidget) that contains text (a lot of it.) The text is drawn using QPainter, which is why a custom widget is used rather than something like QTextBrowser.

I implemented the QAccessibleTextInterface for the widget in a AccessibleMyWidget class that derives from QAccessibleWidget and QAccessibleTextInterface. It works fine with Orca under Linux, but when used in Windows 7 with NVDA, QAccessibleInterface::interface_cast() requests the wrong interface type. With Orca, I get requests for a QAccessible::TextInterface. In NVDA, it's always QAccessible::ValueInterface.

AccessibleMyWidget is defined as:

class AccessibleMyWidget:
    public QAccessibleWidget, public QAccessibleTextInterface {

public:
    explicit AccessibleMyWidget(QWidget* w)
        : QAccessibleWidget(w, QAccessible::EditableText)
    {
        Q_ASSERT(isValid());
    }

    void* interface_cast(QAccessible::InterfaceType t) override
    {
        if (t == QAccessible::TextInterface) {
            // !!! This is never requested with NVDA !!!
            return static_cast<QAccessibleTextInterface*>(this);
        }
        return QAccessibleWidget::interface_cast(t);
    }

    /*
     * QAccessibleTextInterface implementation below this point.
     */
    void addSelection(int startOffset, int endOffset) override;
    QString attributes(int offset, int* startOffset,
                       int* endOffset) const override;
    // etc.
};

With Orca under Linux, everything seems to work as intended. I get calls to interface_cast() for a TextInterface, and after that, the various functions of QAccessibleTextInterface are called. With NVDA under Linux, I just get interface_cast() calls for ValueInterface, and none of the QAccessibleTextInterface functions are called. Which means MyWidget is completely inaccessible, unless I override QAccessibleWidget::text() and just return all text as a single string, which means no cursor navigation, no selection support... It basically becomes just a QLabel at this point, but with a ton of text and thus very hard to use.

What am I missing here?


问:
Selectively inheriting from any of multiple classes at runtime
I'm doing scientific computing and I'm beginner in c++. MyNLP is a class which contain all the problem data and methods. I'm using third party libraries for numerical optimization. Each third party is a specific algorithm to solve my problem. In order to use each library, my MyNLP class need to inherit corresponding class from third party library.

For example,

```<code>Class MyNLP :public IPOPT
{
};
</code>```

enable me to use IPOPT algorithm to solve my problem. Similarly,

```<code>class MyNLP: public SQP
{
};
</code>```

enable me to use SQP algorithm.

But in my case, only at the run-time, program decides which class it should inherit. I have to inherit either one of third party class.
Could any one give a  technique to achieve this in cpp?

答:
With a little bit of template magic (well there is no such thing as magic in programming) I think this would help you to achieve your goal in the manner in which you were asking. There were many other great answers out there such Strategy Pattern, Factory, Dispatching etc. but this is a version that uses templates and inheritance from said library while choosing which one to instantiate at run time through  the use of template specialization.

```<code>#include <iostream>

class A {
public:
    int a = 1;
    A() {}
};

class B {
public:
    float b = 2.0f;
    B() {}
};

class C {
public:
    char c = 'c';
    C() {}
};

template<class T>
class D : public T {
public:
    D() : T() {}
};

int main( int argc, char** argv ) {
    D<A> dA;
    D<B> dB;
    D<C> dC;

    std::cout << "D<A>::a = " << dA.a << "\n";
    std::cout << "D<B>::b = " << dB.b << "\n";
    std::cout << "D<C>::c = " << dC.c << "\n";

    std::cout << "Press any key and enter to quit." << std::endl;
    char c;
    std::cin >> c;

    return 0;
}
</code>```

Here I have shown 3 different concrete or complete types classes A,B, & C that can represent your 3 different possible libraries that you would use to perform the evaluations or calculations to solve your problems. Class D is a template type that represents your MyNLP class. Now you can have MyNLP mynlpA use the first library as your class will now inherit from it, and so on.

However; this is done at compile time and not runtime, and you have to instantiate the class with the specific types. You could use this template and set it up with user input through if statements or a switch statement within some defined function to choose which version of your class to create and use during runtime. Also notice that I specialized the different class template constructors based on the inheriting class's base class. Run this snippet to see how I was able to get the class template D<T> to inherit from A, B, or C based on user input at runtime.

```<code>#include <iostream>
#include <string>
#include <algorithm>

class A {
public:
    int a = 1;
    A() {}
};

class B {
public:
    float b = 2.0f;
    B() {}
};

class C {
public:
    char c = 'c';
    C() {}
};

template<class T>
class D : public T {
public:
    D() : T() {}
};

template<>
D<A>::D() {
    std::cout << "Initialize Library A\n";
}

template<>
D<B>::D(){
    std::cout << "Initialize Library B\n";
}

template<>
D<C>::D() {
    std::cout << "Initialize Library C\n";
}

int main( int argc, char** argv ) {
    std::string entry;
    std::cout << "Please choose which library to chose from: `A`, `B` or `C`\n";
    std::cout << "Or `Q` to quit\n";

    std::cin >> entry;

    std::transform(entry.begin(), entry.end(), entry.begin(), ::toupper);

    while ( true ) {

        if (entry == std::string("Q")) {
            break;
        }

        if (entry == std::string("A")) {
            D<A> dA;
            std::cout << "D<A>::a = " << dA.a << "\n";
        }

        if (entry == std::string("B")) {
            D<B> dB;
            std::cout << "D<B>::b = " << dB.b << "\n";

        }

        if (entry == std::string("C")) {
            D<C> dC;
            std::cout << "D<C>::c = " << dC.c << "\n";
        }

        entry.clear();
        std::cout << "Please choose which library to chose from: `A`, `B` or `C`\n";
        std::cout << "Or `Q` to quit\n";

        std::cin >> entry;

        std::transform(entry.begin(), entry.end(), entry.begin(), ::toupper);

    }

    std::cout << "Press any key and enter to quit." << std::endl;
    char c;
    std::cin >> c;

    return 0;
}
</code>```

There is a caveat to this method though: If the base class has private members/functions that you may need to call or use directly, they will be inaccessible to you, but the good thing is you will have access to anything that is public or protected, but this is the idea of data encapsulation.

Body:
I'm doing scientific computing and I'm beginner in c++. MyNLP is a class which contain all the problem data and methods. I'm using third party libraries for numerical optimization. Each third party is a specific algorithm to solve my problem. In order to use each library, my MyNLP class need to inherit corresponding class from third party library.

For example,

Class MyNLP :public IPOPT
{
};

enable me to use IPOPT algorithm to solve my problem. Similarly,

class MyNLP: public SQP
{
};

enable me to use SQP algorithm.

But in my case, only at the run-time, program decides which class it should inherit. I have to inherit either one of third party class.
Could any one give a  technique to achieve this in cpp?

Body:
With a little bit of template magic (well there is no such thing as magic in programming) I think this would help you to achieve your goal in the manner in which you were asking. There were many other great answers out there such Strategy Pattern, Factory, Dispatching etc. but this is a version that uses templates and inheritance from said library while choosing which one to instantiate at run time through  the use of template specialization.

#include <iostream>

class A {
public:
    int a = 1;
    A() {}
};

class B {
public:
    float b = 2.0f;
    B() {}
};

class C {
public:
    char c = 'c';
    C() {}
};

template<class T>
class D : public T {
public:
    D() : T() {}
};

int main( int argc, char** argv ) {
    D<A> dA;
    D<B> dB;
    D<C> dC;

    std::cout << "D<A>::a = " << dA.a << "\n";
    std::cout << "D<B>::b = " << dB.b << "\n";
    std::cout << "D<C>::c = " << dC.c << "\n";

    std::cout << "Press any key and enter to quit." << std::endl;
    char c;
    std::cin >> c;

    return 0;
}

Here I have shown 3 different concrete or complete types classes A,B, & C that can represent your 3 different possible libraries that you would use to perform the evaluations or calculations to solve your problems. Class D is a template type that represents your MyNLP class. Now you can have MyNLP<A> mynlpA use the first library as your class will now inherit from it, and so on.

However; this is done at compile time and not runtime, and you have to instantiate the class with the specific types. You could use this template and set it up with user input through if statements or a switch statement within some defined function to choose which version of your class to create and use during runtime. Also notice that I specialized the different class template constructors based on the inheriting class's base class. Run this snippet to see how I was able to get the class template D<T> to inherit from A, B, or C based on user input at runtime.

#include <iostream>
#include <string>
#include <algorithm>

class A {
public:
    int a = 1;
    A() {}
};

class B {
public:
    float b = 2.0f;
    B() {}
};

class C {
public:
    char c = 'c';
    C() {}
};

template<class T>
class D : public T {
public:
    D() : T() {}
};

template<>
D<A>::D() {
    std::cout << "Initialize Library A\n";
}

template<>
D<B>::D(){
    std::cout << "Initialize Library B\n";
}

template<>
D<C>::D() {
    std::cout << "Initialize Library C\n";
}

int main( int argc, char** argv ) {
    std::string entry;
    std::cout << "Please choose which library to chose from: `A`, `B` or `C`\n";
    std::cout << "Or `Q` to quit\n";

    std::cin >> entry;

    std::transform(entry.begin(), entry.end(), entry.begin(), ::toupper);

    while ( true ) {

        if (entry == std::string("Q")) {
            break;
        }

        if (entry == std::string("A")) {
            D<A> dA;
            std::cout << "D<A>::a = " << dA.a << "\n";
        }

        if (entry == std::string("B")) {
            D<B> dB;
            std::cout << "D<B>::b = " << dB.b << "\n";

        }

        if (entry == std::string("C")) {
            D<C> dC;
            std::cout << "D<C>::c = " << dC.c << "\n";
        }

        entry.clear();
        std::cout << "Please choose which library to chose from: `A`, `B` or `C`\n";
        std::cout << "Or `Q` to quit\n";

        std::cin >> entry;

        std::transform(entry.begin(), entry.end(), entry.begin(), ::toupper);

    }

    std::cout << "Press any key and enter to quit." << std::endl;
    char c;
    std::cin >> c;

    return 0;
}

There is a caveat to this method though: If the base class has private members/functions that you may need to call or use directly, they will be inaccessible to you, but the good thing is you will have access to anything that is public or protected, but this is the idea of data encapsulation.


问:
Add text to image using AForge.Video.FFMEG in C#
Using  AForge.Video.FFMPEG I am able to create video from Images.

```<code>        string[] files;
        string folderPath = @"FolderPath";
        files = Directory.GetFiles(folderPath).OrderBy(c => c).ToArray();

        VideoFileWriter writer = new VideoFileWriter();
        writer.Open(@"C:folder\new.mp4", imageWidth, imageHeight, 10, VideoCodec.MPEG4);
        for (int j = 0; j < files.Length; j++)
        {
            string fileName = files[j];
            BitmapSource imageBitMap = new BitmapImage(new Uri(fileName, UriKind.RelativeOrAbsolute));
            imageBitMap.Freeze();
            int stride = imageBitMap.PixelWidth * ((imageBitMap.Format.BitsPerPixel + 7) / 8);
            byte[] ImageInBits = new byte[imageBitMap.PixelWidth * imageBitMap.PixelHeight];
            imageBitMap.CopyPixels(ImageInBits, stride, 0);

            Bitmap image = new Bitmap(imageWidth, imageHeight, stride, PixelFormat.Format8bppIndexed, Marshal.UnsafeAddrOfPinnedArrayElement(ImageInBits, 0));

            writer.WriteVideoFrame(image);
            image.Dispose();
        }
</code>```

I am trying to add text/String to input image using

```<code>    private Bitmap WriteString(Bitmap bmp)
    {
        RectangleF rectf = new RectangleF(70, 90, 90, 50);

        Bitmap tempBitmap = new Bitmap(bmp.Width, bmp.Height);
        Graphics g = Graphics.FromImage(tempBitmap);

        g.DrawImage(bmp, 0, 0);
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        g.DrawString("yourText", new Font("Tahoma", 8), Brushes.Red, rectf);
        g.Flush();

        return bmp;
    }
</code>```

like

```<code>            Bitmap image = new Bitmap(imageWidth, imageHeight, stride, PixelFormat.Format8bppIndexed, Marshal.UnsafeAddrOfPinnedArrayElement(ImageInBits, 0));
            Bitmap outputBitmap=WriteString(image);
            writer.WriteVideoFrame(outputBitmap);
</code>```

How can I write a string to Image?

Is there any way to add subtitle to AForge.Video.FFMEG to image before creating video?

答:
private Bitmap WriteString(Bitmap bmp)   {

```<code>    Bitmap tempBitmap = new Bitmap(bmp.Width, bmp.Height); << create new
    ..draw on copy..
    return bmp; <<< return original
}
</code>```

Seems to be the wrong.

Body:
Using  AForge.Video.FFMPEG I am able to create video from Images.

        string[] files;
        string folderPath = @"FolderPath";
        files = Directory.GetFiles(folderPath).OrderBy(c => c).ToArray();

        VideoFileWriter writer = new VideoFileWriter();
        writer.Open(@"C:folder\new.mp4", imageWidth, imageHeight, 10, VideoCodec.MPEG4);
        for (int j = 0; j < files.Length; j++)
        {
            string fileName = files[j];
            BitmapSource imageBitMap = new BitmapImage(new Uri(fileName, UriKind.RelativeOrAbsolute));
            imageBitMap.Freeze();
            int stride = imageBitMap.PixelWidth * ((imageBitMap.Format.BitsPerPixel + 7) / 8);
            byte[] ImageInBits = new byte[imageBitMap.PixelWidth * imageBitMap.PixelHeight];
            imageBitMap.CopyPixels(ImageInBits, stride, 0);

            Bitmap image = new Bitmap(imageWidth, imageHeight, stride, PixelFormat.Format8bppIndexed, Marshal.UnsafeAddrOfPinnedArrayElement(ImageInBits, 0));

            writer.WriteVideoFrame(image);
            image.Dispose();
        }

I am trying to add text/String to input image using

    private Bitmap WriteString(Bitmap bmp)
    {
        RectangleF rectf = new RectangleF(70, 90, 90, 50);

        Bitmap tempBitmap = new Bitmap(bmp.Width, bmp.Height);
        Graphics g = Graphics.FromImage(tempBitmap);

        g.DrawImage(bmp, 0, 0);
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        g.DrawString("yourText", new Font("Tahoma", 8), Brushes.Red, rectf);
        g.Flush();

        return bmp;
    }

like

            Bitmap image = new Bitmap(imageWidth, imageHeight, stride, PixelFormat.Format8bppIndexed, Marshal.UnsafeAddrOfPinnedArrayElement(ImageInBits, 0));
            Bitmap outputBitmap=WriteString(image);
            writer.WriteVideoFrame(outputBitmap);

How can I write a string to Image?

Is there any way to add subtitle to AForge.Video.FFMEG to image before creating video?

Body:
private Bitmap WriteString(Bitmap bmp)   {

    Bitmap tempBitmap = new Bitmap(bmp.Width, bmp.Height); << create new
    ..draw on copy..
    return bmp; <<< return original
}

Seems to be the wrong.


问:
Allow user to name and select location of exported table
I've got a table called 'resultsHt'. I'd like to prompt the user to select a filename and directory for it to output to. I've had a look round and can't spot an easy way to do it that works on mac and windows. I'd be grateful for your help!</p>

答:
Thanks. That looks to work for opening files - it opens in XQuartz. However, it is still trying to open a file, rather than write one. Do you know how to modify this code to work?

```<code>library(tcltk)
library(xlsx)
write.xlsx(resultsHt, tk_choose.files(caption = "Choose X"))
</code>```

Update
I've worked out that the following achieves this, at least on mac:

```<code>require(tcltk)
output <- tclvalue(tcl("tk_getSaveFile")) #User inputs Save As directory and filename
output <- paste0(output, ".xlsx") #Appends .xlsx for write.xlsx function
write.xlsx(resultsHt, output, sheetName="height", row.names=FALSE)
</code>```

Body:
Thanks. That looks to work for opening files - it opens in XQuartz. However, it is still trying to open a file, rather than write one. Do you know how to modify this code to work?

library(tcltk)
library(xlsx)
write.xlsx(resultsHt, tk_choose.files(caption = "Choose X"))

Update
I've worked out that the following achieves this, at least on mac:

require(tcltk)
output <- tclvalue(tcl("tk_getSaveFile")) #User inputs Save As directory and filename
output <- paste0(output, ".xlsx") #Appends .xlsx for write.xlsx function
write.xlsx(resultsHt, output, sheetName="height", row.names=FALSE)


答:
Run the code either in onload event, either just before you close body tag.
You try to find an element wich is not there at the moment you do it.

Title: Javascript can't find element by id?

Body:
    <title>Test javascript</title>

If I use alert(e); it turns up null.... and obviously I don't get any "found you" on screen. What am I doing wrong?


问:
Using PHP array in the JS code in PDO
I'm trying to use a PHP array in the JS but encountered the error I don't know how to fix.

I was using this example (in my case - it's PDO, not mysqli.): Inserting MYSQL results from PHP into Javascript Array

```<code>$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . '; charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$type_zagon = 1;
$id_kurat = 1;
$usid = 78;

$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
    AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$num = $stmt1->fetchColumn();
$stmt1->execute(array(
    ':status' => 1,
    ':type' => $type_zagon,
    ':zagon_id' => $id_kurat,
    ':usid' => $usid
));

    $gyvuliu_array = array();

    while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
        $gyvuliu_array[] = $num;
    }

    $array_encode = json_encode($gyvuliu_array);
?>
    <script>
        $('.surinkti_produkcija_paserti_gyvulius').click(function() {
            var gyvuliai_fermoje = '<?php echo $array_encode; ?>';
            var gyvuliu_array = [1,2,3,4,5,6,7,8,9];

            for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
                console.log(gyvuliu_array[i]);
            }

            // DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
            for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
                console.log(gyvuliai_fermoje[i]);
            }
        });
    </script>
</code>```

I guess something is bad with the $num variable but I'm not sure.

EDIT:
I've changed the second for loop and it looks like it's working:

```<code>for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
    console.log(gyvuliai_fermoje[i]);
}
</code>```

But I'm not sure if it's ok they aren't in the same row.
http://prntscr.com/ft4i9m

EDIT 2 After rickdenhaan's comment, it looks exactly how first for loop. Is it ok? Am I done?

答:
```<code>var gyvuliai_fermoje = <?php echo $array_encode; ?>;
</code>```

You have to remove quotes, why? If you put the value in quotes that mean var gyvuliai_fermoje is a string not an array

Title: Using PHP array in the JS code in PDO

Body:
I'm trying to use a PHP array in the JS but encountered the error I don't know how to fix.

I was using this example (in my case - it's PDO, not mysqli.): Inserting MYSQL results from PHP into Javascript Array

$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . '; charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$type_zagon = 1;
$id_kurat = 1;
$usid = 78;

$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
    AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$num = $stmt1->fetchColumn();
$stmt1->execute(array(
    ':status' => 1,
    ':type' => $type_zagon,
    ':zagon_id' => $id_kurat,
    ':usid' => $usid
));

    $gyvuliu_array = array();

    while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
        $gyvuliu_array[] = $num;
    }

    $array_encode = json_encode($gyvuliu_array);
?>

I guess something is bad with the $num variable but I'm not sure.

EDIT:
I've changed the second for loop and it looks like it's working:

for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
    console.log(gyvuliai_fermoje[i]);
}

But I'm not sure if it's ok they aren't in the same row.
http://prntscr.com/ft4i9m

EDIT 2 After rickdenhaan's comment, it looks exactly how first for loop. Is it ok? Am I done?

Body:
var gyvuliai_fermoje = <?php echo $array_encode; ?>;

You have to remove quotes, why? If you put the value in quotes that mean var gyvuliai_fermoje is a string not an array


问:
how to get truth value in for loop with if statement
I am unable to get the correct value for the conditional if statement nested with for loop.Here is an example written in code,

```<code># Input data
d11 = np.matrix([[3,6,1],[6,8,1],[1,1,1],[5,8,9]])
qp1 = np.matrix([[1],[3],[5]])
h1 = np.matrix([[5],[40],[100],[5]])
</code>```

I need that row of d11 matrix whose value on multiplying with qp1 is less than the corresponding value in h1 i.e d11[i] * qp < h[i].The code for this is,

```<code>for x in range(len(d11)):
    if d11[x] * qp1 < h1[x]:
        a = d11[x]
    else:
        a = []
</code>```

when we multipy d11 and qp1 we get the values as  [26,35 , 9 ,22].Thus if we compare with h1, we find the condition is True for 2nd row i.e 35< 40 and 3rd row i.e9 < 100 .So the answer is [[6,8,1],[1,1,1]].But i am unable to get the answer.Please suggest me the correct way..

答:
Your if statement is checking whether or not the list created by the list comprehension
[aa[i] > 10 for i in range(len(a))] (ie the list [False, False, False, False]) is empty.

Since it is not empty the if statement is evaluated to True.

Instead, consider using any:

```<code>aa = [1, 4, 5, 6]
if any(num > 10 for num in aa):
    c = aa[i],'t'  # as (correctly) pointed out in the comments below,
                   # i is not defined here since we are no longer using an index
                   # to iterate over the list's elements.
                   # You'll need to decide what you want to do in case an element
                   # IS larger than 10.
else:
    c = 0
</code>```

Your code has another bug: by the time the list comprehension is done, i will always be the last index.

Body:
I am unable to get the correct value for the conditional if statement nested with for loop.Here is an example written in code,

# Input data
d11 = np.matrix([[3,6,1],[6,8,1],[1,1,1],[5,8,9]])
qp1 = np.matrix([[1],[3],[5]])
h1 = np.matrix([[5],[40],[100],[5]])

I need that row of d11 matrix whose value on multiplying with qp1 is less than the corresponding value in h1 i.e d11[i] * qp < h[i].The code for this is,

for x in range(len(d11)):
    if d11[x] * qp1 < h1[x]:
        a = d11[x]
    else:
        a = []

when we multipy d11 and qp1 we get the values as  [26,35 , 9 ,22].Thus if we compare with h1, we find the condition is True for 2nd row i.e 35< 40 and 3rd row i.e9 < 100 .So the answer is [[6,8,1],[1,1,1]].But i am unable to get the answer.Please suggest me the correct way..

Body:
Your if statement is checking whether or not the list created by the list comprehension
[aa[i] > 10 for i in range(len(a))] (ie the list [False, False, False, False]) is empty.

Since it is not empty the if statement is evaluated to True.

Instead, consider using any:

aa = [1, 4, 5, 6]
if any(num > 10 for num in aa):
    c = aa[i],'t'  # as (correctly) pointed out in the comments below,
                   # i is not defined here since we are no longer using an index
                   # to iterate over the list's elements.
                   # You'll need to decide what you want to do in case an element
                   # IS larger than 10.
else:
    c = 0

Your code has another bug: by the time the list comprehension is done, i will always be the last index.


答:
Your condition is equivalent to:

```<code>if len([aa[i] > 10 for i in range(len(a))]):
</code>```

ie. you're checking if the list is nonempty. And it is nonempty - it consists of four Falses.

Title: how to get truth value in for loop with if statement

Body:
Your condition is equivalent to:

if len([aa[i] > 10 for i in range(len(a))]):

ie. you're checking if the list is nonempty. And it is nonempty - it consists of four Falses.


答:
Could You please try this once </p>

```<code> $stmt1 = $pdo->prepare("SELECT GROUP_CONCAT(num) as nums FROM tb_zagon_id WHERE status = :status
    AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
 $stmt1->execute(array(
    ':status' => 1,
    ':type' => $type_zagon,
    ':zagon_id' => $id_kurat,
    ':usid' => $usid
));
 $row = $stmt1->fetch();
 $array_encode = json_encode(explode(",",$row["nums"]));
?>
 <script>
    var gyvuliai_fermoje = <?php echo $array_encode; ?>;
    $('.surinkti_produkcija_paserti_gyvulius').click(function() {
        var gyvuliu_array = [1,2,3,4,5,6,7,8,9];

        for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
            console.log(gyvuliu_array[i]);
        }

        // DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
        for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
            console.log(gyvuliai_fermoje[i]);
        }
    });
 </script>
</code>```

Title: Using PHP array in the JS code in PDO

Body:
Could You please try this once

 $stmt1 = $pdo->prepare("SELECT GROUP_CONCAT(num) as nums FROM tb_zagon_id WHERE status = :status
    AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
 $stmt1->execute(array(
    ':status' => 1,
    ':type' => $type_zagon,
    ':zagon_id' => $id_kurat,
    ':usid' => $usid
));
 $row = $stmt1->fetch();
 $array_encode = json_encode(explode(",",$row["nums"]));
?>
 <script>
    var gyvuliai_fermoje = <?php echo $array_encode; ?>;
    $('.surinkti_produkcija_paserti_gyvulius').click(function() {
        var gyvuliu_array = [1,2,3,4,5,6,7,8,9];

        for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
            console.log(gyvuliu_array[i]);
        }

        // DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
        for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
            console.log(gyvuliai_fermoje[i]);
        }
    });
 </script>


问:
Call Laravel controller from code and pass HTTP headers to it
To call a controller I use a CURL request like this:

```<code>curl -kX POST https://site/method  -H 'Authorization: Bearer ACCESS_TOKEN\
Content-Type:application/json' -d '
{
    "param1":"value 1",
    "param2":"value 2",
    "param3":"value 3"
}'
</code>```

The route calls UserController@method.

How can I do the same from Laravel code (internal request, not sending CURL)?

I've found an advice to use something like this

```<code>        $controller = app()->make($controllerName);
        $response = app()->call([$controller, 'method'], []);
        echo $response;
</code>```

where the last [] should contain some parameters. But if this is the way, I cannot figure out how the array should look in my case.

P.S. Please, don't answer "it's a bad practice" instead of giving an advice how to implement what I need.

答: I do not see a simple solution to do this. It's not a good idea to call a controller from other methods. The controller responds to the request and should not be used as trivial class. If you need to test the controller, laravel provides methods for testing, including calling the controller. https://laravel.com/docs/5.4/testing. If you need to call some method in several places - better define it in model, or repository and then call it where you want.</p>

Body:
To call a controller I use a CURL request like this:

curl -kX POST https://site/method  -H 'Authorization: Bearer ACCESS_TOKEN\
Content-Type:application/json' -d '
{
    "param1":"value 1",
    "param2":"value 2",
    "param3":"value 3"
}'

The route calls UserController@method.

How can I do the same from Laravel code (internal request, not sending CURL)?

I've found an advice to use something like this

        $controller = app()->make($controllerName);
        $response = app()->call([$controller, 'method'], []);
        echo $response;

where the last [] should contain some parameters. But if this is the way, I cannot figure out how the array should look in my case.

P.S. Please, don't answer "it's a bad practice" instead of giving an advice how to implement what I need.


答:
The list Comprehensions is evalutaed differntly than you think. You are checking whether the list is not empty and return the last element of the list.

What you want is someting like:

```<code>aa = [1,4,5,6,101]
c = [elem for elem in aa if elem >10]
</code>```

If c is not empty, you know that elements above 10 have been in the list.

Body:
The list Comprehensions is evalutaed differntly than you think. You are checking whether the list is not empty and return the last element of the list.

What you want is someting like:

aa = [1,4,5,6,101]
c = [elem for elem in aa if elem >10]

If c is not empty, you know that elements above 10 have been in the list.


问:
Rails: Flash Messages not appearing anywhere
So let's say I have code like this:

```<code>class PostsController < InheritedResources::Base
  # Add before_filter here and devise should handle the redirection if the user is not signed in.
  before_filter :authenticate_user!, only: [:vote_up]

  def vote_up
  begin
  current_user.vote_for(@post = Post.find(params[:id]))
  redirect_to [@post]
  flash[:success] = "You have voted successfully"
rescue ActiveRecord::RecordInvalid
  redirect_to [@post]
  flash[:error] =  "You have already voted"
  end
 end

end
</code>```

Neither of the messages "You have voted successfully" or "You have already voted" are being shown.

In my view I have:

```<code>enter code here

<p id="notice"><%= notice %></p>
    <%= @post.embed .html_safe %>
    <header>
        <h7><%= @post.name %></h7>
    </header>
<h8><%= @post.title %></h8>
<article>
<%= @post.content .html_safe %>

<p>
<%= link_to 'Back', posts_path %> |
<%= link_to('Vote for this song!', vote_up_post_path(@post), :method => :post) %></p>

<p><id="notice"><%= notice %></p>
</code>```

No dice. I'm still not getting flash messages anywhere. Any idea what I'm doing wrong?

答:
Your code is like:
<id="notice"><%= notice %>

You need
<%= notice %>

Body:
So let's say I have code like this:

class PostsController < InheritedResources::Base
  # Add before_filter here and devise should handle the redirection if the user is not signed in.
  before_filter :authenticate_user!, only: [:vote_up]

  def vote_up
  begin
  current_user.vote_for(@post = Post.find(params[:id]))
  redirect_to [@post]
  flash[:success] = "You have voted successfully"
rescue ActiveRecord::RecordInvalid
  redirect_to [@post]
  flash[:error] =  "You have already voted"
  end
 end

end

Neither of the messages "You have voted successfully" or "You have already voted" are being shown.

In my view I have:

enter code here

<%= notice %>

    <%= @post.embed .html_safe %>

        <h7><%= @post.name %></h7>

<h8><%= @post.title %></h8>

<%= @post.content .html_safe %>

<%= link_to 'Back', posts_path %> |
<%= link_to('Vote for this song!', vote_up_post_path(@post), :method => :post) %>

<id="notice"><%= notice %>

No dice. I'm still not getting flash messages anywhere. Any idea what I'm doing wrong?

Body:
Your code is like: <p><id="notice"><%= notice %></p>

You need <p id="notice"><%= notice %></p>