问:
Force to landscape mode without setting auto rotate
I have a simple example:

One button in the middle of the view. I want to press that button to force landscape mode then press again to force portrait mode, but I don't want it auto rotate. I know if I set shouldAutorotate -> true, it will work, but in my case, I don't want auto rotate mode.

```<code>class ViewController: UIViewController {

    var isLanscape = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func rotate(_ sender: Any) {
        isLanscape = !isLanscape
        if isLanscape == true {
            let value = UIInterfaceOrientation.landscapeRight.rawValue
            UIDevice.current.setValue(value, forKey: "orientation")
        } else {
            let value = UIInterfaceOrientation.portrait.rawValue
            UIDevice.current.setValue(value, forKey: "orientation")
        }

    }

    override var shouldAutorotate: Bool {
        return false
    }
}
</code>```

答:
Finally, I found solution for this case.

if shouldAutorotate -> false, you will never be able to rotate screen, so I did some tricks here.

```<code>class ViewController: UIViewController {

    var isLanscape = false
    var shouldRotate = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func rotate(_ sender: Any) {
        isLanscape = !isLanscape
        shouldRotate = true
        if isLanscape == true {
            let value = UIInterfaceOrientation.landscapeRight.rawValue
            UIDevice.current.setValue(value, forKey: "orientation")
        } else {
            let value = UIInterfaceOrientation.portrait.rawValue
            UIDevice.current.setValue(value, forKey: "orientation")
        }
        self.shouldRotate = false
    }

    override var shouldAutorotate: Bool {
        let orientation = UIDevice.current.value(forKey: "orientation") as! Int
        if (orientation == 1 || orientation == 3) && shouldRotate == true {
            return true
        } else {
            return false
        }
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return [.portrait, .landscapeRight]
    }
}
</code>```

Body:
I have a simple example:

One button in the middle of the view. I want to press that button to force landscape mode then press again to force portrait mode, but I don't want it auto rotate. I know if I set shouldAutorotate -> true, it will work, but in my case, I don't want auto rotate mode.

class ViewController: UIViewController {

    var isLanscape = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func rotate(_ sender: Any) {
        isLanscape = !isLanscape
        if isLanscape == true {
            let value = UIInterfaceOrientation.landscapeRight.rawValue
            UIDevice.current.setValue(value, forKey: "orientation")
        } else {
            let value = UIInterfaceOrientation.portrait.rawValue
            UIDevice.current.setValue(value, forKey: "orientation")
        }

    }

    override var shouldAutorotate: Bool {
        return false
    }
}

Body:
Finally, I found solution for this case.

if shouldAutorotate -> false, you will never be able to rotate screen, so I did some tricks here.

class ViewController: UIViewController {

    var isLanscape = false
    var shouldRotate = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func rotate(_ sender: Any) {
        isLanscape = !isLanscape
        shouldRotate = true
        if isLanscape == true {
            let value = UIInterfaceOrientation.landscapeRight.rawValue
            UIDevice.current.setValue(value, forKey: "orientation")
        } else {
            let value = UIInterfaceOrientation.portrait.rawValue
            UIDevice.current.setValue(value, forKey: "orientation")
        }
        self.shouldRotate = false
    }

    override var shouldAutorotate: Bool {
        let orientation = UIDevice.current.value(forKey: "orientation") as! Int
        if (orientation == 1 || orientation == 3) && shouldRotate == true {
            return true
        } else {
            return false
        }
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return [.portrait, .landscapeRight]
    }
}


来源: stackexchange

问:
MVC view first load - Is it better to set conditional div css in the html or javascript?
I am sending value from controller to view and I want to color it red if its zero.

Is it better to do it in html after zero check

```<code>@var redColor = Model.Number == 0 ? "redColor" : "";
<div class = @redColor id="number">
</code>```

or in javascript during init

```<code>if($(#number).val() === 0)
{
   $(#number).addClass("redColor");
}
</code>```

Thanks

答:
Here is Example, I'm using View Bag, then use in my Javascript ,
Ithink its better and more readability to use in javascript. . .
I'm also waiting Answer from Experienced Developer. . .

ActionMethod

```<code>  `public ActionResult Index()
    {
        ViewBag.Color = 1;
        return View();
    }`
</code>```

HTML:

```<code><html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div id="colorMe">
    Blah blah
</div>
</body>
</html>

<script src="~/Scripts/jquery-1.10.2.js"></script>

<script>
var num=@ViewBag.Color;
num == 1 ? $('#colorMe').css('background-color' ,'red') : '';
</script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am sending value from controller to view and I want to color it red if its zero.

Is it better to do it in html after zero check

@var redColor = Model.Number == 0 ? "redColor" : "";

or in javascript during init

if($(#number).val() === 0)
{
   $(#number).addClass("redColor");
}

Thanks

Body:
Here is Example, I'm using View Bag, then use in my Javascript ,
Ithink its better and more readability to use in javascript. . .
I'm also waiting Answer from Experienced Developer. . .

ActionMethod

  `public ActionResult Index()
    {
        ViewBag.Color = 1;
        return View();
    }`

HTML:

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div id="colorMe">
    Blah blah
</div>
</body>
</html>

<script src="~/Scripts/jquery-1.10.2.js"></script>

<script>
var num=@ViewBag.Color;
num == 1 ? $('#colorMe').css('background-color' ,'red') : '';
</script>


问:
Unbound generic return type in Java
I am playing with some ideas about constructing Java APIs and today I spent some time thinking about this code:

```<code>public <T> T getField1(Class<?> type, Class<T> retvalType, String fieldName) {
  Object retval = ...; // boring reflection code - value could be dog, could be duck
  return retvalType.cast(retval); // cast to expected - exception is raised here
}

// usage - we manually repeat the LHS type as a parameter
int foo = getField(o, Integer.class, "foo");
</code>```

This is how I would typically write the API, witht he idea that specifying the retvalType gives me extra type safety. But does it?

Because we have reflection involved, the retval type is unknown. Casting on the second line would reliably catch type mismatch only when retvalType is non-generic. On the other hand, even if we don't do this explicit cast, the Java runtime would cast the generic result when it sets it to a variable - in other words, are there any drawbacks if we rewrite the code above as:

```<code>public <T> T getField2(Class<?> type, String fieldName) {
  return ...; // boring reflection code - the value type will be checked when we assign it
}

// usage - exception is raised at the next line if types don't match
int foo = getField(o, "foo");
</code>```

The advantage of the latter code is that the usage is more compact and we don't have to repeat ourselves. The disadvantage is that type cast exceptions come from non-obvious place (there is no explicit cast at the calls site), but I'm starting to think that that is OK - by specifying type literal, we only repeat what we already know, but ultimately because of reflection the program soundness is still not guaranteed.

Can anybody make a good argument why the first snippet would be preferable to the second?

Edit 1:

One argument is that by having the expected type as a parameter, we can accommodate a need to do non-trivial coercion without changing the API.

For example, the looked-up field may be of type Date, but we may be requesting long, which could be converted internally by doing date.getTime(). Still this seems far-fetched to me and there is risk of mixing responsibilities.

On the other hand, not passing the type limits the input dependencies, which makes the API more robust to changes. (Cue in 'information hiding', 'instability metric', etc).

答:
In conversation with @shmosel it came up that the runtime cast, on which the second version relies, will not necessarily happen when the LHS type is generic type.

For example, consider the code:

```<code>class Foo<T> {
  void a1(Object o) {
    // forces to be explicit about the chance of heap polution
    @SuppressWarning("unchecked")
    Set<String> a = (Set<String>) getField1(o, Set.class, "foo");
    T c = (T) getField1(o, Set.class, "foo"); // guaranteed not to compile
  }

  void a2(Object o) {
    // implicit chance of heap polution in case of Set<Date>
    Set<String> a = (Set<String>) getField2(o, "foo");
    T c = getField2(o, "foo"); // will succeed even if foo is Date
  }
}
</code>```

In other words, by doing the casting in the getField() method, we get a hard guarantee that the value is of the specified class, even if it is not used, or assigned to an Object variable (which happens often in dynamic languages and reflective libraries).

Title: Unbound generic return type in Java

Body:
I am playing with some ideas about constructing Java APIs and today I spent some time thinking about this code:

public <T> T getField1(Class<?> type, Class<T> retvalType, String fieldName) {
  Object retval = ...; // boring reflection code - value could be dog, could be duck
  return retvalType.cast(retval); // cast to expected - exception is raised here
}

// usage - we manually repeat the LHS type as a parameter
int foo = getField(o, Integer.class, "foo");

This is how I would typically write the API, witht he idea that specifying the retvalType gives me extra type safety. But does it?

Because we have reflection involved, the retval type is unknown. Casting on the second line would reliably catch type mismatch only when retvalType is non-generic. On the other hand, even if we don't do this explicit cast, the Java runtime would cast the generic result when it sets it to a variable - in other words, are there any drawbacks if we rewrite the code above as:

public <T> T getField2(Class<?> type, String fieldName) {
  return ...; // boring reflection code - the value type will be checked when we assign it
}

// usage - exception is raised at the next line if types don't match
int foo = getField(o, "foo");

The advantage of the latter code is that the usage is more compact and we don't have to repeat ourselves. The disadvantage is that type cast exceptions come from non-obvious place (there is no explicit cast at the calls site), but I'm starting to think that that is OK - by specifying type literal, we only repeat what we already know, but ultimately because of reflection the program soundness is still not guaranteed.

Can anybody make a good argument why the first snippet would be preferable to the second?

Edit 1:

One argument is that by having the expected type as a parameter, we can accommodate a need to do non-trivial coercion without changing the API.

For example, the looked-up field may be of type Date, but we may be requesting long, which could be converted internally by doing date.getTime(). Still this seems far-fetched to me and there is risk of mixing responsibilities.

On the other hand, not passing the type limits the input dependencies, which makes the API more robust to changes. (Cue in 'information hiding', 'instability metric', etc).

Body:
In conversation with @shmosel it came up that the runtime cast, on which the second version relies, will not necessarily happen when the LHS type is generic type.

For example, consider the code:

class Foo<T> {
  void a1(Object o) {
    // forces to be explicit about the chance of heap polution
    @SuppressWarning("unchecked")
    Set<String> a = (Set<String>) getField1(o, Set.class, "foo");
    T c = (T) getField1(o, Set.class, "foo"); // guaranteed not to compile
  }

  void a2(Object o) {
    // implicit chance of heap polution in case of Set<Date>
    Set<String> a = (Set<String>) getField2(o, "foo");
    T c = getField2(o, "foo"); // will succeed even if foo is Date
  }
}

In other words, by doing the casting in the getField() method, we get a hard guarantee that the value is of the specified class, even if it is not used, or assigned to an Object variable (which happens often in dynamic languages and reflective libraries).


问:
HTTP/1.1 400 Bad Request between an AWS server to another AWS server but HTTP/1.1 200 between my local server and the same AWS server

Reference

PHP App1 AWS instances

AWSApp1Live (64bit Amazon Linux 2015.03 v1.4.6 running PHP 5.5)

AWSApp1Test (64bit Amazon Linux 2015.03 v1.3.2 running PHP 5.6)

PHP App2 AWS instances

AWSApp2Live (64bit Amazon Linux 2016.09 v2.3.2 running PHP 5.6)

AWSApp2Test (64bit Amazon Linux 2015.09 v2.0.4 running PHP 5.5)

Local App1 instance

LocalApp1 (Windows 10 running XAMPP Control Panel v3.2.1)

Overview

I have two PHP applications: PHP App1 and PHP App2 which work together by communicating with eachother using internal POST requests. PHP App1 sends a request using

```<code>$query = http_build_query($data);
$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-Type: application/x-www-form-urlencoded' . PHP_EOL .
        'Cv-Forwarded-For: ' . $_SERVER["REMOTE_ADDR"] . PHP_EOL,
        'content' => $query,
    ),
    'ssl'=>array(
        'verify_peer'=>false,
        'verify_peer_name'=>false
    )
));

$response = @file_get_contents(
    $target = $this->api_target.$action,
    $use_include_path = false,
    $context
);
</code>```

PHP App2 is running a RESTful API service which responds to the requests sent from PHP App1. The response is a JSON string.

Problem

I have loaded these PHP applications onto four different AWS instances as mentioned above. The following combinations of request/respone

AWSApp1Live communicating with AWSApp2Live

```<code>(HTTP/1.1 400 Bad Request)
</code>```

AWSApp1Test communicating with AWSApp2Live

```<code>(HTTP/1.1 400 Bad Request)
</code>```

AWSApp1Test communicating with AWSApp2Test

```<code>(HTTP/1.1 200 OK)
</code>```

LocalApp1 communicating with AWSApp2Live

```<code>(HTTP/1.1 200 OK)
</code>```

So as you can see, PHP App2 when loaded onto AWSApp2Test and sent a request from AWSApp1Test, it responds with (HTTP/1.1 200 OK). But when loaded onto AWSApp2Live and given the same request from either AWSApp1Live or AWSApp1Test it responds with (HTTP/1.1 400 Bad Request). The only time AWSApp2Live responds with (HTTP/1.1 200 OK) is when the request was sent from LocalApp1.

Attempts to fix so far

We thought there might be something to do with the Zlib output compression setting on the AWSApp2Live software configuration, but the response was still the same.

We've done an nslookup from the LocalApp1 server and the AWSApp2Test server for the AWSApp2Live server and both of them returned the same IP addresses to rule out any DNS issues

We SSH'd into the AWSApp1Test server and did a wget for one of the API commands on the AWSApp2Live server and we got back a JSON response which meant it is reaching the PHP application on that server.

There are no logs being generated on the AwsApp2Live server for me to see why the server is treating some requests as bad requests and others as not.

Using Postman (https://www.getpostman.com/) I was able to successfully communicate with the API on AWSApp2Live so the application is running as expected.

Any help would be greatly appreciated!

We are not sure where to look for any further clues as to what might be happening. If you need any further information please let us know. Thank you so much.

答:
There's nothing in the documentation, but I think headers should be passed as a string only if there's a single one of them. Otherwise use an array:</p>

```<code>$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => array(
            'Content-Type: application/x-www-form-urlencoded',
            'Cv-Forwarded-For: ' . $_SERVER["REMOTE_ADDR"]
        ),
        'content' => $query,
    ),
    'ssl'=>array(
        'verify_peer'=>false,
        'verify_peer_name'=>false
    )
));
</code>```

Body:
Reference

PHP App1 AWS instances

AWSApp1Live (64bit Amazon Linux 2015.03 v1.4.6 running PHP 5.5)

AWSApp1Test (64bit Amazon Linux 2015.03 v1.3.2 running PHP 5.6)

PHP App2 AWS instances

AWSApp2Live (64bit Amazon Linux 2016.09 v2.3.2 running PHP 5.6)

AWSApp2Test (64bit Amazon Linux 2015.09 v2.0.4 running PHP 5.5)

Local App1 instance

LocalApp1 (Windows 10 running XAMPP Control Panel v3.2.1)

Overview

I have two PHP applications: PHP App1 and PHP App2 which work together by communicating with eachother using internal POST requests. PHP App1 sends a request using

$query = http_build_query($data);
$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-Type: application/x-www-form-urlencoded' . PHP_EOL .
        'Cv-Forwarded-For: ' . $_SERVER["REMOTE_ADDR"] . PHP_EOL,
        'content' => $query,
    ),
    'ssl'=>array(
        'verify_peer'=>false,
        'verify_peer_name'=>false
    )
));

$response = @file_get_contents(
    $target = $this->api_target.$action,
    $use_include_path = false,
    $context
);

PHP App2 is running a RESTful API service which responds to the requests sent from PHP App1. The response is a JSON string.

Problem

I have loaded these PHP applications onto four different AWS instances as mentioned above. The following combinations of request/respone

AWSApp1Live communicating with AWSApp2Live

(HTTP/1.1 400 Bad Request)

AWSApp1Test communicating with AWSApp2Live

(HTTP/1.1 400 Bad Request)

AWSApp1Test communicating with AWSApp2Test

(HTTP/1.1 200 OK)

LocalApp1 communicating with AWSApp2Live

(HTTP/1.1 200 OK)

So as you can see, PHP App2 when loaded onto AWSApp2Test and sent a request from AWSApp1Test, it responds with (HTTP/1.1 200 OK). But when loaded onto AWSApp2Live and given the same request from either AWSApp1Live or AWSApp1Test it responds with (HTTP/1.1 400 Bad Request). The only time AWSApp2Live responds with (HTTP/1.1 200 OK) is when the request was sent from LocalApp1.

Attempts to fix so far

We thought there might be something to do with the Zlib output compression setting on the AWSApp2Live software configuration, but the response was still the same.

We've done an nslookup from the LocalApp1 server and the AWSApp2Test server for the AWSApp2Live server and both of them returned the same IP addresses to rule out any DNS issues

We SSH'd into the AWSApp1Test server and did a wget for one of the API commands on the AWSApp2Live server and we got back a JSON response which meant it is reaching the PHP application on that server.

There are no logs being generated on the AwsApp2Live server for me to see why the server is treating some requests as bad requests and others as not.

Using Postman (https://www.getpostman.com/) I was able to successfully communicate with the API on AWSApp2Live so the application is running as expected.

Any help would be greatly appreciated!

We are not sure where to look for any further clues as to what might be happening. If you need any further information please let us know. Thank you so much.

Body:
There's nothing in the documentation, but I think headers should be passed as a string only if there's a single one of them. Otherwise use an array:

$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => array(
            'Content-Type: application/x-www-form-urlencoded',
            'Cv-Forwarded-For: ' . $_SERVER["REMOTE_ADDR"]
        ),
        'content' => $query,
    ),
    'ssl'=>array(
        'verify_peer'=>false,
        'verify_peer_name'=>false
    )
));


问:
Use model attribute as field parameter
I'm trying to create a folder and upload an image to in it. My model is similar to this:

```<code>class XYZ(models.Model):
    def code(self):
      syms = ['@','#','$','%','&','*','+','-']
      return ''.join(x+random.choice(syms) for x in [self.name[-2:],self.name[2:]])

    def make_folder(self):
        os.mkdir(os.getcwd()+'/XYZ/'+folder)

    def save(self):
        self.make_folder()
        super(XYZ,self).save(*args,**kwargs)

    name = models.CharField(max_length=20)
    folder = property(code)
    image = models.ImageField(upload_to='HELP_HERE')
</code>```

I've tried using folder, self.folder, property(code) but it says it isn't defined, how do I access this attribute? Is this the correct approach?

I've also set in the configs.py my MEDIA_URL and MEDIA_ROOT

答:
I think a more simple and understandable way to do this would be to avoid using the inner class function and doing something like this:

```<code># Reference this function outside of your model class.
def xyz_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/xyz_<id>/<filename>
    return 'xyz_{0}/{1}'.format(instance.id, filename)
</code>```

Then, on your models, reference the function in your upload_to field like so:

```<code>class XYZ(models.Model):
    image = models.ImageField(upload_to=xyz_directory_path)
</code>```

With your media config set up, this should work. There's a really nice and simple explanation about file handling here.

Title: Use model attribute as field parameter

Body:
I'm trying to create a folder and upload an image to in it. My model is similar to this:

class XYZ(models.Model):
    def code(self):
      syms = ['@','#','$','%','&','*','+','-']
      return ''.join(x+random.choice(syms) for x in [self.name[-2:],self.name[2:]])

    def make_folder(self):
        os.mkdir(os.getcwd()+'/XYZ/'+folder)

    def save(self):
        self.make_folder()
        super(XYZ,self).save(*args,**kwargs)

    name = models.CharField(max_length=20)
    folder = property(code)
    image = models.ImageField(upload_to='HELP_HERE')

I've tried using folder, self.folder, property(code) but it says it isn't defined, how do I access this attribute? Is this the correct approach?

I've also set in the configs.py my MEDIA_URL and MEDIA_ROOT

Body:
I think a more simple and understandable way to do this would be to avoid using the inner class function and doing something like this:

# Reference this function outside of your model class.
def xyz_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/xyz_<id>/<filename>
    return 'xyz_{0}/{1}'.format(instance.id, filename)

Then, on your models, reference the function in your upload_to field like so:

class XYZ(models.Model):
    image = models.ImageField(upload_to=xyz_directory_path)

With your media config set up, this should work. There's a really nice and simple explanation about file handling here.


问:
WP CSS problems / Url Problems
I've got some problemes with my WP.
I've got a distant web site and I need to modify it. So i copy it on a wamp server to work on local.
Problemes are coming ^^

First when i go into localhost/my_site/wp-admin and I log myself no css are loading, and workpress is new for me so it's a little bit difficult to doing that without css.

Second when i click on a link in my local web site I've got 2 time the url.

I mean : 127.0.0.1/my_site/127.0.0.1/my_site/mypageIneed.

And obviously that doesn't work.

EDIT

I fix the CSS problems

答: If you already downloaded  database and all files from your cpanel and everything is settled up on your localhost including database import. Just search this plugin online and place it to your root directory  "Search-Replace-DB-master" run it on your browser and change all the links ( Ex. www.xyz.com/   to localhost/newsite/ ) . Good Luck !!</p>

Title: WP CSS problems / Url Problems


问:
Generating an Odd Random Number between a given Range
How to generate an odd Random number between a given range..

For Eg: For range between 1 to 6 ..
Random No is 3 or 1 or 5

Method for Generating Random No :

```<code>    Random_No = Min + (int)(Math.Random()*((Max-Min)+1))
</code>```

Refer How do I generate random integers within a specific range in Java?

Method For Generating Odd Random No :

```<code>    Random_No = Min + (int)(Math.Random()*((Max-Min)+1))
    if(Random_No%2 ==0)
    {
          if((Max%2)==0)&&Random_No==Max)
          {
              Random_No = Random_No - 1;
          }
          else{
              Random_No = Random_No +1;
          }
    }
</code>```

This Function will always convert 2 into 3 and not 1
Can we make this a more random function which can convert 2 sometimes into 3 and sometimes into 1 ??

答:
In Java 1.7 or later, I would use ThreadLocalRandom:

```<code>import java.util.concurrent.ThreadLocalRandom;

// Get odd random number within range [min, max]
// Start with an odd minimum and add random even number from the remaining range
public static int randOddInt(int min, int max) {
    if (min % 2 == 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}

// Get even random number within range [min, max]
// Start with an even minimum and add random even number from the remaining range
public static int randEvenInt(int min, int max) {
    if (min % 2 != 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}
</code>```

The reason to use ThreadLocalRandom is explained here. Also note that the reason we +1 to the input to ThreadLocalRandom.nextInt() is to make sure the max is included in the range.

Body:
How to generate an odd Random number between a given range..

For Eg: For range between 1 to 6 ..
Random No is 3 or 1 or 5

Method for Generating Random No :

    Random_No = Min + (int)(Math.Random()*((Max-Min)+1))

Refer How do I generate random integers within a specific range in Java?

Method For Generating Odd Random No :

    Random_No = Min + (int)(Math.Random()*((Max-Min)+1))
    if(Random_No%2 ==0)
    {
          if((Max%2)==0)&&Random_No==Max)
          {
              Random_No = Random_No - 1;
          }
          else{
              Random_No = Random_No +1;
          }
    }

This Function will always convert 2 into 3 and not 1
Can we make this a more random function which can convert 2 sometimes into 3 and sometimes into 1 ??

Body:
In Java 1.7 or later, I would use ThreadLocalRandom:

import java.util.concurrent.ThreadLocalRandom;

// Get odd random number within range [min, max]
// Start with an odd minimum and add random even number from the remaining range
public static int randOddInt(int min, int max) {
    if (min % 2 == 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}

// Get even random number within range [min, max]
// Start with an even minimum and add random even number from the remaining range
public static int randEvenInt(int min, int max) {
    if (min % 2 != 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}

The reason to use ThreadLocalRandom is explained here. Also note that the reason we +1 to the input to ThreadLocalRandom.nextInt() is to make sure the max is included in the range.


问:
access netezza database with python without driver from IBM
Is there a way to query a netezza database without explicitly installing its driver? I am using ubuntu 64 bit OS, our IT support says the driver they have only works on red hat systems.</p>

答:
You can use pyodbc.

pyodbc is an open source Python module that makes accessing ODBC
  databases simple. It implements the DB API 2.0 specification but is
  packed with even more Pythonic convenience.

On Ubuntu systems, all you need to do is run

```<code>sudo apt install unixodbc-dev
</code>```

before attempting

```<code>pip install pyodbc
</code>```

See more details from Installing pyodbc.

Body:
You can use pyodbc.

pyodbc is an open source Python module that makes accessing ODBC
  databases simple. It implements the DB API 2.0 specification but is
  packed with even more Pythonic convenience.

On Ubuntu systems, all you need to do is run

sudo apt install unixodbc-dev

before attempting

pip install pyodbc

See more details from Installing pyodbc.


问:
sed and awk: how to replace a section of file to another content?
File a.html:

```<code><!--TEMPLATE: banner-->
blahblah
<!--TEMPLATE-END: banner-->
</code>```

I want to replace the middle text to some other text, how to achieve that using sed/awk/other tools?

答:
If you have the new banner text in another file:</p>

```<code>awk -v new_file=new_banner.txt '
    /!--TEMPLATE:/ {print; system("cat " new_file); banner=1; next}
    /!--TEMPLATE-END:/ {banner=0}
    banner {next}
    {print}
' a.html
</code>```

ContentLicense: CC BY-SA 2.5

Body:
File a.html:

blahblah

I want to replace the middle text to some other text, how to achieve that using sed/awk/other tools?

Body:
If you have the new banner text in another file:

awk -v new_file=new_banner.txt '
    /!--TEMPLATE:/ {print; system("cat " new_file); banner=1; next}
    /!--TEMPLATE-END:/ {banner=0}
    banner {next}
    {print}
' a.html


问:
Serialise Java object to JSON using Static GSON object in Singleton class
I have a question regarding Singleton class behavior.

Scenario

We have webservices that is used by partners with request coming as frequently as 2-3 times in 1 second. So, they are heavily used services. We would like to store the request and response in JSON format.

As of now, in each webservice interface class, we have initiated Gson object and doing the serialization of java object to json.

Question

I was just thinking if I initiate Gson object once in Singleton class as static object and then refer it for all the request / response serialization of java object to Json, can it cause any issue/problem?

I mean, as there are multiple webservices and couple of them are heavily used by partners, so will single instance of GSON accessed in all the webservice can cause any delay or any other problem? If yes, apart than memory, what are the other benefits and issues with it?

答:
From javadoc of Gson:

This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple threads.

So it's ok to have only one Gson instance in your service and reuse it for each request/response. As an example you can consider to create a util class, something like the following class:

```<code>public abstract class GsonUtils {
    private static Gson gson = new Gson();

    static {
        // your extra init logic goes here
    }

    public static <T> T fromJson(String json, Class<T> classOfT) {
        return gson.fromJson(json, classOfT);
    }

    public static String toJson(Object object) {
        if (object == null) {
            return "";
        }
        return gson.toJson(object);
    }
}
</code>```

Or you can do it in your way :-)

Body:
From javadoc of Gson:

This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple threads.

So it's ok to have only one Gson instance in your service and reuse it for each request/response. As an example you can consider to create a util class, something like the following class:

public abstract class GsonUtils {
    private static Gson gson = new Gson();

    static {
        // your extra init logic goes here
    }

    public static <T> T fromJson(String json, Class<T> classOfT) {
        return gson.fromJson(json, classOfT);
    }

    public static String toJson(Object object) {
        if (object == null) {
            return "";
        }
        return gson.toJson(object);
    }
}

Or you can do it in your way :-)


问:
id showing undefined when trying to implement delete in angularjs
Trying to implement delete funtion in angularjs. The backend in asp.net is working fine. when i check with postman its working fine. now am trying to the front end for that. when i hit the delete button. its not getting the UId. its showing like this.

```<code>http://localhost:50802/api/User/BUser/[object%20Object]
</code>```

am totally new to angular. i dont know whether this angular code is correct or not.And another thing is i need to implement user confirmation popup window also. please help me...

angular controller.

```<code>$scope.DeleteUser = function (data, UId) {
        $http({
            method: "post",
            url: urls.api + 'User/BUser/' + UId,

            data: JSON.stringify(data)
        }).then(function (response) {
            alert(response.data);

        })
    };
</code>```

HTML

```<code> <tr ng-repeat="d in UserList">

                        <td>{{d.description}}</td>
                        <td>{{d.path}}</td>
                        <td><button ng-click="DeleteUser()">Delete </button></td>

                    </tr>
</code>```

here my Asp.net Controller

```<code>[HttpDelete]
        [Route("DeleteBanner/{UId}")]
        public async Task<IHttpActionResult> DeleteBanner(int UId)
        {
            int? result = await _service.DeleteBannerAsync(UId);

            return Ok();

        }
</code>```

答:
Try this, Change your tr to

```<code><tr ng-repeat="d in UserList">
  <td>{{d.description}}</td>
  <td>{{d.path}}</td>
  <td><button ng-click="DeleteUser(d, d.UId)">Delete </button></td>
</tr>
</code>```

Body:
Trying to implement delete funtion in angularjs. The backend in asp.net is working fine. when i check with postman its working fine. now am trying to the front end for that. when i hit the delete button. its not getting the UId. its showing like this.

http://localhost:50802/api/User/BUser/[object%20Object]

am totally new to angular. i dont know whether this angular code is correct or not.And another thing is i need to implement user confirmation popup window also. please help me...

angular controller.

$scope.DeleteUser = function (data, UId) {
        $http({
            method: "post",
            url: urls.api + 'User/BUser/' + UId,

            data: JSON.stringify(data)
        }).then(function (response) {
            alert(response.data);

        })
    };

HTML

                        {{d.description}}
                        {{d.path}}
                        <button ng-click="DeleteUser()">Delete </button>

here my Asp.net Controller

[HttpDelete]
        [Route("DeleteBanner/{UId}")]
        public async Task<IHttpActionResult> DeleteBanner(int UId)
        {
            int? result = await _service.DeleteBannerAsync(UId);

            return Ok();

        }

Body:
Try this, Change your tr to

<tr ng-repeat="d in UserList">
  <td>{{d.description}}</td>
  <td>{{d.path}}</td>
  <td><button ng-click="DeleteUser(d, d.UId)">Delete </button></td>
</tr>


问:
XmlDocument.Load finds illegal characters in my file path
I have a file with xml in it. The path contains a character "ñ" in it, but the full path was url encoded before being saved to the file, so this character is percent encoded along with a number of other characters in the path.

I try to load the file with the following code, and the Exists portion succeeds, but then the Load() call fails with a

System.ArgumentException: Illegal characters in path.

```<code>if (File.Exists(path))
{
    var xd = new XmlDocument();
    xd.Load(path);
}
</code>```

I have a bunch of these files with the url encoding being used, but it's only these accented characters that cause problems.

Any ideas?

答: It could possibly be that your file path is something in the format of: ...\User\Documents.... Try to add an extra '\' at each directory change. For example: ..\\User\\Documents.</p>

Body:
I have a file with xml in it. The path contains a character "ñ" in it, but the full path was url encoded before being saved to the file, so this character is percent encoded along with a number of other characters in the path.

I try to load the file with the following code, and the Exists portion succeeds, but then the Load() call fails with a

System.ArgumentException: Illegal characters in path.

if (File.Exists(path))
{
    var xd = new XmlDocument();
    xd.Load(path);
}

I have a bunch of these files with the url encoding being used, but it's only these accented characters that cause problems.

Any ideas?


问:
How to remove line breaks from a file in Java?
How can I replace all line breaks from a string in Java in such a way that will work on Windows and Linux (ie no OS specific problems of carriage return/line feed/new line etc.)?

I've tried (note readFileAsString is a function that reads a text file into a String):

```<code>String text = readFileAsString("textfile.txt");
text.replace("\n", "");
</code>```

but this doesn't seem to work.

How can this be done?

答:
You can use generic methods to replace any char with any char.</p>

```<code>public static void removeWithAnyChar(String str, char replceChar,
        char replaceWith) {
    char chrs[] = str.toCharArray();
    int i = 0;
    while (i < chrs.length) {

        if (chrs[i] == replceChar) {
            chrs[i] = replaceWith;
        }
        i++;
    }

}
</code>```

Body:
How can I replace all line breaks from a string in Java in such a way that will work on Windows and Linux (ie no OS specific problems of carriage return/line feed/new line etc.)?

I've tried (note readFileAsString is a function that reads a text file into a String):

String text = readFileAsString("textfile.txt");
text.replace("\n", "");

but this doesn't seem to work.

How can this be done?

Body:
You can use generic methods to replace any char with any char.

public static void removeWithAnyChar(String str, char replceChar,
        char replaceWith) {
    char chrs[] = str.toCharArray();
    int i = 0;
    while (i < chrs.length) {

        if (chrs[i] == replceChar) {
            chrs[i] = replaceWith;
        }
        i++;
    }

}


问:
Make post from graph api so it return following error : An active access token must be used to query information about the current user
I want to share post from graph api in python

```<code>import requests
import urllib

host = "https://graph.facebook.com"
path = "/oauth/access_token"
params = urllib.urlencode({"client_id":"XXXXXXX","client_secret": 'XXXXXXXXXXXXXXXXXXXXXXXXX','grant_type': 'client_credentials'})

url = "{host}{path}?{params}".format(host=host, path=path, params=params)

r = requests.get(url)
print "r",r

payload = {'grant_type': 'client_credentials', 'client_id': 'XXXXXXXXXXXXXXX', 'client_secret': 'XXXXXXXXXXXXXXXXXX'}
file = requests.post('https://graph.facebook.com/oauth/access_token?', params = payload)
result = file.text.split("=")[1]
print "result",result

param = {'client_id':'XXXXXXXXXXXX', 'access_token':result}
file_one = requests.post('https://graph.facebook.com/oauth/access_token_info?', params = param)
print "access token info file",file_one
print "access token info file.text",file_one.text

host = "https://graph.facebook.com"
path = "/me/feed"
params = urllib.urlencode({"message":"Hello, World.","access_token": file.text.split("=")[1]})
url = "{host}{path}?{params}".format(host=host, path=path, params=params)
r = requests.post(url)
print "value of r",r
print "r.text",r.text
</code>```

i get token but when i try to post in fb so it return error like

{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500,"fbtrace_id":"G3PcKSN1mFA"}}

in facebook three types of tokens 1)user token 2)app tokens 3)page token but i required usertoken from above script i get app token not user token can you please give solution fo how we get user token

答:
hi i found my solution from get app-access token and then convert them in to user access token this link is useful for me

Facebook Graph API: Have app access token, need user access token without interaction

Body:
I want to share post from graph api in python

import requests
import urllib

host = "https://graph.facebook.com"
path = "/oauth/access_token"
params = urllib.urlencode({"client_id":"XXXXXXX","client_secret": 'XXXXXXXXXXXXXXXXXXXXXXXXX','grant_type': 'client_credentials'})

url = "{host}{path}?{params}".format(host=host, path=path, params=params)

r = requests.get(url)
print "r",r

payload = {'grant_type': 'client_credentials', 'client_id': 'XXXXXXXXXXXXXXX', 'client_secret': 'XXXXXXXXXXXXXXXXXX'}
file = requests.post('https://graph.facebook.com/oauth/access_token?', params = payload)
result = file.text.split("=")[1]
print "result",result

param = {'client_id':'XXXXXXXXXXXX', 'access_token':result}
file_one = requests.post('https://graph.facebook.com/oauth/access_token_info?', params = param)
print "access token info file",file_one
print "access token info file.text",file_one.text

host = "https://graph.facebook.com"
path = "/me/feed"
params = urllib.urlencode({"message":"Hello, World.","access_token": file.text.split("=")[1]})
url = "{host}{path}?{params}".format(host=host, path=path, params=params)
r = requests.post(url)
print "value of r",r
print "r.text",r.text

i get token but when i try to post in fb so it return error like

{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500,"fbtrace_id":"G3PcKSN1mFA"}}

in facebook three types of tokens 1)user token 2)app tokens 3)page token but i required usertoken from above script i get app token not user token can you please give solution fo how we get user token


问:
Download multiple CSV files from a list in a single CSV (Python)
I have a 2 column CSV with download links in the first column and company symbols in the second column. For example:

http://data.com/data001.csv, BHP

http://data.com/data001.csv, TSA

I am trying to loop through the list so that Python opens each CSV via the download link and saves it separately as the company name. Therefore each file should be downloaded and saved as follows:

BHP.csv

TSA.csv

Below is the code I am using. It currently exports the entire CSV into a single row tabbed format, then loops back and does it again and again in an infinite loop.

```<code>import pandas as pd

data = pd.read_csv('download_links.csv', names=['download', 'symbol'])
file = pd.DataFrame()
cache = []

for d in data.download:
    df = pd.read_csv(d,index_col=None, header=0)
    cache.append(df)
    file = pd.DataFrame(cache)
    for s in data.symbol:
        file.to_csv(s+'.csv')

print("done")
</code>```

Up until I convert the list 'cache' into the DataFrame 'file' to export it, the data is formatted perfectly. It's only when it gets converted to a DataFrame when the trouble starts.

I'd love some help on this one as I've been stuck on it for a few hours.

答:
```<code>import pandas as pd
data = pd.read_csv('download_links.csv')
links = data.download
file_names = data.symbol
for link, file_name in zip(links,file_names):
    file = pd.read_csv(link).to_csv(file_name+'.csv', index=False)
</code>```

Body:
I have a 2 column CSV with download links in the first column and company symbols in the second column. For example:

http://data.com/data001.csv, BHP

http://data.com/data001.csv, TSA

I am trying to loop through the list so that Python opens each CSV via the download link and saves it separately as the company name. Therefore each file should be downloaded and saved as follows:

BHP.csv

TSA.csv

Below is the code I am using. It currently exports the entire CSV into a single row tabbed format, then loops back and does it again and again in an infinite loop.

import pandas as pd

data = pd.read_csv('download_links.csv', names=['download', 'symbol'])
file = pd.DataFrame()
cache = []

for d in data.download:
    df = pd.read_csv(d,index_col=None, header=0)
    cache.append(df)
    file = pd.DataFrame(cache)
    for s in data.symbol:
        file.to_csv(s+'.csv')

print("done")

Up until I convert the list 'cache' into the DataFrame 'file' to export it, the data is formatted perfectly. It's only when it gets converted to a DataFrame when the trouble starts.

I'd love some help on this one as I've been stuck on it for a few hours.


问:
In unity3d, How can i add a new class file to my project using visual studio?
In the visual studio in the project name i make right click then add then class.
The new created .cs file is:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace
{
    class CUBE
    {
    }
}
</code>```

First why it's not giving some namespace automatic ? I'm getting error. I can give my own namespace name but not sure why it's creating it like this.

I will want later to use this class in other cs file script i have.
I could also just a create a new script file in the editor but i wonder how to work with a class ? Or maybe i should just create a script file and working with it like a class ?

答:
according to my observation/understanding.

If you add any cs file directly in to visual studio(when using unity editory) it will create that file next to asset folder which is not correct. Every cs file that you want to utilized must be in asset folder.

And as you know, VS is a separate application so if you want to add a new class you should create it inside asset folder using the unity editor. And remember each script that inheriting from Mono Behaviour must match file and class name while for other classes(that are not inheriting from monobheviour-like in your case) you can change its file name but create it inside asset folder.

Body:
In the visual studio in the project name i make right click then add then class.
The new created .cs file is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace
{
    class CUBE
    {
    }
}

First why it's not giving some namespace automatic ? I'm getting error. I can give my own namespace name but not sure why it's creating it like this.

I will want later to use this class in other cs file script i have.
I could also just a create a new script file in the editor but i wonder how to work with a class ? Or maybe i should just create a script file and working with it like a class ?


问:
Print() vs Write() method of System.out
The Javadoc for PrintStream#print(char) states

Prints a character. The character is translated into one or more bytes
  according to the platform's default character encoding, and these
  bytes are written in exactly the manner of the write(int) method.

So this means that following code should print 2 'a' however prints one 'a' not two.

```<code>System.out.print('a');
System.out.write('a');
</code>```

Can some one help me understand this behaviour

答:
As per the java docs of PrintStream#write

Writes the specified byte to this stream. If the byte is a newline and
  automatic flushing is enabled then the flush method will be invoked.

So just call flush.

Call System.out.flush(); after System.out.write('a');.

Alternately,

As the docs suggest, set the output stream to autoflushable and then write a new line char at the end of your program. In fact the PrintStream object System.out is already set to autoflushable if you look at the source code System class. So really, all you need to do is just print a new line character in the end. No need to call flush.

```<code>System.out.print('a');
System.out.write('a');
System.out.write('\n');
</code>```

Title: Print() vs Write() method of System.out

Body:
The Javadoc for PrintStream#print(char) states

Prints a character. The character is translated into one or more bytes
  according to the platform's default character encoding, and these
  bytes are written in exactly the manner of the write(int) method.

So this means that following code should print 2 'a' however prints one 'a' not two.

System.out.print('a');
System.out.write('a');

Can some one help me understand this behaviour

Body:
As per the java docs of PrintStream#write

Writes the specified byte to this stream. If the byte is a newline and
  automatic flushing is enabled then the flush method will be invoked.

So just call flush.

Call System.out.flush(); after System.out.write('a');.

Alternately,

As the docs suggest, set the output stream to autoflushable and then write a new line char at the end of your program. In fact the PrintStream object System.out is already set to autoflushable if you look at the source code System class. So really, all you need to do is just print a new line character in the end. No need to call flush.

System.out.print('a');
System.out.write('a');
System.out.write('\n');


问:
Yii Framework 2.0 $model->validate always returns true
I'm new to the yii2 framework.I cant understand where i did the mistake.Below is my code.

```<code>public function rules()
    {
        return [
            // username and password are both required
            [['oldpassword', 'newpassword','reenternewpassword'], 'required'],
            // rememberMe must be a boolean value
            ['reenternewpassword', 'compare','compareAttribute'=>'newpassword'],
            // password is validated by validatePassword()
            ['oldpassword', 'validatePassword'],
        ];
    }

public function validatePassword()
    {

        $this->password_hash= User::findOne(['username'=>Yii::$app->user->identity->username,'status'=> User::STATUS_ACTIVE])->password_hash;
        if(is_null($this->oldpassword))
            return false;
        return Yii::$app->getSecurity()->validatePassword($this->oldpassword, $this->password_hash);
    }
</code>```

Model:

```<code>public function actionChangepwd()
{
if($model->load(Yii::$app->request->post()))
        {
            if($model->validate()){
             echo 'pwd correct';
            }
            else
            {
             echo 'pwd incorrect';
            }
        }
}
</code>```

Here validatePassword is returning false but model validate function is returning true.How?Please help me.

答:
Why dont you do this, as validatePassword() is the method which checks the values to be true or false, </p>

```<code>public function actionChangepwd()
{
if($model->load(Yii::$app->request->post()))
        {
            if($model->validatePassword()){
             echo 'pwd correct';
            }
            else
            {
             echo 'pwd incorrect';
            }
        }
}
</code>```

Body:
I'm new to the yii2 framework.I cant understand where i did the mistake.Below is my code.

public function rules()
    {
        return [
            // username and password are both required
            [['oldpassword', 'newpassword','reenternewpassword'], 'required'],
            // rememberMe must be a boolean value
            ['reenternewpassword', 'compare','compareAttribute'=>'newpassword'],
            // password is validated by validatePassword()
            ['oldpassword', 'validatePassword'],
        ];
    }

public function validatePassword()
    {

        $this->password_hash= User::findOne(['username'=>Yii::$app->user->identity->username,'status'=> User::STATUS_ACTIVE])->password_hash;
        if(is_null($this->oldpassword))
            return false;
        return Yii::$app->getSecurity()->validatePassword($this->oldpassword, $this->password_hash);
    }

Model:

public function actionChangepwd()
{
if($model->load(Yii::$app->request->post()))
        {
            if($model->validate()){
             echo 'pwd correct';
            }
            else
            {
             echo 'pwd incorrect';
            }
        }
}

Here validatePassword is returning false but model validate function is returning true.How?Please help me.

Body:
Why dont you do this, as validatePassword() is the method which checks the values to be true or false,

public function actionChangepwd()
{
if($model->load(Yii::$app->request->post()))
        {
            if($model->validatePassword()){
             echo 'pwd correct';
            }
            else
            {
             echo 'pwd incorrect';
            }
        }
}


问:
python: how to only output the integers in a list of both integers and floats
I have a problem. I was wondering if there was a way to only output the integers in a list of both integers and floats.

this is what I have written so far: (sory about how it's formatted)

```<code># Greet the user
print("Welcome to the Common Divisors Machine!")

# Initialize variable
confirm = 'yes'

# Start nested checking against variable to start or not
while confirm != ('n' or 'N' or 'no' or 'No'):
    x = int(input("Please enter the first number: "))

    # Validating the variable "x"
    while x <= 0:
        x = int(input("Error, please enter a positive, non-zero number: "))
    # Initializing for the first part of the FOR loop
    i = 1
    y = int(input("Please enter the second number: "))

    # Validating the variable "y"
    while y <= 0:
        y = int(input("Error, please enter a positive, non-zero number: "))
    # Initializing variable for the second part of the FOR loop
    h = 1
    print("The common divisors, excluding 1 and 2, are: ")
    # Starting the FOR loop
    # Setting the variable initialized earlier to be used against "x"
    for i in range (1, x - 1):
        # Nested the second part to run within the first part
        for h in range (1, y - 1):
            # Dividing the user input
            a = x / i
            b = y / h

            # Nesting a WHILE loop to run within both of the FOR loops
            # to print the output of both
            # Also checking whether the answers are the same
            while a == b and a != 1 and a != 2:
                # Printing the output
                print(b)
                # Re initializing "a" so that it will loop back to the top
                a = 0

    # Checking whether or not the user would like to check for more divisors
    confirm = input("Would you like to continue(y/n)? ")
 # Exiting comment
print("Thank you for using the Common Divisors Machine!")
</code>```

Is this even possible?

here is a sample output for those who were asking:

```<code>Welcome to the Common Diviors Machine!
Please enter the first number: 150
Please enter the second number: 300
The common divisors, excluding 1 and 2, are:
150.0
75.0
50.0
37.5
30.0
25.0
21.428571428571427
18.75
16.666666666666668
15.0
13.636363636363637
12.5
11.538461538461538
10.714285714285714
10.0
9.375
8.823529411764707
8.333333333333334
7.894736842105263
7.5
7.142857142857143
6.818181818181818
6.521739130434782
6.25
6.0
5.769230769230769
5.555555555555555
5.357142857142857
5.172413793103448
5.0
4.838709677419355
4.6875
4.545454545454546
4.411764705882353
4.285714285714286
4.166666666666667
4.054054054054054
3.9473684210526314
3.8461538461538463
3.75
3.658536585365854
3.5714285714285716
3.488372093023256
3.409090909090909
3.3333333333333335
3.260869565217391
3.1914893617021276
3.125
3.061224489795918
3.0
Would you like to continue(y/n)?
</code>```

I do not want it to display the long decimals, only the whole numbers

答:
I think what you are trying to ask is, "How do I determine if one number is evenly divisible by another?"

The answer to that question is the modulo operator: %

The modulo operation basically returns the integer remainder after division of two numbers. So the result of 6 % 5 will be 1, 7 % 5 will be 2, etc.

You can check if a % b == 0 in order to determine that yes, a is divisible by b.

Body:
I have a problem. I was wondering if there was a way to only output the integers in a list of both integers and floats.

this is what I have written so far: (sory about how it's formatted)

# Greet the user
print("Welcome to the Common Divisors Machine!")

# Initialize variable
confirm = 'yes'

# Start nested checking against variable to start or not
while confirm != ('n' or 'N' or 'no' or 'No'):
    x = int(input("Please enter the first number: "))

    # Validating the variable "x"
    while x <= 0:
        x = int(input("Error, please enter a positive, non-zero number: "))
    # Initializing for the first part of the FOR loop
    i = 1
    y = int(input("Please enter the second number: "))

    # Validating the variable "y"
    while y <= 0:
        y = int(input("Error, please enter a positive, non-zero number: "))
    # Initializing variable for the second part of the FOR loop
    h = 1
    print("The common divisors, excluding 1 and 2, are: ")
    # Starting the FOR loop
    # Setting the variable initialized earlier to be used against "x"
    for i in range (1, x - 1):
        # Nested the second part to run within the first part
        for h in range (1, y - 1):
            # Dividing the user input
            a = x / i
            b = y / h

            # Nesting a WHILE loop to run within both of the FOR loops
            # to print the output of both
            # Also checking whether the answers are the same
            while a == b and a != 1 and a != 2:
                # Printing the output
                print(b)
                # Re initializing "a" so that it will loop back to the top
                a = 0

    # Checking whether or not the user would like to check for more divisors
    confirm = input("Would you like to continue(y/n)? ")
 # Exiting comment
print("Thank you for using the Common Divisors Machine!")

Is this even possible?

here is a sample output for those who were asking:

Welcome to the Common Diviors Machine!
Please enter the first number: 150
Please enter the second number: 300
The common divisors, excluding 1 and 2, are:
150.0
75.0
50.0
37.5
30.0
25.0
21.428571428571427
18.75
16.666666666666668
15.0
13.636363636363637
12.5
11.538461538461538
10.714285714285714
10.0
9.375
8.823529411764707
8.333333333333334
7.894736842105263
7.5
7.142857142857143
6.818181818181818
6.521739130434782
6.25
6.0
5.769230769230769
5.555555555555555
5.357142857142857
5.172413793103448
5.0
4.838709677419355
4.6875
4.545454545454546
4.411764705882353
4.285714285714286
4.166666666666667
4.054054054054054
3.9473684210526314
3.8461538461538463
3.75
3.658536585365854
3.5714285714285716
3.488372093023256
3.409090909090909
3.3333333333333335
3.260869565217391
3.1914893617021276
3.125
3.061224489795918
3.0
Would you like to continue(y/n)?

I do not want it to display the long decimals, only the whole numbers


问:
How do I identify language of a text document in Java?
Is there an existing Java library that could tell me whether a String contains English language text or not (e.g. I need to be able to distinguish French or Italian text -- the function needs to return false for French and Italian, and true for English)?</p>

答:
There are various techniques, and a robust method would combine various ones:

look at the frequencies of groups of n letters (say, groups of 3 letters or trigrams) in your text and see if they are similar to the frequencies found for the language you are testing against

look at whether the instances of frequent words in the given language match the freuencies found in your text (this tends to work better for longer texts)

does the text contain characters which strongly narrow it down to a particular language? (e.g. if the text contains an upside down question mark there's a good chance it's Spanish)

can you "loosely parse" certain features in the text that would indicate a particular language, e.g. if it contains a match to the following regular expression, you could take this as a strong clue that the language is French:

\bvous\s+\p{L}+ez\b

To get you started, here are frequent trigram and word counts for English, French and Italian (copied and pasted from some code-- I'll leave it as an exercise to parse them):

```<code>  Locale.ENGLISH,
      "he_=38426;the=38122;nd_=20901;ed_=20519;and=18417;ing=16248;to_=15295;ng_=15281;er_=15192;at_=14219",
      "the=11209;and=6631;to=5763;of=5561;a=5487;in=3421;was=3214;his=2313;that=2311;he=2115",
  Locale.FRENCH,
      "es_=38676;de_=28820;ent=21451;nt_=21072;e_d=18764;le_=17051;ion=15803;s_d=15491;e_l=14888;la_=14260",
      "de=10726;la=5581;le=3954;" + ((char)224) + "=3930;et=3563;des=3295;les=3277;du=2667;en=2505;un=1588",
  Locale.ITALIAN,
      "re_=7275;la_=7251;to_=7208;_di=7170;_e_=7031;_co=5919;che=5876;he_=5622;no_=5546;di_=5460",
      "di=7014;e=4045;il=3313;che=3006;la=2943;a=2541;in=2434;per=2165;del=2013;un=1945",
</code>```

(Trigram counts are per million characters; word counts are per million words. The '_' character represents a word boundary.)

As I recall, the figures are cited in the Oxford Handbook of Computational Linguists and are based on a sample of newspaper articles. If you have a corpus of text in these languages, it's easy enough to derive similar figures yourself.

If you want a really quick-and-dirty way of applying the above, try:

consider each sequence of three characters in your text (replacing word boundaries with '_')

for each trigram that matches one of the frequent ones for the given language, increment that language's "score" by 1 (more sophisticatedly, you could weight according to the position in the list)

at the end, assume the language is that with the highest score

optionally, do the same for the common words (combine scores)

Obviously, this can then be refined, but you might find that this simple solution is good enough for what you want, since you're essentially interested in "English or not".

OwnerDisplayName: anonymous coward

LastEditorDisplayName: Neil Coffey

Body:
There are various techniques, and a robust method would combine various ones:

look at the frequencies of groups of n letters (say, groups of 3 letters or trigrams) in your text and see if they are similar to the frequencies found for the language you are testing against

look at whether the instances of frequent words in the given language match the freuencies found in your text (this tends to work better for longer texts)

does the text contain characters which strongly narrow it down to a particular language? (e.g. if the text contains an upside down question mark there's a good chance it's Spanish)

can you "loosely parse" certain features in the text that would indicate a particular language, e.g. if it contains a match to the following regular expression, you could take this as a strong clue that the language is French:

\bvous\s+\p{L}+ez\b

To get you started, here are frequent trigram and word counts for English, French and Italian (copied and pasted from some code-- I'll leave it as an exercise to parse them):

  Locale.ENGLISH,
      "he_=38426;the=38122;nd_=20901;ed_=20519;and=18417;ing=16248;to_=15295;ng_=15281;er_=15192;at_=14219",
      "the=11209;and=6631;to=5763;of=5561;a=5487;in=3421;was=3214;his=2313;that=2311;he=2115",
  Locale.FRENCH,
      "es_=38676;de_=28820;ent=21451;nt_=21072;e_d=18764;le_=17051;ion=15803;s_d=15491;e_l=14888;la_=14260",
      "de=10726;la=5581;le=3954;" + ((char)224) + "=3930;et=3563;des=3295;les=3277;du=2667;en=2505;un=1588",
  Locale.ITALIAN,
      "re_=7275;la_=7251;to_=7208;_di=7170;_e_=7031;_co=5919;che=5876;he_=5622;no_=5546;di_=5460",
      "di=7014;e=4045;il=3313;che=3006;la=2943;a=2541;in=2434;per=2165;del=2013;un=1945",

(Trigram counts are per million characters; word counts are per million words. The '_' character represents a word boundary.)

As I recall, the figures are cited in the Oxford Handbook of Computational Linguists and are based on a sample of newspaper articles. If you have a corpus of text in these languages, it's easy enough to derive similar figures yourself.

If you want a really quick-and-dirty way of applying the above, try:

consider each sequence of three characters in your text (replacing word boundaries with '_')

for each trigram that matches one of the frequent ones for the given language, increment that language's "score" by 1 (more sophisticatedly, you could weight according to the position in the list)

at the end, assume the language is that with the highest score

optionally, do the same for the common words (combine scores)

Obviously, this can then be refined, but you might find that this simple solution is good enough for what you want, since you're essentially interested in "English or not".

OwnerDisplayName: Neil Coffey


问:
Revenue in Google Analytics not appearing correctly
I've just finished tagging a website, and currently submitting test data.

On one page we fire an Ecommerce purchase event, which consists off the transaction information / product information.

The transaction object is populated by retrieving values off the page i.e from html labels this is all working as expected, however when we check Google Analytics > All Web Site Data it seems GA is formatting the number and removing trailing zeros for some strange reason, please see an example:

This doesn't happen to all purchase events, as you can see at the top of the table there is an entry for $1,793.04 and this has been displayed correctly.

In regards to populating the transaction object, we aren't doing any formatting what so ever we simply reference the html label value and pass that, so I'm unsure into how this could be happening.  Has anyone experienced this before?

答:
Personally I have not found this anywhere else documented but just to be sure you can conform with the formatting expected by the Measurement Protocol. Meaning the http request that will be ultimately sent to GA servers to process your values. The transactionRevenue and most monetary values in analytics.js are of type CURRENCY and you can find the documentation of these data type in the parameter reference. And from the link I quote

A decimal point is used as a delimiter between the whole and
fractional portion of the currency.

So the thing that I would advise you to do is use some js function to format your string values. Remove the comma and then use the (.) as a separator for whole and fractional point.


答: Recently I was dealing with same idea. There is older thread related to this Is it OK to use Gson instance as a static field in a model bean (reuse)?. Simply summarised the GSON instance should be thread safe.</p>

Title: Serialise Java object to JSON using Static GSON object in Singleton class

Body:
I have a question regarding Singleton class behavior.

Scenario

We have webservices that is used by partners with request coming as frequently as 2-3 times in 1 second. So, they are heavily used services. We would like to store the request and response in JSON format.

As of now, in each webservice interface class, we have initiated Gson object and doing the serialization of java object to json.

Question

I was just thinking if I initiate Gson object once in Singleton class as static object and then refer it for all the request / response serialization of java object to Json, can it cause any issue/problem?

I mean, as there are multiple webservices and couple of them are heavily used by partners, so will single instance of GSON accessed in all the webservice can cause any delay or any other problem? If yes, apart than memory, what are the other benefits and issues with it?


问:
Firebase messaging on android and permissions
I recently added firebase messaging to my android app and I noticed some new permissions required to my app at similar time, for example:
android.permission.READ_PHONE_STATE
I couldn't find anywhere in documentation, why is this permission required. I even tried to explicitly disable it in manifest (tools:node="remove") and messaging still works for me. It's kinda messy and I want to use only as few permissions as I need for sake of my users.

Is this permissions really needed by messaging or is it added automatically from one of library dependencies?
How can I tell what permissions is being added by what? I tried manifest-merger-report.txt, but there was no mention about READ_PHONE_STATE.

Thanks!

答: Ok this is embarrassing. I in the end, I was adding permissions myself in parent manifest. Thank you for your comments, based on those I managed to track it down.</p>


问:
PL/SQL Function_get total balance has errors
I was trying to create a function that given a customer name, get the total balance of that customer's accounts from the account table(A#, CNAME, BAL).

When compiling in command, I got errors:

line "SELECT SUM(bal) INTO total_a_bal FROM account" ignored

and               line "WHERE account.cname = v_acname" SQL cmd not properly ended.

Please help correct the errors. Any help would be greatly appreciated!

My function is :

```<code>CREATE OR REPLACE FUNCTION totbal
    (v_acname IN account.cname%type)
RETURN NUMBER
IS
    total_a_bal NUMBER;
BEGIN
    SELECT SUM(bal) INTO total_a_bal FROM account
    group by account.cname
    WHERE account.cname = v_acname;
    RETURN total_a_bal;
END;
/
</code>```

答:
This may not be the only problem with your function, but the WHERE clause always precedes the GROUP BY clause in a SQL query.  Hence, your function should look like this:

```<code>CREATE OR REPLACE FUNCTION totbal
    (v_acname IN varchar2)     -- a type should follow IN, e.g. varchar2
RETURN NUMBER
IS
    total_a_bal NUMBER;
BEGIN
    SELECT SUM(bal) INTO total_a_bal
    FROM account
    WHERE account.cname = v_acname;    -- WHERE always precedes GROUP BY
    GROUP BY account.cname
RETURN total_a_bal;
END;
</code>```

Body:
I was trying to create a function that given a customer name, get the total balance of that customer's accounts from the account table(A#, CNAME, BAL).

When compiling in command, I got errors:

line "SELECT SUM(bal) INTO total_a_bal FROM account" ignored

and               line "WHERE account.cname = v_acname" SQL cmd not properly ended.

Please help correct the errors. Any help would be greatly appreciated!

My function is :

CREATE OR REPLACE FUNCTION totbal
    (v_acname IN account.cname%type)
RETURN NUMBER
IS
    total_a_bal NUMBER;
BEGIN
    SELECT SUM(bal) INTO total_a_bal FROM account
    group by account.cname
    WHERE account.cname = v_acname;
    RETURN total_a_bal;
END;
/

Body:
This may not be the only problem with your function, but the WHERE clause always precedes the GROUP BY clause in a SQL query.  Hence, your function should look like this:

CREATE OR REPLACE FUNCTION totbal
    (v_acname IN varchar2)     -- a type should follow IN, e.g. varchar2
RETURN NUMBER
IS
    total_a_bal NUMBER;
BEGIN
    SELECT SUM(bal) INTO total_a_bal
    FROM account
    WHERE account.cname = v_acname;    -- WHERE always precedes GROUP BY
    GROUP BY account.cname
RETURN total_a_bal;
END;


问:
Cannot attach debugger to w3wp
I'm debugging an ASP.NET application but sometimes cannot find w3wp neither in Visual Studio process list (Menu: Debug -> Attach to Process...) nor in task manager. I have selected 'Show processes from all users' and 'Show processes in all sessions' check boxes. When run the project from localhost, after an unhanded exception happens debugger would attach to w3wp (too late for me to step into code) !

Why I cannot see w3wp sometimes ?

```<code>Windows Server 2008 Enterprise Edition 64-bit, Visual Studio 2010
</code>```

答: When you reset IIS or IIS is not running, you need to make a call to the server, when you hit the server for the first time the w3wp process starts.

Title: Cannot attach debugger to w3wp

Body:
I'm debugging an ASP.NET application but sometimes cannot find w3wp neither in Visual Studio process list (Menu: Debug -> Attach to Process...) nor in task manager. I have selected 'Show processes from all users' and 'Show processes in all sessions' check boxes. When run the project from localhost, after an unhanded exception happens debugger would attach to w3wp (too late for me to step into code) !

Why I cannot see w3wp sometimes ?

Windows Server 2008 Enterprise Edition 64-bit, Visual Studio 2010


问:
regex how to read all the characters between the two braces
I am reading log file and have to extract all the values in a line which is like below

```<code>>    DE-055  LLL[136]
> CHR(_*.....\............B........(............................................12345678.&..g..2%.$.'...3.`(..4.....5.!.6....7.s$...A......S..)
</code>```

I am trying to use regex to extract the data between the two braces (). Please advise how can I extract so far, I have tried different methods but not able to do so

```<code>for (String s : incomingmessage) {
    // **DE-011  FXD[006]  CHR(008432)**
    pattern3 working
    String pattern3 = "(DE\\W\\d*)(\\s*\\w*\\W*)(\\d*)(\\W*\\s*)  (\\w*)(\\()([\\w*\\s*]+)(\\))"; --> works when the value is like above,same code do not work for the below format

    //DE-055  LLL[136]  CHR(_*.....\............B........(............................................12345678.&..g..2%.$.'...3.`(..4.....5.!.6....7.s$...A......S..)

    String pattern3 = "(DE\\W\\d*)(\\s*\\w*\\W*)(\\d*)(\\W*\\s*)(\\w*)(\\([.*?]\\))"; --> tried many times changing not able to get the regex which will work to get the values between the two braces even if it is some funny characters like the above

    Pattern p3 = Pattern.compile(pattern3);
    // Matcher m1 = p1.matcher(s);
    //Matcher m2 = p2.matcher(s);
    Matcher m3 = p3.matcher(s);

    while (m3.find()) {
        String fullvalue = m3.group(0);
        // String field = m3.group(1);
        //String length = m3.group(3);
        //String value = m3.group(7);
        System.out.println("m3.find() full value " + fullvalue);
        //System.out.println("m3.find() filed value " + field + "length " + length + "value" + value);
    }
}
</code>```

I want the output value as below which is between the two braces ()

```<code>_*.....\............B........(............................................12345678.&..g..2%.$.'...3.`(..4.....5.!.6....7.s$...A......S..
</code>```

Body:
I am reading log file and have to extract all the values in a line which is like below

>    DE-055  LLL[136]
> CHR(_*.....\............B........(............................................12345678.&..g..2%.$.'...3.`(..4.....5.!.6....7.s$...A......S..)

I am trying to use regex to extract the data between the two braces (). Please advise how can I extract so far, I have tried different methods but not able to do so

for (String s : incomingmessage) {
    // **DE-011  FXD[006]  CHR(008432)**
    pattern3 working
    String pattern3 = "(DE\\W\\d*)(\\s*\\w*\\W*)(\\d*)(\\W*\\s*)  (\\w*)(\\()([\\w*\\s*]+)(\\))"; --> works when the value is like above,same code do not work for the below format

    //DE-055  LLL[136]  CHR(_*.....\............B........(............................................12345678.&..g..2%.$.'...3.`(..4.....5.!.6....7.s$...A......S..)

    String pattern3 = "(DE\\W\\d*)(\\s*\\w*\\W*)(\\d*)(\\W*\\s*)(\\w*)(\\([.*?]\\))"; --> tried many times changing not able to get the regex which will work to get the values between the two braces even if it is some funny characters like the above

    Pattern p3 = Pattern.compile(pattern3);
    // Matcher m1 = p1.matcher(s);
    //Matcher m2 = p2.matcher(s);
    Matcher m3 = p3.matcher(s);

    while (m3.find()) {
        String fullvalue = m3.group(0);
        // String field = m3.group(1);
        //String length = m3.group(3);
        //String value = m3.group(7);
        System.out.println("m3.find() full value " + fullvalue);
        //System.out.println("m3.find() filed value " + field + "length " + length + "value" + value);
    }
}

I want the output value as below which is between the two braces ()

_*.....\............B........(............................................12345678.&..g..2%.$.'...3.`(..4.....5.!.6....7.s$...A......S..

Body:
 String t = "DE-055  LLL[136]  CHR(_*.....\\............B........(............................................12345678.&..g..2%.$.'...3.`(..4.....5.!.6....7.s$...A......S..)";

String pattern3 = "(DE\\W\\d*)(\\s*\\w*\\W*)(\\d*)(\\W*\\s*)(\\w*)(\\()([\\W*?\\w*?\\s*?\\W*?]+)(\\))";

Output :

group 0 :   DE-055  LLL[136]  CHR(_*.....\............B........(............................................12345678.&..g..2%.$.'...3.`(..4.....5.!.6....7.s$...A......S..)
group 1 ;   DE-055
group 2 :     LLL[
group 3 :   136
group 4 :   ]
group 5 :   CHR
group 6 :   (
group 7 :   _*.....\............B........(............................................12345678.&..g..2%.$.'...3.`(..4.....5.!.6....7.s$...A......S..
group 8 :   )

The group 7 gives the output which I look for.
Thanks everyone who try to help me.


问:
g++ crashed when I tried to compile a program with ONE LINE
My program is this:

```<code>#include <iostream>
</code>```

That's it. That's the entire program, just one line.

I tried to compile it with this:

```<code>g++ CVB--OpenPic--00.cpp -o cv
</code>```

and I got this:

```<code>/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 4 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 5 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 6 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 7 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 8 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 10 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 11 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 12 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 21
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_line): relocation 0 has invalid symbol index 2
/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
</code>```

I've compiled dozens of other .cpp files over the past few weeks, and many, many other programs. What exactly is happening here?

答:
You haven't defined main() function in your program.

As said in error:

```<code>(.text+0x20): undefined reference to `main'
</code>```

PS:

This is not crash of g++, it just shows error message when can't find definition of main().

Body:
My program is this:

#include <iostream>

That's it. That's the entire program, just one line.

I tried to compile it with this:

g++ CVB--OpenPic--00.cpp -o cv

and I got this:

/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 4 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 5 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 6 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 7 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 8 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 10 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 11 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 12 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 21
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_line): relocation 0 has invalid symbol index 2
/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status

I've compiled dozens of other .cpp files over the past few weeks, and many, many other programs. What exactly is happening here?

Body:
You haven't defined main() function in your program.

As said in error:

(.text+0x20): undefined reference to `main'

PS:

This is not crash of g++, it just shows error message when can't find definition of main().


问:
Loop through leaflet FeatureGroup
I have a map with 3 geoJson layers representing school district boundaries. The functionality I need is simple: click the map, get a popup with the school names for each level (elementary, middle, and high school.) [eLayer,mLayer,hLayer]

Here's my feature group:

```<code>var fGroup = new L.featureGroup([eLayer,mLayer,hLayer]).addTo(map);
</code>```

I figured I could use the eachLayer method with a click event to get the school name for each polygon at that location. The code below gets me close.

```<code>fGroup.on('click',function(e){
    fGroup.eachLayer(function(layer){
        alert(e.layer.feature.properties.School);
    });
});
</code>```

I only get the name of the last added geoJson layer, which in this case is the high school. I'm a novice programmer, but I researched this for days now and I found one example that sort of had a suggestion, but their solution didn't actually work.

Just to be perfectly clear, I want my output to be like below.

```<code>___________________________
|                         |
|Lincoln Elementary School|
|Tubman Middle School     |
|Frederick High School    |
|_________________________|
</code>```

答:
e.layer will get you only the exactly clicked layer / feature, the click does not "propagate" to layers underneath, even though they may cover that exact location as well. That is why you get the most recently added group data only (i.e. High School).

Furthermore, you arer looping on each layer of fGroup, but do not do anything specific with each child layer, which are actually your 3 GeoJSON layer gorups. So you would get 3 alerts with the same message.

Instead, you should simply get the clicked position (e.latlng) and loop through each individual layer / feature to determine if this layer contains that position.

See Leaflet event how to propagate to overlapping layers

Title: Loop through leaflet FeatureGroup

Body:
I have a map with 3 geoJson layers representing school district boundaries. The functionality I need is simple: click the map, get a popup with the school names for each level (elementary, middle, and high school.) [eLayer,mLayer,hLayer]

Here's my feature group:

var fGroup = new L.featureGroup([eLayer,mLayer,hLayer]).addTo(map);

I figured I could use the eachLayer method with a click event to get the school name for each polygon at that location. The code below gets me close.

fGroup.on('click',function(e){
    fGroup.eachLayer(function(layer){
        alert(e.layer.feature.properties.School);
    });
});

I only get the name of the last added geoJson layer, which in this case is the high school. I'm a novice programmer, but I researched this for days now and I found one example that sort of had a suggestion, but their solution didn't actually work.

Just to be perfectly clear, I want my output to be like below.

___________________________
|                         |
|Lincoln Elementary School|
|Tubman Middle School     |
|Frederick High School    |
|_________________________|


问:
Big quantity of data with MySql
i have a question about Mass storage. Actually, i'm working with 5 sensors which sends a lot of datas with a different frequency for each one and i'm using MySQL DATABASE.

so here is my questions:

1) is MySQL the perfect solution.
2) if not, is there a solution to store this big quantity of data in a data base?
3) I'm using Threads in this and i'm using mutexs also, i'm afraid if this can cause problems, Actually,it seems to be.

i hope i will have an answer to this question.

答:
There are several Questions that discuss "lots of data" and [mysql].  They generally say "yes, but it depends on what you will do with it".

Some general statements (YMMV):

a million rows -- no problem.

a billion rows or a terabyte of data -- You will run into problems, but they are no insurmountable.

100 inserts per second on spinning disk -- probably no problem

1000 rows/second inserted can be done; troubles are surmountable

creating "reports" from huge tables is problematical until you employ Summary Tables.

Two threads storing into the same table at the "same" time?  Every RDBMS (MySQL included) solves that problem before the first release.  The Mutexes (or whatever) are built into the code; you don't have to worry.

"Real time" -- If you are inserting 100 sensor values per second and comparing each value to one other value:  No problem.  Comparing to a million other values: big problem with any system.

"5 sensors" -- Read each hour?  Yawn.  Each minute?  Yawn.  Each second?  Probably still Yawn.  We need more concrete numbers to help you!

Title: Big quantity of data with MySql


问:
python: is there a disadvantage to from package import * besides namespace collision
I'm creating a class to extend a package, and prior to class instantiation I don't know which subset of the package's namespace I need.  I've been careful about avoiding namespace conflicts in my code, so, does

```<code>from package import *
</code>```

create problems besides name conflicts?

Is it better to examine the class's input and import only the names I need (at runtime) in the __init__ ??

Can python import from a set [] ?

does

```<code>for name in [namespace,namespace]:
    from package import name
</code>```

make any sense?

I hope this question doesn't seem like unnecessary hand-ringing, i'm just super new to python and don't want to do the one thing every 'beginnger's guide' says not to do (from pkg import * ) unless I'm sure there's no alternative.

thoughts, advice welcome.

答:
In order:

It does not create other problems - however, name conflicts can be much more of a problem than you'd expect.

Definitely defer your imports if you can. Even though Python variable scoping is simplistic, you also gain the benefit of not having to import the module if the functionality that needs it never gets called.

I don't know what you mean. Square brackets are used to make lists, not sets. You can import multiple names from a module in one line - just use a comma-delimited list:

```<code>from awesome_module import spam, ham, eggs, baked_beans
# awesome_module defines lots of other names, but they aren't pulled in.
</code>```

No, that won't do what you want - name is an identifier, and as such, each time through the loop the code will attempt to import the name name, and not the name that corresponds to the string referred to by the name variable.

However, you can get this kind of "dynamic import" effect, using the __import__ function. Consult the documentation for more information, and make sure you have a real reason for using it first. We get into some pretty advanced uses of the language here pretty quickly, and it usually isn't as necessary as it first appears. Don't get too clever. We hates them tricksy hobbitses.

Body:
I'm creating a class to extend a package, and prior to class instantiation I don't know which subset of the package's namespace I need.  I've been careful about avoiding namespace conflicts in my code, so, does

from package import *

create problems besides name conflicts?

Is it better to examine the class's input and import only the names I need (at runtime) in the __init__ ??

Can python import from a set [] ?

does

for name in [namespace,namespace]:
    from package import name

make any sense?

I hope this question doesn't seem like unnecessary hand-ringing, i'm just super new to python and don't want to do the one thing every 'beginnger's guide' says not to do (from pkg import * ) unless I'm sure there's no alternative.

thoughts, advice welcome.

Body:
In order:

It does not create other problems - however, name conflicts can be much more of a problem than you'd expect.

Definitely defer your imports if you can. Even though Python variable scoping is simplistic, you also gain the benefit of not having to import the module if the functionality that needs it never gets called.

I don't know what you mean. Square brackets are used to make lists, not sets. You can import multiple names from a module in one line - just use a comma-delimited list:

from awesome_module import spam, ham, eggs, baked_beans
# awesome_module defines lots of other names, but they aren't pulled in.

No, that won't do what you want - name is an identifier, and as such, each time through the loop the code will attempt to import the name name, and not the name that corresponds to the string referred to by the name variable.

However, you can get this kind of "dynamic import" effect, using the __import__ function. Consult the documentation for more information, and make sure you have a real reason for using it first. We get into some pretty advanced uses of the language here pretty quickly, and it usually isn't as necessary as it first appears. Don't get too clever. We hates them tricksy hobbitses.


问:
How do "flux" and "redux" relate to "react native" and which of these should a new "react native" start using?
How do "flux" and "redux" and "relay" relate to "react native" and which of these (flux and/or redux and/or relay) do most "react native" developers use.  </p>

<p>Background: For someone starting up with "react native" which of these (i.e. flux, redux, relay) should they start aiming to utilise from day 1?  </p>

答:
All three of them handles the state of your application they only differ on the complexity of setting them up. Relay is more complex I think, compare to flux and redux and when using relay you should be well aware of how GraphQL works.

You actually don't need to use any of this if your application is small. I would suggest getting your self comfortable with handling states on your component, then proceed on using one of this tools. (I personally use redux) setting up is cumbersome for new users but it pays off. I would also suggest checking out Mobx.

Body:
How do "flux" and "redux" and "relay" relate to "react native" and which of these (flux and/or redux and/or relay) do most "react native" developers use.

Background: For someone starting up with "react native" which of these (i.e. flux, redux, relay) should they start aiming to utilise from day 1?


问:
Convert a dictionary of lists into a list of dictionaries
I have the following Dictionary Object:

```<code>Input = {'userName': ['psrr_api@auto-grid.com', 'ps_api1@auto-grid.com'],
         'password': ['Everseeource2016!', 'Eversource2016!']}
</code>```

Which will then result in this specific output:

```<code>output = [{'UserName':'ps_api@auto-grid.com','password': 'Eversource2016!'},
          {'userName':'ps_api1@auto-grid.com','password':'Eversource2016!'}]
</code>```

I'm not sure how I would approach this problem and any help would be appreciated.

答:
Use a zip to iterate over two lists as the same time. Use a dict constructor to create individual dictionaries, inside a list comprehension to handle automatically looping.

```<code>Input = {'userName': ['psrr_api@auto-grid.com', 'ps_api1@auto-grid.com'], 'password': ['Everseeource2016!', 'Eversource2016!']}

Output = [ {'UserName':u, 'password':p} for u,p in zip(Input['userName'], Input['password']) ]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following Dictionary Object:

Input = {'userName': ['psrr_api@auto-grid.com', 'ps_api1@auto-grid.com'],
         'password': ['Everseeource2016!', 'Eversource2016!']}

Which will then result in this specific output:

output = [{'UserName':'ps_api@auto-grid.com','password': 'Eversource2016!'},
          {'userName':'ps_api1@auto-grid.com','password':'Eversource2016!'}]

I'm not sure how I would approach this problem and any help would be appreciated.

Body:
Use a zip to iterate over two lists as the same time. Use a dict constructor to create individual dictionaries, inside a list comprehension to handle automatically looping.

Input = {'userName': ['psrr_api@auto-grid.com', 'ps_api1@auto-grid.com'], 'password': ['Everseeource2016!', 'Eversource2016!']}

Output = [ {'UserName':u, 'password':p} for u,p in zip(Input['userName'], Input['password']) ]


问:
Vim: Replacing a line with another one yanked before
At least once per day i have the following situation:

```<code>A: This line should also replace line X
...
X: This is line should be replaced
</code>```

I believe that I don't perform that task efficiently.

What I do:

Go to line A: AG (replace A with the line number)

Yank line A: yy

Go to line X: XG (replace X with the line number)

Paste line A: P

Move to old line: j

Delete old line: dd

This has the additional disadvantage that line X is now in the default register, which is annoying if I find another line that should be replaced with A. Yanking to and pasting from an additional register ("ayy, "aP) makes this simple task even less efficient.

My Questions:

Did I miss a built-in Vim command to replace a line yanked before?

If not, how can I bind my own command that leaves (or restores) the yanked line in the default register?

答:
Building on the answers that suggest using Vp or VP to paste over a line -- to avoid changing the contents of the yank register I find the most ergonomic command is simply:

VPY

Body:
At least once per day i have the following situation:

A: This line should also replace line X
...
X: This is line should be replaced

I believe that I don't perform that task efficiently.

What I do:

Go to line A: AG (replace A with the line number)

Yank line A: yy

Go to line X: XG (replace X with the line number)

Paste line A: P

Move to old line: j

Delete old line: dd

This has the additional disadvantage that line X is now in the default register, which is annoying if I find another line that should be replaced with A. Yanking to and pasting from an additional register ("ayy, "aP) makes this simple task even less efficient.

My Questions:

Did I miss a built-in Vim command to replace a line yanked before?

If not, how can I bind my own command that leaves (or restores) the yanked line in the default register?